code
stringlengths
2.5k
150k
kind
stringclasses
1 value
rust Comments Comments ======== All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave *comments* in their source code that the compiler will ignore but people reading the source code may find useful. Here’s a simple comment: ``` #![allow(unused)] fn main() { // hello, world } ``` In Rust, the idiomatic comment style starts a comment with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you’ll need to include `//` on each line, like this: ``` #![allow(unused)] fn main() { // So we’re doing something complicated here, long enough that we need // multiple lines of comments to do it! Whew! Hopefully, this comment will // explain what’s going on. } ``` Comments can also be placed at the end of lines containing code: Filename: src/main.rs ``` fn main() { let lucky_number = 7; // I’m feeling lucky today } ``` But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating: Filename: src/main.rs ``` fn main() { // I’m feeling lucky today let lucky_number = 7; } ``` Rust also has another kind of comment, documentation comments, which we’ll discuss in the “Publishing a Crate to Crates.io” section of Chapter 14. rust Appendix D - Useful Development Tools Appendix D - Useful Development Tools ===================================== In this appendix, we talk about some useful development tools that the Rust project provides. We’ll look at automatic formatting, quick ways to apply warning fixes, a linter, and integrating with IDEs. ### Automatic Formatting with `rustfmt` The `rustfmt` tool reformats your code according to the community code style. Many collaborative projects use `rustfmt` to prevent arguments about which style to use when writing Rust: everyone formats their code using the tool. To install `rustfmt`, enter the following: ``` $ rustup component add rustfmt ``` This command gives you `rustfmt` and `cargo-fmt`, similar to how Rust gives you both `rustc` and `cargo`. To format any Cargo project, enter the following: ``` $ cargo fmt ``` Running this command reformats all the Rust code in the current crate. This should only change the code style, not the code semantics. For more information on `rustfmt`, see [its documentation](https://github.com/rust-lang/rustfmt). ### Fix Your Code with `rustfix` The rustfix tool is included with Rust installations and can automatically fix compiler warnings that have a clear way to correct the problem that’s likely what you want. It’s likely you’ve seen compiler warnings before. For example, consider this code: Filename: src/main.rs ``` fn do_something() {} fn main() { for i in 0..100 { do_something(); } } ``` Here, we’re calling the `do_something` function 100 times, but we never use the variable `i` in the body of the `for` loop. Rust warns us about that: ``` $ cargo build Compiling myprogram v0.1.0 (file:///projects/myprogram) warning: unused variable: `i` --> src/main.rs:4:9 | 4 | for i in 0..100 { | ^ help: consider using `_i` instead | = note: #[warn(unused_variables)] on by default Finished dev [unoptimized + debuginfo] target(s) in 0.50s ``` The warning suggests that we use `_i` as a name instead: the underscore indicates that we intend for this variable to be unused. We can automatically apply that suggestion using the `rustfix` tool by running the command `cargo fix`: ``` $ cargo fix Checking myprogram v0.1.0 (file:///projects/myprogram) Fixing src/main.rs (1 fix) Finished dev [unoptimized + debuginfo] target(s) in 0.59s ``` When we look at *src/main.rs* again, we’ll see that `cargo fix` has changed the code: Filename: src/main.rs ``` fn do_something() {} fn main() { for _i in 0..100 { do_something(); } } ``` The `for` loop variable is now named `_i`, and the warning no longer appears. You can also use the `cargo fix` command to transition your code between different Rust editions. Editions are covered in Appendix E. ### More Lints with Clippy The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code. To install Clippy, enter the following: ``` $ rustup component add clippy ``` To run Clippy’s lints on any Cargo project, enter the following: ``` $ cargo clippy ``` For example, say you write a program that uses an approximation of a mathematical constant, such as pi, as this program does: Filename: src/main.rs ``` fn main() { let x = 3.1415; let r = 8.0; println!("the area of the circle is {}", x * r * r); } ``` Running `cargo clippy` on this project results in this error: ``` error: approximate value of `f{32, 64}::consts::PI` found. Consider using it directly --> src/main.rs:2:13 | 2 | let x = 3.1415; | ^^^^^^ | = note: #[deny(clippy::approx_constant)] on by default = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/master/index.html#approx_constant ``` This error lets you know that Rust already has a more precise `PI` constant defined, and that your program would be more correct if you used the constant instead. You would then change your code to use the `PI` constant. The following code doesn’t result in any errors or warnings from Clippy: Filename: src/main.rs ``` fn main() { let x = std::f64::consts::PI; let r = 8.0; println!("the area of the circle is {}", x * r * r); } ``` For more information on Clippy, see [its documentation](https://github.com/rust-lang/rust-clippy). ### IDE Integration Using `rust-analyzer` To help IDE integration, the Rust community recommends using [`rust-analyzer`](https://rust-analyzer.github.io). This tool is a set of compiler-centric utilities that speaks the [Language Server Protocol](http://langserver.org/), which is a specification for IDEs and programming languages to communicate with each other. Different clients can use `rust-analyzer`, such as [the Rust analyzer plug-in for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). Visit the `rust-analyzer` project’s [home page](https://rust-analyzer.github.io) for installation instructions, then install the language server support in your particular IDE. Your IDE will gain abilities such as autocompletion, jump to definition, and inline errors. rust Running Code on Cleanup with the Drop Trait Running Code on Cleanup with the `Drop` Trait ============================================= The second trait important to the smart pointer pattern is `Drop`, which lets you customize what happens when a value is about to go out of scope. You can provide an implementation for the `Drop` trait on any type, and that code can be used to release resources like files or network connections. We’re introducing `Drop` in the context of smart pointers because the functionality of the `Drop` trait is almost always used when implementing a smart pointer. For example, when a `Box<T>` is dropped it will deallocate the space on the heap that the box points to. In some languages, for some types, the programmer must call code to free memory or resources every time they finish using an instance of those types. Examples include file handles, sockets, or locks. If they forget, the system might become overloaded and crash. In Rust, you can specify that a particular bit of code be run whenever a value goes out of scope, and the compiler will insert this code automatically. As a result, you don’t need to be careful about placing cleanup code everywhere in a program that an instance of a particular type is finished with—you still won’t leak resources! You specify the code to run when a value goes out of scope by implementing the `Drop` trait. The `Drop` trait requires you to implement one method named `drop` that takes a mutable reference to `self`. To see when Rust calls `drop`, let’s implement `drop` with `println!` statements for now. Listing 15-14 shows a `CustomSmartPointer` struct whose only custom functionality is that it will print `Dropping CustomSmartPointer!` when the instance goes out of scope, to show when Rust runs the `drop` function. Filename: src/main.rs ``` struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } fn main() { let c = CustomSmartPointer { data: String::from("my stuff"), }; let d = CustomSmartPointer { data: String::from("other stuff"), }; println!("CustomSmartPointers created."); } ``` Listing 15-14: A `CustomSmartPointer` struct that implements the `Drop` trait where we would put our cleanup code The `Drop` trait is included in the prelude, so we don’t need to bring it into scope. We implement the `Drop` trait on `CustomSmartPointer` and provide an implementation for the `drop` method that calls `println!`. The body of the `drop` function is where you would place any logic that you wanted to run when an instance of your type goes out of scope. We’re printing some text here to demonstrate visually when Rust will call `drop`. In `main`, we create two instances of `CustomSmartPointer` and then print `CustomSmartPointers created`. At the end of `main`, our instances of `CustomSmartPointer` will go out of scope, and Rust will call the code we put in the `drop` method, printing our final message. Note that we didn’t need to call the `drop` method explicitly. When we run this program, we’ll see the following output: ``` $ cargo run Compiling drop-example v0.1.0 (file:///projects/drop-example) Finished dev [unoptimized + debuginfo] target(s) in 0.60s Running `target/debug/drop-example` CustomSmartPointers created. Dropping CustomSmartPointer with data `other stuff`! Dropping CustomSmartPointer with data `my stuff`! ``` Rust automatically called `drop` for us when our instances went out of scope, calling the code we specified. Variables are dropped in the reverse order of their creation, so `d` was dropped before `c`. This example's purpose is to give you a visual guide to how the `drop` method works; usually you would specify the cleanup code that your type needs to run rather than a print message. ### Dropping a Value Early with `std::mem::drop` Unfortunately, it’s not straightforward to disable the automatic `drop` functionality. Disabling `drop` isn’t usually necessary; the whole point of the `Drop` trait is that it’s taken care of automatically. Occasionally, however, you might want to clean up a value early. One example is when using smart pointers that manage locks: you might want to force the `drop` method that releases the lock so that other code in the same scope can acquire the lock. Rust doesn’t let you call the `Drop` trait’s `drop` method manually; instead you have to call the `std::mem::drop` function provided by the standard library if you want to force a value to be dropped before the end of its scope. If we try to call the `Drop` trait’s `drop` method manually by modifying the `main` function from Listing 15-14, as shown in Listing 15-15, we’ll get a compiler error: Filename: src/main.rs ``` struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } fn main() { let c = CustomSmartPointer { data: String::from("some data"), }; println!("CustomSmartPointer created."); c.drop(); println!("CustomSmartPointer dropped before the end of main."); } ``` Listing 15-15: Attempting to call the `drop` method from the `Drop` trait manually to clean up early When we try to compile this code, we’ll get this error: ``` $ cargo run Compiling drop-example v0.1.0 (file:///projects/drop-example) error[E0040]: explicit use of destructor method --> src/main.rs:16:7 | 16 | c.drop(); | --^^^^-- | | | | | explicit destructor calls not allowed | help: consider using `drop` function: `drop(c)` For more information about this error, try `rustc --explain E0040`. error: could not compile `drop-example` due to previous error ``` This error message states that we’re not allowed to explicitly call `drop`. The error message uses the term *destructor*, which is the general programming term for a function that cleans up an instance. A *destructor* is analogous to a *constructor*, which creates an instance. The `drop` function in Rust is one particular destructor. Rust doesn’t let us call `drop` explicitly because Rust would still automatically call `drop` on the value at the end of `main`. This would cause a *double free* error because Rust would be trying to clean up the same value twice. We can’t disable the automatic insertion of `drop` when a value goes out of scope, and we can’t call the `drop` method explicitly. So, if we need to force a value to be cleaned up early, we use the `std::mem::drop` function. The `std::mem::drop` function is different from the `drop` method in the `Drop` trait. We call it by passing as an argument the value we want to force drop. The function is in the prelude, so we can modify `main` in Listing 15-15 to call the `drop` function, as shown in Listing 15-16: Filename: src/main.rs ``` struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } fn main() { let c = CustomSmartPointer { data: String::from("some data"), }; println!("CustomSmartPointer created."); drop(c); println!("CustomSmartPointer dropped before the end of main."); } ``` Listing 15-16: Calling `std::mem::drop` to explicitly drop a value before it goes out of scope Running this code will print the following: ``` $ cargo run Compiling drop-example v0.1.0 (file:///projects/drop-example) Finished dev [unoptimized + debuginfo] target(s) in 0.73s Running `target/debug/drop-example` CustomSmartPointer created. Dropping CustomSmartPointer with data `some data`! CustomSmartPointer dropped before the end of main. ``` The text `Dropping CustomSmartPointer with data `some data`!` is printed between the `CustomSmartPointer created.` and `CustomSmartPointer dropped before the end of main.` text, showing that the `drop` method code is called to drop `c` at that point. You can use code specified in a `Drop` trait implementation in many ways to make cleanup convenient and safe: for instance, you could use it to create your own memory allocator! With the `Drop` trait and Rust’s ownership system, you don’t have to remember to clean up because Rust does it automatically. You also don’t have to worry about problems resulting from accidentally cleaning up values still in use: the ownership system that makes sure references are always valid also ensures that `drop` gets called only once when the value is no longer being used. Now that we’ve examined `Box<T>` and some of the characteristics of smart pointers, let’s look at a few other smart pointers defined in the standard library. rust Using Structs to Structure Related Data Using Structs to Structure Related Data ======================================= A *struct*, or *structure*, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. If you’re familiar with an object-oriented language, a *struct* is like an object’s data attributes. In this chapter, we’ll compare and contrast tuples with structs to build on what you already know and demonstrate when structs are a better way to group data. We’ll demonstrate how to define and instantiate structs. We’ll discuss how to define associated functions, especially the kind of associated functions called *methods*, to specify behavior associated with a struct type. Structs and enums (discussed in Chapter 6) are the building blocks for creating new types in your program’s domain to take full advantage of Rust’s compile time type checking. rust Refutability: Whether a Pattern Might Fail to Match Refutability: Whether a Pattern Might Fail to Match =================================================== Patterns come in two forms: refutable and irrefutable. Patterns that will match for any possible value passed are *irrefutable*. An example would be `x` in the statement `let x = 5;` because `x` matches anything and therefore cannot fail to match. Patterns that can fail to match for some possible value are *refutable*. An example would be `Some(x)` in the expression `if let Some(x) = a_value` because if the value in the `a_value` variable is `None` rather than `Some`, the `Some(x)` pattern will not match. Function parameters, `let` statements, and `for` loops can only accept irrefutable patterns, because the program cannot do anything meaningful when values don’t match. The `if let` and `while let` expressions accept refutable and irrefutable patterns, but the compiler warns against irrefutable patterns because by definition they’re intended to handle possible failure: the functionality of a conditional is in its ability to perform differently depending on success or failure. In general, you shouldn’t have to worry about the distinction between refutable and irrefutable patterns; however, you do need to be familiar with the concept of refutability so you can respond when you see it in an error message. In those cases, you’ll need to change either the pattern or the construct you’re using the pattern with, depending on the intended behavior of the code. Let’s look at an example of what happens when we try to use a refutable pattern where Rust requires an irrefutable pattern and vice versa. Listing 18-8 shows a `let` statement, but for the pattern we’ve specified `Some(x)`, a refutable pattern. As you might expect, this code will not compile. ``` fn main() { let some_option_value: Option<i32> = None; let Some(x) = some_option_value; } ``` Listing 18-8: Attempting to use a refutable pattern with `let` If `some_option_value` was a `None` value, it would fail to match the pattern `Some(x)`, meaning the pattern is refutable. However, the `let` statement can only accept an irrefutable pattern because there is nothing valid the code can do with a `None` value. At compile time, Rust will complain that we’ve tried to use a refutable pattern where an irrefutable pattern is required: ``` $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) error[E0005]: refutable pattern in local binding: `None` not covered --> src/main.rs:3:9 | 3 | let Some(x) = some_option_value; | ^^^^^^^ pattern `None` not covered | = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html note: `Option<i32>` defined here = note: the matched value is of type `Option<i32>` help: you might want to use `if let` to ignore the variant that isn't matched | 3 | let x = if let Some(x) = some_option_value { x } else { todo!() }; | ++++++++++ ++++++++++++++++++++++ For more information about this error, try `rustc --explain E0005`. error: could not compile `patterns` due to previous error ``` Because we didn’t cover (and couldn’t cover!) every valid value with the pattern `Some(x)`, Rust rightfully produces a compiler error. If we have a refutable pattern where an irrefutable pattern is needed, we can fix it by changing the code that uses the pattern: instead of using `let`, we can use `if let`. Then if the pattern doesn’t match, the code will just skip the code in the curly brackets, giving it a way to continue validly. Listing 18-9 shows how to fix the code in Listing 18-8. ``` fn main() { let some_option_value: Option<i32> = None; if let Some(x) = some_option_value { println!("{}", x); } } ``` Listing 18-9: Using `if let` and a block with refutable patterns instead of `let` We’ve given the code an out! This code is perfectly valid, although it means we cannot use an irrefutable pattern without receiving an error. If we give `if let` a pattern that will always match, such as `x`, as shown in Listing 18-10, the compiler will give a warning. ``` fn main() { if let x = 5 { println!("{}", x); }; } ``` Listing 18-10: Attempting to use an irrefutable pattern with `if let` Rust complains that it doesn’t make sense to use `if let` with an irrefutable pattern: ``` $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) warning: irrefutable `if let` pattern --> src/main.rs:2:8 | 2 | if let x = 5 { | ^^^^^^^^^ | = note: `#[warn(irrefutable_let_patterns)]` on by default = note: this pattern will always match, so the `if let` is useless = help: consider replacing the `if let` with a `let` warning: `patterns` (bin "patterns") generated 1 warning Finished dev [unoptimized + debuginfo] target(s) in 0.39s Running `target/debug/patterns` 5 ``` For this reason, match arms must use refutable patterns, except for the last arm, which should match any remaining values with an irrefutable pattern. Rust allows us to use an irrefutable pattern in a `match` with only one arm, but this syntax isn’t particularly useful and could be replaced with a simpler `let` statement. Now that you know where to use patterns and the difference between refutable and irrefutable patterns, let’s cover all the syntax we can use to create patterns.
programming_docs
rust Writing Automated Tests Writing Automated Tests ======================= In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that “Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.” That doesn’t mean we shouldn’t try to test as much as we can! Correctness in our programs is the extent to which our code does what we intend it to do. Rust is designed with a high degree of concern about the correctness of programs, but correctness is complex and not easy to prove. Rust’s type system shoulders a huge part of this burden, but the type system cannot catch everything. As such, Rust includes support for writing automated software tests. Say we write a function `add_two` that adds 2 to whatever number is passed to it. This function’s signature accepts an integer as a parameter and returns an integer as a result. When we implement and compile that function, Rust does all the type checking and borrow checking that you’ve learned so far to ensure that, for instance, we aren’t passing a `String` value or an invalid reference to this function. But Rust *can’t* check that this function will do precisely what we intend, which is return the parameter plus 2 rather than, say, the parameter plus 10 or the parameter minus 50! That’s where tests come in. We can write tests that assert, for example, that when we pass `3` to the `add_two` function, the returned value is `5`. We can run these tests whenever we make changes to our code to make sure any existing correct behavior has not changed. Testing is a complex skill: although we can’t cover every detail about how to write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing facilities. We’ll talk about the annotations and macros available to you when writing your tests, the default behavior and options provided for running your tests, and how to organize tests into unit tests and integration tests. rust Rc<T>, the Reference Counted Smart Pointer `Rc<T>`, the Reference Counted Smart Pointer ============================================= In the majority of cases, ownership is clear: you know exactly which variable owns a given value. However, there are cases when a single value might have multiple owners. For example, in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it. A node shouldn’t be cleaned up unless it doesn’t have any edges pointing to it and so has no owners. You have to enable multiple ownership explicitly by using the Rust type `Rc<T>`, which is an abbreviation for *reference counting*. The `Rc<T>` type keeps track of the number of references to a value to determine whether or not the value is still in use. If there are zero references to a value, the value can be cleaned up without any references becoming invalid. Imagine `Rc<T>` as a TV in a family room. When one person enters to watch TV, they turn it on. Others can come into the room and watch the TV. When the last person leaves the room, they turn off the TV because it’s no longer being used. If someone turns off the TV while others are still watching it, there would be uproar from the remaining TV watchers! We use the `Rc<T>` type when we want to allocate some data on the heap for multiple parts of our program to read and we can’t determine at compile time which part will finish using the data last. If we knew which part would finish last, we could just make that part the data’s owner, and the normal ownership rules enforced at compile time would take effect. Note that `Rc<T>` is only for use in single-threaded scenarios. When we discuss concurrency in Chapter 16, we’ll cover how to do reference counting in multithreaded programs. ### Using `Rc<T>` to Share Data Let’s return to our cons list example in Listing 15-5. Recall that we defined it using `Box<T>`. This time, we’ll create two lists that both share ownership of a third list. Conceptually, this looks similar to Figure 15-3: Figure 15-3: Two lists, `b` and `c`, sharing ownership of a third list, `a` We’ll create list `a` that contains 5 and then 10. Then we’ll make two more lists: `b` that starts with 3 and `c` that starts with 4. Both `b` and `c` lists will then continue on to the first `a` list containing 5 and 10. In other words, both lists will share the first list containing 5 and 10. Trying to implement this scenario using our definition of `List` with `Box<T>` won’t work, as shown in Listing 15-17: Filename: src/main.rs ``` enum List { Cons(i32, Box<List>), Nil, } use crate::List::{Cons, Nil}; fn main() { let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); let b = Cons(3, Box::new(a)); let c = Cons(4, Box::new(a)); } ``` Listing 15-17: Demonstrating we’re not allowed to have two lists using `Box<T>` that try to share ownership of a third list When we compile this code, we get this error: ``` $ cargo run Compiling cons-list v0.1.0 (file:///projects/cons-list) error[E0382]: use of moved value: `a` --> src/main.rs:11:30 | 9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); | - move occurs because `a` has type `List`, which does not implement the `Copy` trait 10 | let b = Cons(3, Box::new(a)); | - value moved here 11 | let c = Cons(4, Box::new(a)); | ^ value used here after move For more information about this error, try `rustc --explain E0382`. error: could not compile `cons-list` due to previous error ``` The `Cons` variants own the data they hold, so when we create the `b` list, `a` is moved into `b` and `b` owns `a`. Then, when we try to use `a` again when creating `c`, we’re not allowed to because `a` has been moved. We could change the definition of `Cons` to hold references instead, but then we would have to specify lifetime parameters. By specifying lifetime parameters, we would be specifying that every element in the list will live at least as long as the entire list. This is the case for the elements and lists in Listing 15-17, but not in every scenario. Instead, we’ll change our definition of `List` to use `Rc<T>` in place of `Box<T>`, as shown in Listing 15-18. Each `Cons` variant will now hold a value and an `Rc<T>` pointing to a `List`. When we create `b`, instead of taking ownership of `a`, we’ll clone the `Rc<List>` that `a` is holding, thereby increasing the number of references from one to two and letting `a` and `b` share ownership of the data in that `Rc<List>`. We’ll also clone `a` when creating `c`, increasing the number of references from two to three. Every time we call `Rc::clone`, the reference count to the data within the `Rc<List>` will increase, and the data won’t be cleaned up unless there are zero references to it. Filename: src/main.rs ``` enum List { Cons(i32, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); let c = Cons(4, Rc::clone(&a)); } ``` Listing 15-18: A definition of `List` that uses `Rc<T>` We need to add a `use` statement to bring `Rc<T>` into scope because it’s not in the prelude. In `main`, we create the list holding 5 and 10 and store it in a new `Rc<List>` in `a`. Then when we create `b` and `c`, we call the `Rc::clone` function and pass a reference to the `Rc<List>` in `a` as an argument. We could have called `a.clone()` rather than `Rc::clone(&a)`, but Rust’s convention is to use `Rc::clone` in this case. The implementation of `Rc::clone` doesn’t make a deep copy of all the data like most types’ implementations of `clone` do. The call to `Rc::clone` only increments the reference count, which doesn’t take much time. Deep copies of data can take a lot of time. By using `Rc::clone` for reference counting, we can visually distinguish between the deep-copy kinds of clones and the kinds of clones that increase the reference count. When looking for performance problems in the code, we only need to consider the deep-copy clones and can disregard calls to `Rc::clone`. ### Cloning an `Rc<T>` Increases the Reference Count Let’s change our working example in Listing 15-18 so we can see the reference counts changing as we create and drop references to the `Rc<List>` in `a`. In Listing 15-19, we’ll change `main` so it has an inner scope around list `c`; then we can see how the reference count changes when `c` goes out of scope. Filename: src/main.rs ``` enum List { Cons(i32, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cons(3, Rc::clone(&a)); println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cons(4, Rc::clone(&a)); println!("count after creating c = {}", Rc::strong_count(&a)); } println!("count after c goes out of scope = {}", Rc::strong_count(&a)); } ``` Listing 15-19: Printing the reference count At each point in the program where the reference count changes, we print the reference count, which we get by calling the `Rc::strong_count` function. This function is named `strong_count` rather than `count` because the `Rc<T>` type also has a `weak_count`; we’ll see what `weak_count` is used for in the [“Preventing Reference Cycles: Turning an `Rc<T>` into a `Weak<T>`”](ch15-06-reference-cycles#preventing-reference-cycles-turning-an-rct-into-a-weakt) section. This code prints the following: ``` $ cargo run Compiling cons-list v0.1.0 (file:///projects/cons-list) Finished dev [unoptimized + debuginfo] target(s) in 0.45s Running `target/debug/cons-list` count after creating a = 1 count after creating b = 2 count after creating c = 3 count after c goes out of scope = 2 ``` We can see that the `Rc<List>` in `a` has an initial reference count of 1; then each time we call `clone`, the count goes up by 1. When `c` goes out of scope, the count goes down by 1. We don’t have to call a function to decrease the reference count like we have to call `Rc::clone` to increase the reference count: the implementation of the `Drop` trait decreases the reference count automatically when an `Rc<T>` value goes out of scope. What we can’t see in this example is that when `b` and then `a` go out of scope at the end of `main`, the count is then 0, and the `Rc<List>` is cleaned up completely. Using `Rc<T>` allows a single value to have multiple owners, and the count ensures that the value remains valid as long as any of the owners still exist. Via immutable references, `Rc<T>` allows you to share data between multiple parts of your program for reading only. If `Rc<T>` allowed you to have multiple mutable references too, you might violate one of the borrowing rules discussed in Chapter 4: multiple mutable borrows to the same place can cause data races and inconsistencies. But being able to mutate data is very useful! In the next section, we’ll discuss the interior mutability pattern and the `RefCell<T>` type that you can use in conjunction with an `Rc<T>` to work with this immutability restriction. rust Paths for Referring to an Item in the Module Tree Paths for Referring to an Item in the Module Tree ================================================= To show Rust where to find an item in a module tree, we use a path in the same way we use a path when navigating a filesystem. To call a function, we need to know its path. A path can take two forms: * An *absolute path* is the full path starting from a crate root; for code from an external crate, the absolute path begins with the crate name, and for code from the current crate, it starts with the literal `crate`. * A *relative path* starts from the current module and uses `self`, `super`, or an identifier in the current module. Both absolute and relative paths are followed by one or more identifiers separated by double colons (`::`). Returning to Listing 7-1, say we want to call the `add_to_waitlist` function. This is the same as asking: what’s the path of the `add_to_waitlist` function? Listing 7-3 contains Listing 7-1 with some of the modules and functions removed. We’ll show two ways to call the `add_to_waitlist` function from a new function `eat_at_restaurant` defined in the crate root. These paths are correct, but there’s another problem remaining that will prevent this example from compiling as-is. We’ll explain why in a bit. The `eat_at_restaurant` function is part of our library crate’s public API, so we mark it with the `pub` keyword. In the [“Exposing Paths with the `pub` Keyword”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree#exposing-paths-with-the-pub-keyword) section, we’ll go into more detail about `pub`. Filename: src/lib.rs ``` mod front_of_house { mod hosting { fn add_to_waitlist() {} } } pub fn eat_at_restaurant() { // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // Relative path front_of_house::hosting::add_to_waitlist(); } ``` Listing 7-3: Calling the `add_to_waitlist` function using absolute and relative paths The first time we call the `add_to_waitlist` function in `eat_at_restaurant`, we use an absolute path. The `add_to_waitlist` function is defined in the same crate as `eat_at_restaurant`, which means we can use the `crate` keyword to start an absolute path. We then include each of the successive modules until we make our way to `add_to_waitlist`. You can imagine a filesystem with the same structure: we’d specify the path `/front_of_house/hosting/add_to_waitlist` to run the `add_to_waitlist` program; using the `crate` name to start from the crate root is like using `/` to start from the filesystem root in your shell. The second time we call `add_to_waitlist` in `eat_at_restaurant`, we use a relative path. The path starts with `front_of_house`, the name of the module defined at the same level of the module tree as `eat_at_restaurant`. Here the filesystem equivalent would be using the path `front_of_house/hosting/add_to_waitlist`. Starting with a module name means that the path is relative. Choosing whether to use a relative or absolute path is a decision you’ll make based on your project, and depends on whether you’re more likely to move item definition code separately from or together with the code that uses the item. For example, if we move the `front_of_house` module and the `eat_at_restaurant` function into a module named `customer_experience`, we’d need to update the absolute path to `add_to_waitlist`, but the relative path would still be valid. However, if we moved the `eat_at_restaurant` function separately into a module named `dining`, the absolute path to the `add_to_waitlist` call would stay the same, but the relative path would need to be updated. Our preference in general is to specify absolute paths because it’s more likely we’ll want to move code definitions and item calls independently of each other. Let’s try to compile Listing 7-3 and find out why it won’t compile yet! The error we get is shown in Listing 7-4. ``` $ cargo build Compiling restaurant v0.1.0 (file:///projects/restaurant) error[E0603]: module `hosting` is private --> src/lib.rs:9:28 | 9 | crate::front_of_house::hosting::add_to_waitlist(); | ^^^^^^^ private module | note: the module `hosting` is defined here --> src/lib.rs:2:5 | 2 | mod hosting { | ^^^^^^^^^^^ error[E0603]: module `hosting` is private --> src/lib.rs:12:21 | 12 | front_of_house::hosting::add_to_waitlist(); | ^^^^^^^ private module | note: the module `hosting` is defined here --> src/lib.rs:2:5 | 2 | mod hosting { | ^^^^^^^^^^^ For more information about this error, try `rustc --explain E0603`. error: could not compile `restaurant` due to 2 previous errors ``` Listing 7-4: Compiler errors from building the code in Listing 7-3 The error messages say that module `hosting` is private. In other words, we have the correct paths for the `hosting` module and the `add_to_waitlist` function, but Rust won’t let us use them because it doesn’t have access to the private sections. In Rust, all items (functions, methods, structs, enums, modules, and constants) are private to parent modules by default. If you want to make an item like a function or struct private, you put it in a module. Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules. This is because child modules wrap and hide their implementation details, but the child modules can see the context in which they’re defined. To continue with our metaphor, think of the privacy rules as being like the back office of a restaurant: what goes on in there is private to restaurant customers, but office managers can see and do everything in the restaurant they operate. Rust chose to have the module system function this way so that hiding inner implementation details is the default. That way, you know which parts of the inner code you can change without breaking outer code. However, Rust does give you the option to expose inner parts of child modules’ code to outer ancestor modules by using the `pub` keyword to make an item public. ### Exposing Paths with the `pub` Keyword Let’s return to the error in Listing 7-4 that told us the `hosting` module is private. We want the `eat_at_restaurant` function in the parent module to have access to the `add_to_waitlist` function in the child module, so we mark the `hosting` module with the `pub` keyword, as shown in Listing 7-5. Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { fn add_to_waitlist() {} } } pub fn eat_at_restaurant() { // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // Relative path front_of_house::hosting::add_to_waitlist(); } ``` Listing 7-5: Declaring the `hosting` module as `pub` to use it from `eat_at_restaurant` Unfortunately, the code in Listing 7-5 still results in an error, as shown in Listing 7-6. ``` $ cargo build Compiling restaurant v0.1.0 (file:///projects/restaurant) error[E0603]: function `add_to_waitlist` is private --> src/lib.rs:9:37 | 9 | crate::front_of_house::hosting::add_to_waitlist(); | ^^^^^^^^^^^^^^^ private function | note: the function `add_to_waitlist` is defined here --> src/lib.rs:3:9 | 3 | fn add_to_waitlist() {} | ^^^^^^^^^^^^^^^^^^^^ error[E0603]: function `add_to_waitlist` is private --> src/lib.rs:12:30 | 12 | front_of_house::hosting::add_to_waitlist(); | ^^^^^^^^^^^^^^^ private function | note: the function `add_to_waitlist` is defined here --> src/lib.rs:3:9 | 3 | fn add_to_waitlist() {} | ^^^^^^^^^^^^^^^^^^^^ For more information about this error, try `rustc --explain E0603`. error: could not compile `restaurant` due to 2 previous errors ``` Listing 7-6: Compiler errors from building the code in Listing 7-5 What happened? Adding the `pub` keyword in front of `mod hosting` makes the module public. With this change, if we can access `front_of_house`, we can access `hosting`. But the *contents* of `hosting` are still private; making the module public doesn’t make its contents public. The `pub` keyword on a module only lets code in its ancestor modules refer to it, not access its inner code. Because modules are containers, there’s not much we can do by only making the module public; we need to go further and choose to make one or more of the items within the module public as well. The errors in Listing 7-6 say that the `add_to_waitlist` function is private. The privacy rules apply to structs, enums, functions, and methods as well as modules. Let’s also make the `add_to_waitlist` function public by adding the `pub` keyword before its definition, as in Listing 7-7. Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub fn eat_at_restaurant() { // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // Relative path front_of_house::hosting::add_to_waitlist(); } ``` Listing 7-7: Adding the `pub` keyword to `mod hosting` and `fn add_to_waitlist` lets us call the function from `eat_at_restaurant` Now the code will compile! To see why adding the `pub` keyword lets us use these paths in `add_to_waitlist` with respect to the privacy rules, let’s look at the absolute and the relative paths. In the absolute path, we start with `crate`, the root of our crate’s module tree. The `front_of_house` module is defined in the crate root. While `front_of_house` isn’t public, because the `eat_at_restaurant` function is defined in the same module as `front_of_house` (that is, `eat_at_restaurant` and `front_of_house` are siblings), we can refer to `front_of_house` from `eat_at_restaurant`. Next is the `hosting` module marked with `pub`. We can access the parent module of `hosting`, so we can access `hosting`. Finally, the `add_to_waitlist` function is marked with `pub` and we can access its parent module, so this function call works! In the relative path, the logic is the same as the absolute path except for the first step: rather than starting from the crate root, the path starts from `front_of_house`. The `front_of_house` module is defined within the same module as `eat_at_restaurant`, so the relative path starting from the module in which `eat_at_restaurant` is defined works. Then, because `hosting` and `add_to_waitlist` are marked with `pub`, the rest of the path works, and this function call is valid! If you plan on sharing your library crate so other projects can use your code, your public API is your contract with users of your crate that determines how they can interact with your code. There are many considerations around managing changes to your public API to make it easier for people to depend on your crate. These considerations are out of the scope of this book; if you’re interested in this topic, see [The Rust API Guidelines](https://rust-lang.github.io/api-guidelines/). > #### Best Practices for Packages with a Binary and a Library > > We mentioned a package can contain both a *src/main.rs* binary crate root as well as a *src/lib.rs* library crate root, and both crates will have the package name by default. Typically, packages with this pattern of containing both a library and a binary crate will have just enough code in the binary crate to start an executable that calls code with the library crate. This lets other projects benefit from the most functionality that the package provides, because the library crate’s code can be shared. > > The module tree should be defined in *src/lib.rs*. Then, any public items can be used in the binary crate by starting paths with the name of the package. The binary crate becomes a user of the library crate just like a completely external crate would use the library crate: it can only use the public API. This helps you design a good API; not only are you the author, you’re also a client! > > In [Chapter 12](ch12-00-an-io-project), we’ll demonstrate this organizational practice with a command-line program that will contain both a binary crate and a library crate. > > ### Starting Relative Paths with `super` We can construct relative paths that begin in the parent module, rather than the current module or the crate root, by using `super` at the start of the path. This is like starting a filesystem path with the `..` syntax. Using `super` allows us to reference an item that we know is in the parent module, which can make rearranging the module tree easier when the module is closely related to the parent, but the parent might be moved elsewhere in the module tree someday. Consider the code in Listing 7-8 that models the situation in which a chef fixes an incorrect order and personally brings it out to the customer. The function `fix_incorrect_order` defined in the `back_of_house` module calls the function `deliver_order` defined in the parent module by specifying the path to `deliver_order` starting with `super`: Filename: src/lib.rs ``` fn deliver_order() {} mod back_of_house { fn fix_incorrect_order() { cook_order(); super::deliver_order(); } fn cook_order() {} } ``` Listing 7-8: Calling a function using a relative path starting with `super` The `fix_incorrect_order` function is in the `back_of_house` module, so we can use `super` to go to the parent module of `back_of_house`, which in this case is `crate`, the root. From there, we look for `deliver_order` and find it. Success! We think the `back_of_house` module and the `deliver_order` function are likely to stay in the same relationship to each other and get moved together should we decide to reorganize the crate’s module tree. Therefore, we used `super` so we’ll have fewer places to update code in the future if this code gets moved to a different module. ### Making Structs and Enums Public We can also use `pub` to designate structs and enums as public, but there are a few details extra to the usage of `pub` with structs and enums. If we use `pub` before a struct definition, we make the struct public, but the struct’s fields will still be private. We can make each field public or not on a case-by-case basis. In Listing 7-9, we’ve defined a public `back_of_house::Breakfast` struct with a public `toast` field but a private `seasonal_fruit` field. This models the case in a restaurant where the customer can pick the type of bread that comes with a meal, but the chef decides which fruit accompanies the meal based on what’s in season and in stock. The available fruit changes quickly, so customers can’t choose the fruit or even see which fruit they’ll get. Filename: src/lib.rs ``` mod back_of_house { pub struct Breakfast { pub toast: String, seasonal_fruit: String, } impl Breakfast { pub fn summer(toast: &str) -> Breakfast { Breakfast { toast: String::from(toast), seasonal_fruit: String::from("peaches"), } } } } pub fn eat_at_restaurant() { // Order a breakfast in the summer with Rye toast let mut meal = back_of_house::Breakfast::summer("Rye"); // Change our mind about what bread we'd like meal.toast = String::from("Wheat"); println!("I'd like {} toast please", meal.toast); // The next line won't compile if we uncomment it; we're not allowed // to see or modify the seasonal fruit that comes with the meal // meal.seasonal_fruit = String::from("blueberries"); } ``` Listing 7-9: A struct with some public fields and some private fields Because the `toast` field in the `back_of_house::Breakfast` struct is public, in `eat_at_restaurant` we can write and read to the `toast` field using dot notation. Notice that we can’t use the `seasonal_fruit` field in `eat_at_restaurant` because `seasonal_fruit` is private. Try uncommenting the line modifying the `seasonal_fruit` field value to see what error you get! Also, note that because `back_of_house::Breakfast` has a private field, the struct needs to provide a public associated function that constructs an instance of `Breakfast` (we’ve named it `summer` here). If `Breakfast` didn’t have such a function, we couldn’t create an instance of `Breakfast` in `eat_at_restaurant` because we couldn’t set the value of the private `seasonal_fruit` field in `eat_at_restaurant`. In contrast, if we make an enum public, all of its variants are then public. We only need the `pub` before the `enum` keyword, as shown in Listing 7-10. Filename: src/lib.rs ``` mod back_of_house { pub enum Appetizer { Soup, Salad, } } pub fn eat_at_restaurant() { let order1 = back_of_house::Appetizer::Soup; let order2 = back_of_house::Appetizer::Salad; } ``` Listing 7-10: Designating an enum as public makes all its variants public Because we made the `Appetizer` enum public, we can use the `Soup` and `Salad` variants in `eat_at_restaurant`. Enums aren’t very useful unless their variants are public; it would be annoying to have to annotate all enum variants with `pub` in every case, so the default for enum variants is to be public. Structs are often useful without their fields being public, so struct fields follow the general rule of everything being private by default unless annotated with `pub`. There’s one more situation involving `pub` that we haven’t covered, and that is our last module system feature: the `use` keyword. We’ll cover `use` by itself first, and then we’ll show how to combine `pub` and `use`.
programming_docs
rust Installation Installation ============ The first step is to install Rust. We’ll download Rust through `rustup`, a command line tool for managing Rust versions and associated tools. You’ll need an internet connection for the download. > Note: If you prefer not to use `rustup` for some reason, please see the [Other Rust Installation Methods page](https://forge.rust-lang.org/infra/other-installation-methods.html) for more options. > > The following steps install the latest stable version of the Rust compiler. Rust’s stability guarantees ensure that all the examples in the book that compile will continue to compile with newer Rust versions. The output might differ slightly between versions, because Rust often improves error messages and warnings. In other words, any newer, stable version of Rust you install using these steps should work as expected with the content of this book. > ### Command Line Notation > > In this chapter and throughout the book, we’ll show some commands used in the terminal. Lines that you should enter in a terminal all start with `$`. You don’t need to type in the `$` character; it’s the command line prompt shown to indicate the start of each command. Lines that don’t start with `$` typically show the output of the previous command. Additionally, PowerShell-specific examples will use `>` rather than `$`. > > ### Installing `rustup` on Linux or macOS If you’re using Linux or macOS, open a terminal and enter the following command: ``` $ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh ``` The command downloads a script and starts the installation of the `rustup` tool, which installs the latest stable version of Rust. You might be prompted for your password. If the install is successful, the following line will appear: ``` Rust is installed now. Great! ``` You will also need a *linker*, which is a program that Rust uses to join its compiled outputs into one file. It is likely you already have one. If you get linker errors, you should install a C compiler, which will typically include a linker. A C compiler is also useful because some common Rust packages depend on C code and will need a C compiler. On macOS, you can get a C compiler by running: ``` $ xcode-select --install ``` Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the `build-essential` package. ### Installing `rustup` on Windows On Windows, go to <https://www.rust-lang.org/tools/install> and follow the instructions for installing Rust. At some point in the installation, you’ll receive a message explaining that you’ll also need the MSVC build tools for Visual Studio 2013 or later. To acquire the build tools, you’ll need to install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/). When asked which workloads to install, include: * “Desktop Development with C++” * The Windows 10 or 11 SDK * The English language pack component, along with any other language pack of your choosing The rest of this book uses commands that work in both *cmd.exe* and PowerShell. If there are specific differences, we’ll explain which to use. ### Troubleshooting To check whether you have Rust installed correctly, open a shell and enter this line: ``` $ rustc --version ``` You should see the version number, commit hash, and commit date for the latest stable version that has been released in the following format: ``` rustc x.y.z (abcabcabc yyyy-mm-dd) ``` If you see this information, you have installed Rust successfully! If you don’t see this information, check that Rust is in your `%PATH%` system variable as follows. In Windows CMD, use: ``` > echo %PATH% ``` In PowerShell, use: ``` > echo $env:Path ``` In Linux and macOS, use: ``` echo $PATH ``` If that’s all correct and Rust still isn’t working, there are a number of places you can get help. The easiest is the #beginners channel on [the official Rust Discord](https://discord.gg/rust-lang). There, you can chat with other Rustaceans (a silly nickname we call ourselves) who can help you out. Other great resources include [the Users forum](https://users.rust-lang.org/) and [Stack Overflow](https://stackoverflow.com/questions/tagged/rust). ### Updating and Uninstalling Once Rust is installed via `rustup`, when a new version of Rust is released, updating to the latest version is easy. From your shell, run the following update script: ``` $ rustup update ``` To uninstall Rust and `rustup`, run the following uninstall script from your shell: ``` $ rustup self uninstall ``` ### Local Documentation The installation of Rust also includes a local copy of the documentation, so you can read it offline. Run `rustup doc` to open the local documentation in your browser. Any time a type or function is provided by the standard library and you’re not sure what it does or how to use it, use the application programming interface (API) documentation to find out! rust Developing the Library’s Functionality with Test-Driven Development Developing the Library’s Functionality with Test-Driven Development =================================================================== Now that we’ve extracted the logic into *src/lib.rs* and left the argument collecting and error handling in *src/main.rs*, it’s much easier to write tests for the core functionality of our code. We can call functions directly with various arguments and check return values without having to call our binary from the command line. In this section, we’ll add the searching logic to the `minigrep` program using the test-driven development (TDD) process with the following steps: 1. Write a test that fails and run it to make sure it fails for the reason you expect. 2. Write or modify just enough code to make the new test pass. 3. Refactor the code you just added or changed and make sure the tests continue to pass. 4. Repeat from step 1! Though it’s just one of many ways to write software, TDD can help drive code design. Writing the test before you write the code that makes the test pass helps to maintain high test coverage throughout the process. We’ll test drive the implementation of the functionality that will actually do the searching for the query string in the file contents and produce a list of lines that match the query. We’ll add this functionality in a function called `search`. ### Writing a Failing Test Because we don’t need them anymore, let’s remove the `println!` statements from *src/lib.rs* and *src/main.rs* that we used to check the program’s behavior. Then, in *src/lib.rs*, add a `tests` module with a test function, as we did in [Chapter 11](ch11-01-writing-tests#the-anatomy-of-a-test-function). The test function specifies the behavior we want the `search` function to have: it will take a query and the text to search, and it will return only the lines from the text that contain the query. Listing 12-15 shows this test, which won’t compile yet. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 12-15: Creating a failing test for the `search` function we wish we had This test searches for the string `"duct"`. The text we’re searching is three lines, only one of which contains `"duct"` (Note that the backslash after the opening double quote tells Rust not to put a newline character at the beginning of the contents of this string literal). We assert that the value returned from the `search` function contains only the line we expect. We aren’t yet able to run this test and watch it fail because the test doesn’t even compile: the `search` function doesn’t exist yet! In accordance with TDD principles, we’ll add just enough code to get the test to compile and run by adding a definition of the `search` function that always returns an empty vector, as shown in Listing 12-16. Then the test should compile and fail because an empty vector doesn’t match a vector containing the line `"safe, fast, productive."` Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { vec![] } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 12-16: Defining just enough of the `search` function so our test will compile Notice that we need to define an explicit lifetime `'a` in the signature of `search` and use that lifetime with the `contents` argument and the return value. Recall in [Chapter 10](ch10-03-lifetime-syntax) that the lifetime parameters specify which argument lifetime is connected to the lifetime of the return value. In this case, we indicate that the returned vector should contain string slices that reference slices of the argument `contents` (rather than the argument `query`). In other words, we tell Rust that the data returned by the `search` function will live as long as the data passed into the `search` function in the `contents` argument. This is important! The data referenced *by* a slice needs to be valid for the reference to be valid; if the compiler assumes we’re making string slices of `query` rather than `contents`, it will do its safety checking incorrectly. If we forget the lifetime annotations and try to compile this function, we’ll get this error: ``` $ cargo build Compiling minigrep v0.1.0 (file:///projects/minigrep) error[E0106]: missing lifetime specifier --> src/lib.rs:28:51 | 28 | pub fn search(query: &str, contents: &str) -> Vec<&str> { | ---- ---- ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents` help: consider introducing a named lifetime parameter | 28 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> { | ++++ ++ ++ ++ For more information about this error, try `rustc --explain E0106`. error: could not compile `minigrep` due to previous error ``` Rust can’t possibly know which of the two arguments we need, so we need to tell it explicitly. Because `contents` is the argument that contains all of our text and we want to return the parts of that text that match, we know `contents` is the argument that should be connected to the return value using the lifetime syntax. Other programming languages don’t require you to connect arguments to return values in the signature, but this practice will get easier over time. You might want to compare this example with the [“Validating References with Lifetimes”](ch10-03-lifetime-syntax#validating-references-with-lifetimes) section in Chapter 10. Now let’s run the test: ``` $ cargo test Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished test [unoptimized + debuginfo] target(s) in 0.97s Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94) running 1 test test tests::one_result ... FAILED failures: ---- tests::one_result stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `["safe, fast, productive."]`, right: `[]`', src/lib.rs:44:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::one_result test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Great, the test fails, exactly as we expected. Let’s get the test to pass! ### Writing Code to Pass the Test Currently, our test is failing because we always return an empty vector. To fix that and implement `search`, our program needs to follow these steps: * Iterate through each line of the contents. * Check whether the line contains our query string. * If it does, add it to the list of values we’re returning. * If it doesn’t, do nothing. * Return the list of results that match. Let’s work through each step, starting with iterating through lines. #### Iterating Through Lines with the `lines` Method Rust has a helpful method to handle line-by-line iteration of strings, conveniently named `lines`, that works as shown in Listing 12-17. Note this won’t compile yet. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { for line in contents.lines() { // do something with line } } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 12-17: Iterating through each line in `contents` The `lines` method returns an iterator. We’ll talk about iterators in depth in [Chapter 13](ch13-02-iterators), but recall that you saw this way of using an iterator in [Listing 3-5](ch03-05-control-flow#looping-through-a-collection-with-for), where we used a `for` loop with an iterator to run some code on each item in a collection. #### Searching Each Line for the Query Next, we’ll check whether the current line contains our query string. Fortunately, strings have a helpful method named `contains` that does this for us! Add a call to the `contains` method in the `search` function, as shown in Listing 12-18. Note this still won’t compile yet. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { for line in contents.lines() { if line.contains(query) { // do something with line } } } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 12-18: Adding functionality to see whether the line contains the string in `query` At the moment, we’re building up functionality. To get it to compile, we need to return a value from the body as we indicated we would in the function signature. #### Storing Matching Lines To finish this function, we need a way to store the matching lines that we want to return. For that, we can make a mutable vector before the `for` loop and call the `push` method to store a `line` in the vector. After the `for` loop, we return the vector, as shown in Listing 12-19. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 12-19: Storing the lines that match so we can return them Now the `search` function should return only the lines that contain `query`, and our test should pass. Let’s run the test: ``` $ cargo test Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished test [unoptimized + debuginfo] target(s) in 1.22s Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94) running 1 test test tests::one_result ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests minigrep running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Our test passed, so we know it works! At this point, we could consider opportunities for refactoring the implementation of the search function while keeping the tests passing to maintain the same functionality. The code in the search function isn’t too bad, but it doesn’t take advantage of some useful features of iterators. We’ll return to this example in [Chapter 13](ch13-02-iterators), where we’ll explore iterators in detail, and look at how to improve it. #### Using the `search` Function in the `run` Function Now that the `search` function is working and tested, we need to call `search` from our `run` function. We need to pass the `config.query` value and the `contents` that `run` reads from the file to the `search` function. Then `run` will print each line returned from `search`: Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; for line in search(&config.query, &contents) { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` We’re still using a `for` loop to return each line from `search` and print it. Now the entire program should work! Let’s try it out, first with a word that should return exactly one line from the Emily Dickinson poem, “frog”: ``` $ cargo run -- frog poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.38s Running `target/debug/minigrep frog poem.txt` How public, like a frog ``` Cool! Now let’s try a word that will match multiple lines, like “body”: ``` $ cargo run -- body poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep body poem.txt` I'm nobody! Who are you? Are you nobody, too? How dreary to be somebody! ``` And finally, let’s make sure that we don’t get any lines when we search for a word that isn’t anywhere in the poem, such as “monomorphization”: ``` $ cargo run -- monomorphization poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep monomorphization poem.txt` ``` Excellent! We’ve built our own mini version of a classic tool and learned a lot about how to structure applications. We’ve also learned a bit about file input and output, lifetimes, testing, and command line parsing. To round out this project, we’ll briefly demonstrate how to work with environment variables and how to print to standard error, both of which are useful when you’re writing command line programs.
programming_docs
rust Control Flow Control Flow ============ The ability to run some code depending on if a condition is true, or run some code repeatedly while a condition is true, are basic building blocks in most programming languages. The most common constructs that let you control the flow of execution of Rust code are `if` expressions and loops. ### `if` Expressions An `if` expression allows you to branch your code depending on conditions. You provide a condition and then state, “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.” Create a new project called *branches* in your *projects* directory to explore the `if` expression. In the *src/main.rs* file, input the following: Filename: src/main.rs ``` fn main() { let number = 3; if number < 5 { println!("condition was true"); } else { println!("condition was false"); } } ``` All `if` expressions start with the keyword `if`, followed by a condition. In this case, the condition checks whether or not the variable `number` has a value less than 5. We place the block of code to execute if the condition is true immediately after the condition inside curly brackets. Blocks of code associated with the conditions in `if` expressions are sometimes called *arms*, just like the arms in `match` expressions that we discussed in the [“Comparing the Guess to the Secret Number”](ch02-00-guessing-game-tutorial#comparing-the-guess-to-the-secret-number) section of Chapter 2. Optionally, we can also include an `else` expression, which we chose to do here, to give the program an alternative block of code to execute should the condition evaluate to false. If you don’t provide an `else` expression and the condition is false, the program will just skip the `if` block and move on to the next bit of code. Try running this code; you should see the following output: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) Finished dev [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/branches` condition was true ``` Let’s try changing the value of `number` to a value that makes the condition `false` to see what happens: ``` fn main() { let number = 7; if number < 5 { println!("condition was true"); } else { println!("condition was false"); } } ``` Run the program again, and look at the output: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) Finished dev [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/branches` condition was false ``` It’s also worth noting that the condition in this code *must* be a `bool`. If the condition isn’t a `bool`, we’ll get an error. For example, try running the following code: Filename: src/main.rs ``` fn main() { let number = 3; if number { println!("number was three"); } } ``` The `if` condition evaluates to a value of `3` this time, and Rust throws an error: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) error[E0308]: mismatched types --> src/main.rs:4:8 | 4 | if number { | ^^^^^^ expected `bool`, found integer For more information about this error, try `rustc --explain E0308`. error: could not compile `branches` due to previous error ``` The error indicates that Rust expected a `bool` but got an integer. Unlike languages such as Ruby and JavaScript, Rust will not automatically try to convert non-Boolean types to a Boolean. You must be explicit and always provide `if` with a Boolean as its condition. If we want the `if` code block to run only when a number is not equal to `0`, for example, we can change the `if` expression to the following: Filename: src/main.rs ``` fn main() { let number = 3; if number != 0 { println!("number was something other than zero"); } } ``` Running this code will print `number was something other than zero`. #### Handling Multiple Conditions with `else if` You can use multiple conditions by combining `if` and `else` in an `else if` expression. For example: Filename: src/main.rs ``` fn main() { let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3"); } else if number % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); } } ``` This program has four possible paths it can take. After running it, you should see the following output: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) Finished dev [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/branches` number is divisible by 3 ``` When this program executes, it checks each `if` expression in turn and executes the first body for which the condition holds true. Note that even though 6 is divisible by 2, we don’t see the output `number is divisible by 2`, nor do we see the `number is not divisible by 4, 3, or 2` text from the `else` block. That’s because Rust only executes the block for the first true condition, and once it finds one, it doesn’t even check the rest. Using too many `else if` expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Rust branching construct called `match` for these cases. #### Using `if` in a `let` Statement Because `if` is an expression, we can use it on the right side of a `let` statement to assign the outcome to a variable, as in Listing 3-2. Filename: src/main.rs ``` fn main() { let condition = true; let number = if condition { 5 } else { 6 }; println!("The value of number is: {number}"); } ``` Listing 3-2: Assigning the result of an `if` expression to a variable The `number` variable will be bound to a value based on the outcome of the `if` expression. Run this code to see what happens: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) Finished dev [unoptimized + debuginfo] target(s) in 0.30s Running `target/debug/branches` The value of number is: 5 ``` Remember that blocks of code evaluate to the last expression in them, and numbers by themselves are also expressions. In this case, the value of the whole `if` expression depends on which block of code executes. This means the values that have the potential to be results from each arm of the `if` must be the same type; in Listing 3-2, the results of both the `if` arm and the `else` arm were `i32` integers. If the types are mismatched, as in the following example, we’ll get an error: Filename: src/main.rs ``` fn main() { let condition = true; let number = if condition { 5 } else { "six" }; println!("The value of number is: {number}"); } ``` When we try to compile this code, we’ll get an error. The `if` and `else` arms have value types that are incompatible, and Rust indicates exactly where to find the problem in the program: ``` $ cargo run Compiling branches v0.1.0 (file:///projects/branches) error[E0308]: `if` and `else` have incompatible types --> src/main.rs:4:44 | 4 | let number = if condition { 5 } else { "six" }; | - ^^^^^ expected integer, found `&str` | | | expected because of this For more information about this error, try `rustc --explain E0308`. error: could not compile `branches` due to previous error ``` The expression in the `if` block evaluates to an integer, and the expression in the `else` block evaluates to a string. This won’t work because variables must have a single type, and Rust needs to know at compile time what type the `number` variable is, definitively. Knowing the type of `number` lets the compiler verify the type is valid everywhere we use `number`. Rust wouldn’t be able to do that if the type of `number` was only determined at runtime; the compiler would be more complex and would make fewer guarantees about the code if it had to keep track of multiple hypothetical types for any variable. ### Repetition with Loops It’s often useful to execute a block of code more than once. For this task, Rust provides several *loops*, which will run through the code inside the loop body to the end and then start immediately back at the beginning. To experiment with loops, let’s make a new project called *loops*. Rust has three kinds of loops: `loop`, `while`, and `for`. Let’s try each one. #### Repeating Code with `loop` The `loop` keyword tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop. As an example, change the *src/main.rs* file in your *loops* directory to look like this: Filename: src/main.rs ``` fn main() { loop { println!("again!"); } } ``` When we run this program, we’ll see `again!` printed over and over continuously until we stop the program manually. Most terminals support the keyboard shortcut ctrl-c to interrupt a program that is stuck in a continual loop. Give it a try: ``` $ cargo run Compiling loops v0.1.0 (file:///projects/loops) Finished dev [unoptimized + debuginfo] target(s) in 0.29s Running `target/debug/loops` again! again! again! again! ^Cagain! ``` The symbol `^C` represents where you pressed ctrl-c . You may or may not see the word `again!` printed after the `^C`, depending on where the code was in the loop when it received the interrupt signal. Fortunately, Rust also provides a way to break out of a loop using code. You can place the `break` keyword within the loop to tell the program when to stop executing the loop. Recall that we did this in the guessing game in the [“Quitting After a Correct Guess”](ch02-00-guessing-game-tutorial#quitting-after-a-correct-guess) section of Chapter 2 to exit the program when the user won the game by guessing the correct number. We also used `continue` in the guessing game, which in a loop tells the program to skip over any remaining code in this iteration of the loop and go to the next iteration. #### Returning Values from Loops One of the uses of a `loop` is to retry an operation you know might fail, such as checking whether a thread has completed its job. You might also need to pass the result of that operation out of the loop to the rest of your code. To do this, you can add the value you want returned after the `break` expression you use to stop the loop; that value will be returned out of the loop so you can use it, as shown here: ``` fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is {result}"); } ``` Before the loop, we declare a variable named `counter` and initialize it to `0`. Then we declare a variable named `result` to hold the value returned from the loop. On every iteration of the loop, we add `1` to the `counter` variable, and then check whether the counter is equal to `10`. When it is, we use the `break` keyword with the value `counter * 2`. After the loop, we use a semicolon to end the statement that assigns the value to `result`. Finally, we print the value in `result`, which in this case is 20. #### Loop Labels to Disambiguate Between Multiple Loops If you have loops within loops, `break` and `continue` apply to the innermost loop at that point. You can optionally specify a *loop label* on a loop that we can then use with `break` or `continue` to specify that those keywords apply to the labeled loop instead of the innermost loop. Loop labels must begin with a single quote. Here’s an example with two nested loops: ``` fn main() { let mut count = 0; 'counting_up: loop { println!("count = {count}"); let mut remaining = 10; loop { println!("remaining = {remaining}"); if remaining == 9 { break; } if count == 2 { break 'counting_up; } remaining -= 1; } count += 1; } println!("End count = {count}"); } ``` The outer loop has the label `'counting_up`, and it will count up from 0 to 2. The inner loop without a label counts down from 10 to 9. The first `break` that doesn’t specify a label will exit the inner loop only. The `break 'counting_up;` statement will exit the outer loop. This code prints: ``` $ cargo run Compiling loops v0.1.0 (file:///projects/loops) Finished dev [unoptimized + debuginfo] target(s) in 0.58s Running `target/debug/loops` count = 0 remaining = 10 remaining = 9 count = 1 remaining = 10 remaining = 9 count = 2 remaining = 10 End count = 2 ``` #### Conditional Loops with `while` A program will often need to evaluate a condition within a loop. While the condition is true, the loop runs. When the condition ceases to be true, the program calls `break`, stopping the loop. It’s possible to implement behavior like this using a combination of `loop`, `if`, `else`, and `break`; you could try that now in a program, if you’d like. However, this pattern is so common that Rust has a built-in language construct for it, called a `while` loop. In Listing 3-3, we use `while` to loop the program three times, counting down each time, and then, after the loop, print a message and exit. Filename: src/main.rs ``` fn main() { let mut number = 3; while number != 0 { println!("{number}!"); number -= 1; } println!("LIFTOFF!!!"); } ``` Listing 3-3: Using a `while` loop to run code while a condition holds true This construct eliminates a lot of nesting that would be necessary if you used `loop`, `if`, `else`, and `break`, and it’s clearer. While a condition holds true, the code runs; otherwise, it exits the loop. #### Looping Through a Collection with `for` You can choose to use the `while` construct to loop over the elements of a collection, such as an array. For example, the loop in Listing 3-4 prints each element in the array `a`. Filename: src/main.rs ``` fn main() { let a = [10, 20, 30, 40, 50]; let mut index = 0; while index < 5 { println!("the value is: {}", a[index]); index += 1; } } ``` Listing 3-4: Looping through each element of a collection using a `while` loop Here, the code counts up through the elements in the array. It starts at index `0`, and then loops until it reaches the final index in the array (that is, when `index < 5` is no longer true). Running this code will print every element in the array: ``` $ cargo run Compiling loops v0.1.0 (file:///projects/loops) Finished dev [unoptimized + debuginfo] target(s) in 0.32s Running `target/debug/loops` the value is: 10 the value is: 20 the value is: 30 the value is: 40 the value is: 50 ``` All five array values appear in the terminal, as expected. Even though `index` will reach a value of `5` at some point, the loop stops executing before trying to fetch a sixth value from the array. However, this approach is error prone; we could cause the program to panic if the index value or test condition are incorrect. For example, if you changed the definition of the `a` array to have four elements but forgot to update the condition to `while index < 4`, the code would panic. It’s also slow, because the compiler adds runtime code to perform the conditional check of whether the index is within the bounds of the array on every iteration through the loop. As a more concise alternative, you can use a `for` loop and execute some code for each item in a collection. A `for` loop looks like the code in Listing 3-5. Filename: src/main.rs ``` fn main() { let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {element}"); } } ``` Listing 3-5: Looping through each element of a collection using a `for` loop When we run this code, we’ll see the same output as in Listing 3-4. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items. Using the `for` loop, you wouldn’t need to remember to change any other code if you changed the number of values in the array, as you would with the method used in Listing 3-4. The safety and conciseness of `for` loops make them the most commonly used loop construct in Rust. Even in situations in which you want to run some code a certain number of times, as in the countdown example that used a `while` loop in Listing 3-3, most Rustaceans would use a `for` loop. The way to do that would be to use a `Range`, provided by the standard library, which generates all numbers in sequence starting from one number and ending before another number. Here’s what the countdown would look like using a `for` loop and another method we’ve not yet talked about, `rev`, to reverse the range: Filename: src/main.rs ``` fn main() { for number in (1..4).rev() { println!("{number}!"); } println!("LIFTOFF!!!"); } ``` This code is a bit nicer, isn’t it? Summary ------- You made it! That was a sizable chapter: you learned about variables, scalar and compound data types, functions, comments, `if` expressions, and loops! To practice with the concepts discussed in this chapter, try building programs to do the following: * Convert temperatures between Fahrenheit and Celsius. * Generate the nth Fibonacci number. * Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song. When you’re ready to move on, we’ll talk about a concept in Rust that *doesn’t* commonly exist in other programming languages: ownership. rust Reference Cycles Can Leak Memory Reference Cycles Can Leak Memory ================================ Rust’s memory safety guarantees make it difficult, but not impossible, to accidentally create memory that is never cleaned up (known as a *memory leak*). Preventing memory leaks entirely is not one of Rust’s guarantees, meaning memory leaks are memory safe in Rust. We can see that Rust allows memory leaks by using `Rc<T>` and `RefCell<T>`: it’s possible to create references where items refer to each other in a cycle. This creates memory leaks because the reference count of each item in the cycle will never reach 0, and the values will never be dropped. ### Creating a Reference Cycle Let’s look at how a reference cycle might happen and how to prevent it, starting with the definition of the `List` enum and a `tail` method in Listing 15-25: Filename: src/main.rs ``` use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Rc<List>>> { match self { Cons(_, item) => Some(item), Nil => None, } } } fn main() {} ``` Listing 15-25: A cons list definition that holds a `RefCell<T>` so we can modify what a `Cons` variant is referring to We’re using another variation of the `List` definition from Listing 15-5. The second element in the `Cons` variant is now `RefCell<Rc<List>>`, meaning that instead of having the ability to modify the `i32` value as we did in Listing 15-24, we want to modify the `List` value a `Cons` variant is pointing to. We’re also adding a `tail` method to make it convenient for us to access the second item if we have a `Cons` variant. In Listing 15-26, we’re adding a `main` function that uses the definitions in Listing 15-25. This code creates a list in `a` and a list in `b` that points to the list in `a`. Then it modifies the list in `a` to point to `b`, creating a reference cycle. There are `println!` statements along the way to show what the reference counts are at various points in this process. Filename: src/main.rs ``` use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Rc<List>>> { match self { Cons(_, item) => Some(item), Nil => None, } } } fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); println!("a initial rc count = {}", Rc::strong_count(&a)); println!("a next item = {:?}", a.tail()); let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); println!("a rc count after b creation = {}", Rc::strong_count(&a)); println!("b initial rc count = {}", Rc::strong_count(&b)); println!("b next item = {:?}", b.tail()); if let Some(link) = a.tail() { *link.borrow_mut() = Rc::clone(&b); } println!("b rc count after changing a = {}", Rc::strong_count(&b)); println!("a rc count after changing a = {}", Rc::strong_count(&a)); // Uncomment the next line to see that we have a cycle; // it will overflow the stack // println!("a next item = {:?}", a.tail()); } ``` Listing 15-26: Creating a reference cycle of two `List` values pointing to each other We create an `Rc<List>` instance holding a `List` value in the variable `a` with an initial list of `5, Nil`. We then create an `Rc<List>` instance holding another `List` value in the variable `b` that contains the value 10 and points to the list in `a`. We modify `a` so it points to `b` instead of `Nil`, creating a cycle. We do that by using the `tail` method to get a reference to the `RefCell<Rc<List>>` in `a`, which we put in the variable `link`. Then we use the `borrow_mut` method on the `RefCell<Rc<List>>` to change the value inside from an `Rc<List>` that holds a `Nil` value to the `Rc<List>` in `b`. When we run this code, keeping the last `println!` commented out for the moment, we’ll get this output: ``` $ cargo run Compiling cons-list v0.1.0 (file:///projects/cons-list) Finished dev [unoptimized + debuginfo] target(s) in 0.53s Running `target/debug/cons-list` a initial rc count = 1 a next item = Some(RefCell { value: Nil }) a rc count after b creation = 2 b initial rc count = 1 b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) }) b rc count after changing a = 2 a rc count after changing a = 2 ``` The reference count of the `Rc<List>` instances in both `a` and `b` are 2 after we change the list in `a` to point to `b`. At the end of `main`, Rust drops the variable `b`, which decreases the reference count of the `b` `Rc<List>` instance from 2 to 1. The memory that `Rc<List>` has on the heap won’t be dropped at this point, because its reference count is 1, not 0. Then Rust drops `a`, which decreases the reference count of the `a` `Rc<List>` instance from 2 to 1 as well. This instance’s memory can’t be dropped either, because the other `Rc<List>` instance still refers to it. The memory allocated to the list will remain uncollected forever. To visualize this reference cycle, we’ve created a diagram in Figure 15-4. Figure 15-4: A reference cycle of lists `a` and `b` pointing to each other If you uncomment the last `println!` and run the program, Rust will try to print this cycle with `a` pointing to `b` pointing to `a` and so forth until it overflows the stack. Compared to a real-world program, the consequences creating a reference cycle in this example aren’t very dire: right after we create the reference cycle, the program ends. However, if a more complex program allocated lots of memory in a cycle and held onto it for a long time, the program would use more memory than it needed and might overwhelm the system, causing it to run out of available memory. Creating reference cycles is not easily done, but it’s not impossible either. If you have `RefCell<T>` values that contain `Rc<T>` values or similar nested combinations of types with interior mutability and reference counting, you must ensure that you don’t create cycles; you can’t rely on Rust to catch them. Creating a reference cycle would be a logic bug in your program that you should use automated tests, code reviews, and other software development practices to minimize. Another solution for avoiding reference cycles is reorganizing your data structures so that some references express ownership and some references don’t. As a result, you can have cycles made up of some ownership relationships and some non-ownership relationships, and only the ownership relationships affect whether or not a value can be dropped. In Listing 15-25, we always want `Cons` variants to own their list, so reorganizing the data structure isn’t possible. Let’s look at an example using graphs made up of parent nodes and child nodes to see when non-ownership relationships are an appropriate way to prevent reference cycles. ### Preventing Reference Cycles: Turning an `Rc<T>` into a `Weak<T>` So far, we’ve demonstrated that calling `Rc::clone` increases the `strong_count` of an `Rc<T>` instance, and an `Rc<T>` instance is only cleaned up if its `strong_count` is 0. You can also create a *weak reference* to the value within an `Rc<T>` instance by calling `Rc::downgrade` and passing a reference to the `Rc<T>`. Strong references are how you can share ownership of an `Rc<T>` instance. Weak references don’t express an ownership relationship, and their count doesn't affect when an `Rc<T>` instance is cleaned up. They won’t cause a reference cycle because any cycle involving some weak references will be broken once the strong reference count of values involved is 0. When you call `Rc::downgrade`, you get a smart pointer of type `Weak<T>`. Instead of increasing the `strong_count` in the `Rc<T>` instance by 1, calling `Rc::downgrade` increases the `weak_count` by 1. The `Rc<T>` type uses `weak_count` to keep track of how many `Weak<T>` references exist, similar to `strong_count`. The difference is the `weak_count` doesn’t need to be 0 for the `Rc<T>` instance to be cleaned up. Because the value that `Weak<T>` references might have been dropped, to do anything with the value that a `Weak<T>` is pointing to, you must make sure the value still exists. Do this by calling the `upgrade` method on a `Weak<T>` instance, which will return an `Option<Rc<T>>`. You’ll get a result of `Some` if the `Rc<T>` value has not been dropped yet and a result of `None` if the `Rc<T>` value has been dropped. Because `upgrade` returns an `Option<Rc<T>>`, Rust will ensure that the `Some` case and the `None` case are handled, and there won’t be an invalid pointer. As an example, rather than using a list whose items know only about the next item, we’ll create a tree whose items know about their children items *and* their parent items. #### Creating a Tree Data Structure: a `Node` with Child Nodes To start, we’ll build a tree with nodes that know about their child nodes. We’ll create a struct named `Node` that holds its own `i32` value as well as references to its children `Node` values: Filename: src/main.rs ``` use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] struct Node { value: i32, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), }); } ``` We want a `Node` to own its children, and we want to share that ownership with variables so we can access each `Node` in the tree directly. To do this, we define the `Vec<T>` items to be values of type `Rc<Node>`. We also want to modify which nodes are children of another node, so we have a `RefCell<T>` in `children` around the `Vec<Rc<Node>>`. Next, we’ll use our struct definition and create one `Node` instance named `leaf` with the value 3 and no children, and another instance named `branch` with the value 5 and `leaf` as one of its children, as shown in Listing 15-27: Filename: src/main.rs ``` use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] struct Node { value: i32, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), }); } ``` Listing 15-27: Creating a `leaf` node with no children and a `branch` node with `leaf` as one of its children We clone the `Rc<Node>` in `leaf` and store that in `branch`, meaning the `Node` in `leaf` now has two owners: `leaf` and `branch`. We can get from `branch` to `leaf` through `branch.children`, but there’s no way to get from `leaf` to `branch`. The reason is that `leaf` has no reference to `branch` and doesn’t know they’re related. We want `leaf` to know that `branch` is its parent. We’ll do that next. #### Adding a Reference from a Child to Its Parent To make the child node aware of its parent, we need to add a `parent` field to our `Node` struct definition. The trouble is in deciding what the type of `parent` should be. We know it can’t contain an `Rc<T>`, because that would create a reference cycle with `leaf.parent` pointing to `branch` and `branch.children` pointing to `leaf`, which would cause their `strong_count` values to never be 0. Thinking about the relationships another way, a parent node should own its children: if a parent node is dropped, its child nodes should be dropped as well. However, a child should not own its parent: if we drop a child node, the parent should still exist. This is a case for weak references! So instead of `Rc<T>`, we’ll make the type of `parent` use `Weak<T>`, specifically a `RefCell<Weak<Node>>`. Now our `Node` struct definition looks like this: Filename: src/main.rs ``` use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); } ``` A node will be able to refer to its parent node but doesn’t own its parent. In Listing 15-28, we update `main` to use this new definition so the `leaf` node will have a way to refer to its parent, `branch`: Filename: src/main.rs ``` use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); } ``` Listing 15-28: A `leaf` node with a weak reference to its parent node `branch` Creating the `leaf` node looks similar to Listing 15-27 with the exception of the `parent` field: `leaf` starts out without a parent, so we create a new, empty `Weak<Node>` reference instance. At this point, when we try to get a reference to the parent of `leaf` by using the `upgrade` method, we get a `None` value. We see this in the output from the first `println!` statement: ``` leaf parent = None ``` When we create the `branch` node, it will also have a new `Weak<Node>` reference in the `parent` field, because `branch` doesn’t have a parent node. We still have `leaf` as one of the children of `branch`. Once we have the `Node` instance in `branch`, we can modify `leaf` to give it a `Weak<Node>` reference to its parent. We use the `borrow_mut` method on the `RefCell<Weak<Node>>` in the `parent` field of `leaf`, and then we use the `Rc::downgrade` function to create a `Weak<Node>` reference to `branch` from the `Rc<Node>` in `branch.` When we print the parent of `leaf` again, this time we’ll get a `Some` variant holding `branch`: now `leaf` can access its parent! When we print `leaf`, we also avoid the cycle that eventually ended in a stack overflow like we had in Listing 15-26; the `Weak<Node>` references are printed as `(Weak)`: ``` leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) }, children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) }, children: RefCell { value: [] } }] } }) ``` The lack of infinite output indicates that this code didn’t create a reference cycle. We can also tell this by looking at the values we get from calling `Rc::strong_count` and `Rc::weak_count`. #### Visualizing Changes to `strong_count` and `weak_count` Let’s look at how the `strong_count` and `weak_count` values of the `Rc<Node>` instances change by creating a new inner scope and moving the creation of `branch` into that scope. By doing so, we can see what happens when `branch` is created and then dropped when it goes out of scope. The modifications are shown in Listing 15-29: Filename: src/main.rs ``` use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); { let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!( "branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch), ); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); } println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); } ``` Listing 15-29: Creating `branch` in an inner scope and examining strong and weak reference counts After `leaf` is created, its `Rc<Node>` has a strong count of 1 and a weak count of 0. In the inner scope, we create `branch` and associate it with `leaf`, at which point when we print the counts, the `Rc<Node>` in `branch` will have a strong count of 1 and a weak count of 1 (for `leaf.parent` pointing to `branch` with a `Weak<Node>`). When we print the counts in `leaf`, we’ll see it will have a strong count of 2, because `branch` now has a clone of the `Rc<Node>` of `leaf` stored in `branch.children`, but will still have a weak count of 0. When the inner scope ends, `branch` goes out of scope and the strong count of the `Rc<Node>` decreases to 0, so its `Node` is dropped. The weak count of 1 from `leaf.parent` has no bearing on whether or not `Node` is dropped, so we don’t get any memory leaks! If we try to access the parent of `leaf` after the end of the scope, we’ll get `None` again. At the end of the program, the `Rc<Node>` in `leaf` has a strong count of 1 and a weak count of 0, because the variable `leaf` is now the only reference to the `Rc<Node>` again. All of the logic that manages the counts and value dropping is built into `Rc<T>` and `Weak<T>` and their implementations of the `Drop` trait. By specifying that the relationship from a child to its parent should be a `Weak<T>` reference in the definition of `Node`, you’re able to have parent nodes point to child nodes and vice versa without creating a reference cycle and memory leaks. Summary ------- This chapter covered how to use smart pointers to make different guarantees and trade-offs from those Rust makes by default with regular references. The `Box<T>` type has a known size and points to data allocated on the heap. The `Rc<T>` type keeps track of the number of references to data on the heap so that data can have multiple owners. The `RefCell<T>` type with its interior mutability gives us a type that we can use when we need an immutable type but need to change an inner value of that type; it also enforces the borrowing rules at runtime instead of at compile time. Also discussed were the `Deref` and `Drop` traits, which enable a lot of the functionality of smart pointers. We explored reference cycles that can cause memory leaks and how to prevent them using `Weak<T>`. If this chapter has piqued your interest and you want to implement your own smart pointers, check out [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/index.html) for more useful information. Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new smart pointers.
programming_docs
rust Using Box<T> to Point to Data on the Heap Using `Box<T>` to Point to Data on the Heap =========================================== The most straightforward smart pointer is a *box*, whose type is written `Box<T>`. Boxes allow you to store data on the heap rather than the stack. What remains on the stack is the pointer to the heap data. Refer to Chapter 4 to review the difference between the stack and the heap. Boxes don’t have performance overhead, other than storing their data on the heap instead of on the stack. But they don’t have many extra capabilities either. You’ll use them most often in these situations: * When you have a type whose size can’t be known at compile time and you want to use a value of that type in a context that requires an exact size * When you have a large amount of data and you want to transfer ownership but ensure the data won’t be copied when you do so * When you want to own a value and you care only that it’s a type that implements a particular trait rather than being of a specific type We’ll demonstrate the first situation in the [“Enabling Recursive Types with Boxes”](#enabling-recursive-types-with-boxes) section. In the second case, transferring ownership of a large amount of data can take a long time because the data is copied around on the stack. To improve performance in this situation, we can store the large amount of data on the heap in a box. Then, only the small amount of pointer data is copied around on the stack, while the data it references stays in one place on the heap. The third case is known as a *trait object*, and Chapter 17 devotes an entire section, [“Using Trait Objects That Allow for Values of Different Types,”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) just to that topic. So what you learn here you’ll apply again in Chapter 17! ### Using a `Box<T>` to Store Data on the Heap Before we discuss the heap storage use case for `Box<T>`, we’ll cover the syntax and how to interact with values stored within a `Box<T>`. Listing 15-1 shows how to use a box to store an `i32` value on the heap: Filename: src/main.rs ``` fn main() { let b = Box::new(5); println!("b = {}", b); } ``` Listing 15-1: Storing an `i32` value on the heap using a box We define the variable `b` to have the value of a `Box` that points to the value `5`, which is allocated on the heap. This program will print `b = 5`; in this case, we can access the data in the box similar to how we would if this data were on the stack. Just like any owned value, when a box goes out of scope, as `b` does at the end of `main`, it will be deallocated. The deallocation happens both for the box (stored on the stack) and the data it points to (stored on the heap). Putting a single value on the heap isn’t very useful, so you won’t use boxes by themselves in this way very often. Having values like a single `i32` on the stack, where they’re stored by default, is more appropriate in the majority of situations. Let’s look at a case where boxes allow us to define types that we wouldn’t be allowed to if we didn’t have boxes. ### Enabling Recursive Types with Boxes A value of *recursive type* can have another value of the same type as part of itself. Recursive types pose an issue because at compile time Rust needs to know how much space a type takes up. However, the nesting of values of recursive types could theoretically continue infinitely, so Rust can’t know how much space the value needs. Because boxes have a known size, we can enable recursive types by inserting a box in the recursive type definition. As an example of a recursive type, let’s explore the *cons list*. This is a data type commonly found in functional programming languages. The cons list type we’ll define is straightforward except for the recursion; therefore, the concepts in the example we’ll work with will be useful any time you get into more complex situations involving recursive types. #### More Information About the Cons List A *cons list* is a data structure that comes from the Lisp programming language and its dialects and is made up of nested pairs, and is the Lisp version of a linked list. Its name comes from the `cons` function (short for “construct function”) in Lisp that constructs a new pair from its two arguments. By calling `cons` on a pair consisting of a value and another pair, we can construct cons lists made up of recursive pairs. For example, here's a pseudocode representation of a cons list containing the list 1, 2, 3 with each pair in parentheses: ``` (1, (2, (3, Nil))) ``` Each item in a cons list contains two elements: the value of the current item and the next item. The last item in the list contains only a value called `Nil` without a next item. A cons list is produced by recursively calling the `cons` function. The canonical name to denote the base case of the recursion is `Nil`. Note that this is not the same as the “null” or “nil” concept in Chapter 6, which is an invalid or absent value. The cons list isn’t a commonly used data structure in Rust. Most of the time when you have a list of items in Rust, `Vec<T>` is a better choice to use. Other, more complex recursive data types *are* useful in various situations, but by starting with the cons list in this chapter, we can explore how boxes let us define a recursive data type without much distraction. Listing 15-2 contains an enum definition for a cons list. Note that this code won’t compile yet because the `List` type doesn’t have a known size, which we’ll demonstrate. Filename: src/main.rs ``` enum List { Cons(i32, List), Nil, } fn main() {} ``` Listing 15-2: The first attempt at defining an enum to represent a cons list data structure of `i32` values > Note: We’re implementing a cons list that holds only `i32` values for the purposes of this example. We could have implemented it using generics, as we discussed in Chapter 10, to define a cons list type that could store values of any type. > > Using the `List` type to store the list `1, 2, 3` would look like the code in Listing 15-3: Filename: src/main.rs ``` enum List { Cons(i32, List), Nil, } use crate::List::{Cons, Nil}; fn main() { let list = Cons(1, Cons(2, Cons(3, Nil))); } ``` Listing 15-3: Using the `List` enum to store the list `1, 2, 3` The first `Cons` value holds `1` and another `List` value. This `List` value is another `Cons` value that holds `2` and another `List` value. This `List` value is one more `Cons` value that holds `3` and a `List` value, which is finally `Nil`, the non-recursive variant that signals the end of the list. If we try to compile the code in Listing 15-3, we get the error shown in Listing 15-4: ``` $ cargo run Compiling cons-list v0.1.0 (file:///projects/cons-list) error[E0072]: recursive type `List` has infinite size --> src/main.rs:1:1 | 1 | enum List { | ^^^^^^^^^ recursive type has infinite size 2 | Cons(i32, List), | ---- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable | 2 | Cons(i32, Box<List>), | ++++ + error[E0391]: cycle detected when computing drop-check constraints for `List` --> src/main.rs:1:1 | 1 | enum List { | ^^^^^^^^^ | = note: ...which immediately requires computing drop-check constraints for `List` again = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst }, value: List } }` Some errors have detailed explanations: E0072, E0391. For more information about an error, try `rustc --explain E0072`. error: could not compile `cons-list` due to 2 previous errors ``` Listing 15-4: The error we get when attempting to define a recursive enum The error shows this type “has infinite size.” The reason is that we’ve defined `List` with a variant that is recursive: it holds another value of itself directly. As a result, Rust can’t figure out how much space it needs to store a `List` value. Let’s break down why we get this error. First, we'll look at how Rust decides how much space it needs to store a value of a non-recursive type. #### Computing the Size of a Non-Recursive Type Recall the `Message` enum we defined in Listing 6-2 when we discussed enum definitions in Chapter 6: ``` enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() {} ``` To determine how much space to allocate for a `Message` value, Rust goes through each of the variants to see which variant needs the most space. Rust sees that `Message::Quit` doesn’t need any space, `Message::Move` needs enough space to store two `i32` values, and so forth. Because only one variant will be used, the most space a `Message` value will need is the space it would take to store the largest of its variants. Contrast this with what happens when Rust tries to determine how much space a recursive type like the `List` enum in Listing 15-2 needs. The compiler starts by looking at the `Cons` variant, which holds a value of type `i32` and a value of type `List`. Therefore, `Cons` needs an amount of space equal to the size of an `i32` plus the size of a `List`. To figure out how much memory the `List` type needs, the compiler looks at the variants, starting with the `Cons` variant. The `Cons` variant holds a value of type `i32` and a value of type `List`, and this process continues infinitely, as shown in Figure 15-1. Figure 15-1: An infinite `List` consisting of infinite `Cons` variants #### Using `Box<T>` to Get a Recursive Type with a Known Size Because Rust can’t figure out how much space to allocate for recursively defined types, the compiler gives an error with this helpful suggestion: ``` help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable | 2 | Cons(i32, Box<List>), | ^^^^ ^ ``` In this suggestion, “indirection” means that instead of storing a value directly, we should change the data structure to store the value indirectly by storing a pointer to the value instead. Because a `Box<T>` is a pointer, Rust always knows how much space a `Box<T>` needs: a pointer’s size doesn’t change based on the amount of data it’s pointing to. This means we can put a `Box<T>` inside the `Cons` variant instead of another `List` value directly. The `Box<T>` will point to the next `List` value that will be on the heap rather than inside the `Cons` variant. Conceptually, we still have a list, created with lists holding other lists, but this implementation is now more like placing the items next to one another rather than inside one another. We can change the definition of the `List` enum in Listing 15-2 and the usage of the `List` in Listing 15-3 to the code in Listing 15-5, which will compile: Filename: src/main.rs ``` enum List { Cons(i32, Box<List>), Nil, } use crate::List::{Cons, Nil}; fn main() { let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); } ``` Listing 15-5: Definition of `List` that uses `Box<T>` in order to have a known size The `Cons` variant needs the size of an `i32` plus the space to store the box’s pointer data. The `Nil` variant stores no values, so it needs less space than the `Cons` variant. We now know that any `List` value will take up the size of an `i32` plus the size of a box’s pointer data. By using a box, we’ve broken the infinite, recursive chain, so the compiler can figure out the size it needs to store a `List` value. Figure 15-2 shows what the `Cons` variant looks like now. Figure 15-2: A `List` that is not infinitely sized because `Cons` holds a `Box` Boxes provide only the indirection and heap allocation; they don’t have any other special capabilities, like those we’ll see with the other smart pointer types. They also don’t have the performance overhead that these special capabilities incur, so they can be useful in cases like the cons list where the indirection is the only feature we need. We’ll look at more use cases for boxes in Chapter 17, too. The `Box<T>` type is a smart pointer because it implements the `Deref` trait, which allows `Box<T>` values to be treated like references. When a `Box<T>` value goes out of scope, the heap data that the box is pointing to is cleaned up as well because of the `Drop` trait implementation. These two traits will be even more important to the functionality provided by the other smart pointer types we’ll discuss in the rest of this chapter. Let’s explore these two traits in more detail. rust None The `match` Control Flow Construct ---------------------------------- Rust has an extremely powerful control flow construct called `match` that allows you to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable names, wildcards, and many other things; Chapter 18 covers all the different kinds of patterns and what they do. The power of `match` comes from the expressiveness of the patterns and the fact that the compiler confirms that all possible cases are handled. Think of a `match` expression as being like a coin-sorting machine: coins slide down a track with variously sized holes along it, and each coin falls through the first hole it encounters that it fits into. In the same way, values go through each pattern in a `match`, and at the first pattern the value “fits,” the value falls into the associated code block to be used during execution. Speaking of coins, let’s use them as an example using `match`! We can write a function that takes an unknown United States coin and, in a similar way as the counting machine, determines which coin it is and returns its value in cents, as shown here in Listing 6-3. ``` enum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } } fn main() {} ``` Listing 6-3: An enum and a `match` expression that has the variants of the enum as its patterns Let’s break down the `match` in the `value_in_cents` function. First, we list the `match` keyword followed by an expression, which in this case is the value `coin`. This seems very similar to an expression used with `if`, but there’s a big difference: with `if`, the expression needs to return a Boolean value, but here, it can return any type. The type of `coin` in this example is the `Coin` enum that we defined on the first line. Next are the `match` arms. An arm has two parts: a pattern and some code. The first arm here has a pattern that is the value `Coin::Penny` and then the `=>` operator that separates the pattern and the code to run. The code in this case is just the value `1`. Each arm is separated from the next with a comma. When the `match` expression executes, it compares the resulting value against the pattern of each arm, in order. If a pattern matches the value, the code associated with that pattern is executed. If that pattern doesn’t match the value, execution continues to the next arm, much as in a coin-sorting machine. We can have as many arms as we need: in Listing 6-3, our `match` has four arms. The code associated with each arm is an expression, and the resulting value of the expression in the matching arm is the value that gets returned for the entire `match` expression. We don’t typically use curly brackets if the match arm code is short, as it is in Listing 6-3 where each arm just returns a value. If you want to run multiple lines of code in a match arm, you must use curly brackets, and the comma following the arm is then optional. For example, the following code prints “Lucky penny!” every time the method is called with a `Coin::Penny`, but still returns the last value of the block, `1`: ``` enum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => { println!("Lucky penny!"); 1 } Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } } fn main() {} ``` ### Patterns that Bind to Values Another useful feature of match arms is that they can bind to the parts of the values that match the pattern. This is how we can extract values out of enum variants. As an example, let’s change one of our enum variants to hold data inside it. From 1999 through 2008, the United States minted quarters with different designs for each of the 50 states on one side. No other coins got state designs, so only quarters have this extra value. We can add this information to our `enum` by changing the `Quarter` variant to include a `UsState` value stored inside it, which we’ve done here in Listing 6-4. ``` #[derive(Debug)] // so we can inspect the state in a minute enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() {} ``` Listing 6-4: A `Coin` enum in which the `Quarter` variant also holds a `UsState` value Let’s imagine that a friend is trying to collect all 50 state quarters. While we sort our loose change by coin type, we’ll also call out the name of the state associated with each quarter so if it’s one our friend doesn’t have, they can add it to their collection. In the match expression for this code, we add a variable called `state` to the pattern that matches values of the variant `Coin::Quarter`. When a `Coin::Quarter` matches, the `state` variable will bind to the value of that quarter’s state. Then we can use `state` in the code for that arm, like so: ``` #[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter(state) => { println!("State quarter from {:?}!", state); 25 } } } fn main() { value_in_cents(Coin::Quarter(UsState::Alaska)); } ``` If we were to call `value_in_cents(Coin::Quarter(UsState::Alaska))`, `coin` would be `Coin::Quarter(UsState::Alaska)`. When we compare that value with each of the match arms, none of them match until we reach `Coin::Quarter(state)`. At that point, the binding for `state` will be the value `UsState::Alaska`. We can then use that binding in the `println!` expression, thus getting the inner state value out of the `Coin` enum variant for `Quarter`. ### Matching with `Option<T>` In the previous section, we wanted to get the inner `T` value out of the `Some` case when using `Option<T>`; we can also handle `Option<T>` using `match` as we did with the `Coin` enum! Instead of comparing coins, we’ll compare the variants of `Option<T>`, but the way that the `match` expression works remains the same. Let’s say we want to write a function that takes an `Option<i32>` and, if there’s a value inside, adds 1 to that value. If there isn’t a value inside, the function should return the `None` value and not attempt to perform any operations. This function is very easy to write, thanks to `match`, and will look like Listing 6-5. ``` fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` Listing 6-5: A function that uses a `match` expression on an `Option<i32>` Let’s examine the first execution of `plus_one` in more detail. When we call `plus_one(five)`, the variable `x` in the body of `plus_one` will have the value `Some(5)`. We then compare that against each match arm. ``` fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` The `Some(5)` value doesn’t match the pattern `None`, so we continue to the next arm. ``` fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` Does `Some(5)` match `Some(i)`? Why yes it does! We have the same variant. The `i` binds to the value contained in `Some`, so `i` takes the value `5`. The code in the match arm is then executed, so we add 1 to the value of `i` and create a new `Some` value with our total `6` inside. Now let’s consider the second call of `plus_one` in Listing 6-5, where `x` is `None`. We enter the `match` and compare to the first arm. ``` fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` It matches! There’s no value to add to, so the program stops and returns the `None` value on the right side of `=>`. Because the first arm matched, no other arms are compared. Combining `match` and enums is useful in many situations. You’ll see this pattern a lot in Rust code: `match` against an enum, bind a variable to the data inside, and then execute code based on it. It’s a bit tricky at first, but once you get used to it, you’ll wish you had it in all languages. It’s consistently a user favorite. ### Matches Are Exhaustive There’s one other aspect of `match` we need to discuss: the arms’ patterns must cover all possibilities. Consider this version of our `plus_one` function, which has a bug and won’t compile: ``` fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); } ``` We didn’t handle the `None` case, so this code will cause a bug. Luckily, it’s a bug Rust knows how to catch. If we try to compile this code, we’ll get this error: ``` $ cargo run Compiling enums v0.1.0 (file:///projects/enums) error[E0004]: non-exhaustive patterns: `None` not covered --> src/main.rs:3:15 | 3 | match x { | ^ pattern `None` not covered | note: `Option<i32>` defined here = note: the matched value is of type `Option<i32>` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown | 4 ~ Some(i) => Some(i + 1), 5 ~ None => todo!(), | For more information about this error, try `rustc --explain E0004`. error: could not compile `enums` due to previous error ``` Rust knows that we didn’t cover every possible case and even knows which pattern we forgot! Matches in Rust are *exhaustive*: we must exhaust every last possibility in order for the code to be valid. Especially in the case of `Option<T>`, when Rust prevents us from forgetting to explicitly handle the `None` case, it protects us from assuming that we have a value when we might have null, thus making the billion-dollar mistake discussed earlier impossible. ### Catch-all Patterns and the `_` Placeholder Using enums, we can also take special actions for a few particular values, but for all other values take one default action. Imagine we’re implementing a game where, if you roll a 3 on a dice roll, your player doesn’t move, but instead gets a new fancy hat. If you roll a 7, your player loses a fancy hat. For all other values, your player moves that number of spaces on the game board. Here’s a `match` that implements that logic, with the result of the dice roll hardcoded rather than a random value, and all other logic represented by functions without bodies because actually implementing them is out of scope for this example: ``` fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), other => move_player(other), } fn add_fancy_hat() {} fn remove_fancy_hat() {} fn move_player(num_spaces: u8) {} } ``` For the first two arms, the patterns are the literal values 3 and 7. For the last arm that covers every other possible value, the pattern is the variable we’ve chosen to name `other`. The code that runs for the `other` arm uses the variable by passing it to the `move_player` function. This code compiles, even though we haven’t listed all the possible values a `u8` can have, because the last pattern will match all values not specifically listed. This catch-all pattern meets the requirement that `match` must be exhaustive. Note that we have to put the catch-all arm last because the patterns are evaluated in order. If we put the catch-all arm earlier, the other arms would never run, so Rust will warn us if we add arms after a catch-all! Rust also has a pattern we can use when we want a catch-all but don’t want to *use* the value in the catch-all pattern: `_` is a special pattern that matches any value and does not bind to that value. This tells Rust we aren’t going to use the value, so Rust won’t warn us about an unused variable. Let’s change the rules of the game: now, if you roll anything other than a 3 or a 7, you must roll again. We no longer need to use the catch-all value, so we can change our code to use `_` instead of the variable named `other`: ``` fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), _ => reroll(), } fn add_fancy_hat() {} fn remove_fancy_hat() {} fn reroll() {} } ``` This example also meets the exhaustiveness requirement because we’re explicitly ignoring all other values in the last arm; we haven’t forgotten anything. Finally, we’ll change the rules of the game one more time, so that nothing else happens on your turn if you roll anything other than a 3 or a 7. We can express that by using the unit value (the empty tuple type we mentioned in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section) as the code that goes with the `_` arm: ``` fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), _ => (), } fn add_fancy_hat() {} fn remove_fancy_hat() {} } ``` Here, we’re telling Rust explicitly that we aren’t going to use any other value that doesn’t match a pattern in an earlier arm, and we don’t want to run any code in this case. There’s more about patterns and matching that we’ll cover in [Chapter 18](ch18-00-patterns). For now, we’re going to move on to the `if let` syntax, which can be useful in situations where the `match` expression is a bit wordy.
programming_docs
rust Publishing a Crate to Crates.io Publishing a Crate to Crates.io =============================== We’ve used packages from [crates.io](https://crates.io/) as dependencies of our project, but you can also share your code with other people by publishing your own packages. The crate registry at [crates.io](https://crates.io/) distributes the source code of your packages, so it primarily hosts code that is open source. Rust and Cargo have features that make your published package easier for people to find and use. We’ll talk about some of these features next and then explain how to publish a package. ### Making Useful Documentation Comments Accurately documenting your packages will help other users know how and when to use them, so it’s worth investing the time to write documentation. In Chapter 3, we discussed how to comment Rust code using two slashes, `//`. Rust also has a particular kind of comment for documentation, known conveniently as a *documentation comment*, that will generate HTML documentation. The HTML displays the contents of documentation comments for public API items intended for programmers interested in knowing how to *use* your crate as opposed to how your crate is *implemented*. Documentation comments use three slashes, `///`, instead of two and support Markdown notation for formatting the text. Place documentation comments just before the item they’re documenting. Listing 14-1 shows documentation comments for an `add_one` function in a crate named `my_crate`. Filename: src/lib.rs ``` /// Adds one to the number given. /// /// # Examples /// /// ``` /// let arg = 5; /// let answer = my_crate::add_one(arg); /// /// assert_eq!(6, answer); /// ``` pub fn add_one(x: i32) -> i32 { x + 1 } ``` Listing 14-1: A documentation comment for a function Here, we give a description of what the `add_one` function does, start a section with the heading `Examples`, and then provide code that demonstrates how to use the `add_one` function. We can generate the HTML documentation from this documentation comment by running `cargo doc`. This command runs the `rustdoc` tool distributed with Rust and puts the generated HTML documentation in the *target/doc* directory. For convenience, running `cargo doc --open` will build the HTML for your current crate’s documentation (as well as the documentation for all of your crate’s dependencies) and open the result in a web browser. Navigate to the `add_one` function and you’ll see how the text in the documentation comments is rendered, as shown in Figure 14-1: ![Rendered HTML documentation for the `add_one` function of `my_crate`](https://doc.rust-lang.org/book/img/trpl14-01.png) Figure 14-1: HTML documentation for the `add_one` function #### Commonly Used Sections We used the `# Examples` Markdown heading in Listing 14-1 to create a section in the HTML with the title “Examples.” Here are some other sections that crate authors commonly use in their documentation: * **Panics**: The scenarios in which the function being documented could panic. Callers of the function who don’t want their programs to panic should make sure they don’t call the function in these situations. * **Errors**: If the function returns a `Result`, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can write code to handle the different kinds of errors in different ways. * **Safety**: If the function is `unsafe` to call (we discuss unsafety in Chapter 19), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold. Most documentation comments don’t need all of these sections, but this is a good checklist to remind you of the aspects of your code users will be interested in knowing about. #### Documentation Comments as Tests Adding example code blocks in your documentation comments can help demonstrate how to use your library, and doing so has an additional bonus: running `cargo test` will run the code examples in your documentation as tests! Nothing is better than documentation with examples. But nothing is worse than examples that don’t work because the code has changed since the documentation was written. If we run `cargo test` with the documentation for the `add_one` function from Listing 14-1, we will see a section in the test results like this: ``` Doc-tests my_crate running 1 test test src/lib.rs - add_one (line 5) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s ``` Now if we change either the function or the example so the `assert_eq!` in the example panics and run `cargo test` again, we’ll see that the doc tests catch that the example and the code are out of sync with each other! #### Commenting Contained Items The style of doc comment `//!` adds documentation to the item that contains the comments rather than to the items following the comments. We typically use these doc comments inside the crate root file (*src/lib.rs* by convention) or inside a module to document the crate or the module as a whole. For example, to add documentation that describes the purpose of the `my_crate` crate that contains the `add_one` function, we add documentation comments that start with `//!` to the beginning of the *src/lib.rs* file, as shown in Listing 14-2: Filename: src/lib.rs ``` //! # My Crate //! //! `my_crate` is a collection of utilities to make performing certain //! calculations more convenient. /// Adds one to the number given. // --snip-- /// /// # Examples /// /// ``` /// let arg = 5; /// let answer = my_crate::add_one(arg); /// /// assert_eq!(6, answer); /// ``` pub fn add_one(x: i32) -> i32 { x + 1 } ``` Listing 14-2: Documentation for the `my_crate` crate as a whole Notice there isn’t any code after the last line that begins with `//!`. Because we started the comments with `//!` instead of `///`, we’re documenting the item that contains this comment rather than an item that follows this comment. In this case, that item is the *src/lib.rs* file, which is the crate root. These comments describe the entire crate. When we run `cargo doc --open`, these comments will display on the front page of the documentation for `my_crate` above the list of public items in the crate, as shown in Figure 14-2: Figure 14-2: Rendered documentation for `my_crate`, including the comment describing the crate as a whole Documentation comments within items are useful for describing crates and modules especially. Use them to explain the overall purpose of the container to help your users understand the crate’s organization. ### Exporting a Convenient Public API with `pub use` The structure of your public API is a major consideration when publishing a crate. People who use your crate are less familiar with the structure than you are and might have difficulty finding the pieces they want to use if your crate has a large module hierarchy. In Chapter 7, we covered how to make items public using the `pub` keyword, and bring items into a scope with the `use` keyword. However, the structure that makes sense to you while you’re developing a crate might not be very convenient for your users. You might want to organize your structs in a hierarchy containing multiple levels, but then people who want to use a type you’ve defined deep in the hierarchy might have trouble finding out that type exists. They might also be annoyed at having to enter `use` `my_crate::some_module::another_module::UsefulType;` rather than `use` `my_crate::UsefulType;`. The good news is that if the structure *isn’t* convenient for others to use from another library, you don’t have to rearrange your internal organization: instead, you can re-export items to make a public structure that’s different from your private structure by using `pub use`. Re-exporting takes a public item in one location and makes it public in another location, as if it were defined in the other location instead. For example, say we made a library named `art` for modeling artistic concepts. Within this library are two modules: a `kinds` module containing two enums named `PrimaryColor` and `SecondaryColor` and a `utils` module containing a function named `mix`, as shown in Listing 14-3: Filename: src/lib.rs ``` //! # Art //! //! A library for modeling artistic concepts. pub mod kinds { /// The primary colors according to the RYB color model. pub enum PrimaryColor { Red, Yellow, Blue, } /// The secondary colors according to the RYB color model. pub enum SecondaryColor { Orange, Green, Purple, } } pub mod utils { use crate::kinds::*; /// Combines two primary colors in equal amounts to create /// a secondary color. pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { // --snip-- unimplemented!(); } } ``` Listing 14-3: An `art` library with items organized into `kinds` and `utils` modules Figure 14-3 shows what the front page of the documentation for this crate generated by `cargo doc` would look like: Figure 14-3: Front page of the documentation for `art` that lists the `kinds` and `utils` modules Note that the `PrimaryColor` and `SecondaryColor` types aren’t listed on the front page, nor is the `mix` function. We have to click `kinds` and `utils` to see them. Another crate that depends on this library would need `use` statements that bring the items from `art` into scope, specifying the module structure that’s currently defined. Listing 14-4 shows an example of a crate that uses the `PrimaryColor` and `mix` items from the `art` crate: Filename: src/main.rs ``` use art::kinds::PrimaryColor; use art::utils::mix; fn main() { let red = PrimaryColor::Red; let yellow = PrimaryColor::Yellow; mix(red, yellow); } ``` Listing 14-4: A crate using the `art` crate’s items with its internal structure exported The author of the code in Listing 14-4, which uses the `art` crate, had to figure out that `PrimaryColor` is in the `kinds` module and `mix` is in the `utils` module. The module structure of the `art` crate is more relevant to developers working on the `art` crate than to those using it. The internal structure doesn’t contain any useful information for someone trying to understand how to use the `art` crate, but rather causes confusion because developers who use it have to figure out where to look, and must specify the module names in the `use` statements. To remove the internal organization from the public API, we can modify the `art` crate code in Listing 14-3 to add `pub use` statements to re-export the items at the top level, as shown in Listing 14-5: Filename: src/lib.rs ``` //! # Art //! //! A library for modeling artistic concepts. pub use self::kinds::PrimaryColor; pub use self::kinds::SecondaryColor; pub use self::utils::mix; pub mod kinds { // --snip-- /// The primary colors according to the RYB color model. pub enum PrimaryColor { Red, Yellow, Blue, } /// The secondary colors according to the RYB color model. pub enum SecondaryColor { Orange, Green, Purple, } } pub mod utils { // --snip-- use crate::kinds::*; /// Combines two primary colors in equal amounts to create /// a secondary color. pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { SecondaryColor::Orange } } ``` Listing 14-5: Adding `pub use` statements to re-export items The API documentation that `cargo doc` generates for this crate will now list and link re-exports on the front page, as shown in Figure 14-4, making the `PrimaryColor` and `SecondaryColor` types and the `mix` function easier to find. ![Rendered documentation for the `art` crate with the re-exports on the front page](https://doc.rust-lang.org/book/img/trpl14-04.png) Figure 14-4: The front page of the documentation for `art` that lists the re-exports The `art` crate users can still see and use the internal structure from Listing 14-3 as demonstrated in Listing 14-4, or they can use the more convenient structure in Listing 14-5, as shown in Listing 14-6: Filename: src/main.rs ``` use art::mix; use art::PrimaryColor; fn main() { // --snip-- let red = PrimaryColor::Red; let yellow = PrimaryColor::Yellow; mix(red, yellow); } ``` Listing 14-6: A program using the re-exported items from the `art` crate In cases where there are many nested modules, re-exporting the types at the top level with `pub use` can make a significant difference in the experience of people who use the crate. Another common use of `pub use` is to re-export definitions of a dependency in the current crate to make that crate's definitions part of your crate’s public API. Creating a useful public API structure is more of an art than a science, and you can iterate to find the API that works best for your users. Choosing `pub use` gives you flexibility in how you structure your crate internally and decouples that internal structure from what you present to your users. Look at some of the code of crates you’ve installed to see if their internal structure differs from their public API. ### Setting Up a Crates.io Account Before you can publish any crates, you need to create an account on [crates.io](https://crates.io/) and get an API token. To do so, visit the home page at [crates.io](https://crates.io/) and log in via a GitHub account. (The GitHub account is currently a requirement, but the site might support other ways of creating an account in the future.) Once you’re logged in, visit your account settings at <https://crates.io/me/> and retrieve your API key. Then run the `cargo login` command with your API key, like this: ``` $ cargo login abcdefghijklmnopqrstuvwxyz012345 ``` This command will inform Cargo of your API token and store it locally in *~/.cargo/credentials*. Note that this token is a *secret*: do not share it with anyone else. If you do share it with anyone for any reason, you should revoke it and generate a new token on [crates.io](https://crates.io/). ### Adding Metadata to a New Crate Let’s say you have a crate you want to publish. Before publishing, you’ll need to add some metadata in the `[package]` section of the crate’s *Cargo.toml* file. Your crate will need a unique name. While you’re working on a crate locally, you can name a crate whatever you’d like. However, crate names on [crates.io](https://crates.io/) are allocated on a first-come, first-served basis. Once a crate name is taken, no one else can publish a crate with that name. Before attempting to publish a crate, search for the name you want to use. If the name has been used, you will need to find another name and edit the `name` field in the *Cargo.toml* file under the `[package]` section to use the new name for publishing, like so: Filename: Cargo.toml ``` [package] name = "guessing_game" ``` Even if you’ve chosen a unique name, when you run `cargo publish` to publish the crate at this point, you’ll get a warning and then an error: ``` $ cargo publish Updating crates.io index warning: manifest has no description, license, license-file, documentation, homepage or repository. See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info. --snip-- error: failed to publish to registry at https://crates.io Caused by: the remote server responded with an error: missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for how to upload metadata ``` This errors because you’re missing some crucial information: a description and license are required so people will know what your crate does and under what terms they can use it. In *Cargo.toml*, add a description that's just a sentence or two, because it will appear with your crate in search results. For the `license` field, you need to give a *license identifier value*. The [Linux Foundation’s Software Package Data Exchange (SPDX)](http://spdx.org/licenses/) lists the identifiers you can use for this value. For example, to specify that you’ve licensed your crate using the MIT License, add the `MIT` identifier: Filename: Cargo.toml ``` [package] name = "guessing_game" license = "MIT" ``` If you want to use a license that doesn’t appear in the SPDX, you need to place the text of that license in a file, include the file in your project, and then use `license-file` to specify the name of that file instead of using the `license` key. Guidance on which license is appropriate for your project is beyond the scope of this book. Many people in the Rust community license their projects in the same way as Rust by using a dual license of `MIT OR Apache-2.0`. This practice demonstrates that you can also specify multiple license identifiers separated by `OR` to have multiple licenses for your project. With a unique name, the version, your description, and a license added, the *Cargo.toml* file for a project that is ready to publish might look like this: Filename: Cargo.toml ``` [package] name = "guessing_game" version = "0.1.0" edition = "2021" description = "A fun game where you guess what number the computer has chosen." license = "MIT OR Apache-2.0" [dependencies] ``` [Cargo’s documentation](https://doc.rust-lang.org/cargo/index.html) describes other metadata you can specify to ensure others can discover and use your crate more easily. ### Publishing to Crates.io Now that you’ve created an account, saved your API token, chosen a name for your crate, and specified the required metadata, you’re ready to publish! Publishing a crate uploads a specific version to [crates.io](https://crates.io/) for others to use. Be careful, because a publish is *permanent*. The version can never be overwritten, and the code cannot be deleted. One major goal of [crates.io](https://crates.io/) is to act as a permanent archive of code so that builds of all projects that depend on crates from [crates.io](https://crates.io/) will continue to work. Allowing version deletions would make fulfilling that goal impossible. However, there is no limit to the number of crate versions you can publish. Run the `cargo publish` command again. It should succeed now: ``` $ cargo publish Updating crates.io index Packaging guessing_game v0.1.0 (file:///projects/guessing_game) Verifying guessing_game v0.1.0 (file:///projects/guessing_game) Compiling guessing_game v0.1.0 (file:///projects/guessing_game/target/package/guessing_game-0.1.0) Finished dev [unoptimized + debuginfo] target(s) in 0.19s Uploading guessing_game v0.1.0 (file:///projects/guessing_game) ``` Congratulations! You’ve now shared your code with the Rust community, and anyone can easily add your crate as a dependency of their project. ### Publishing a New Version of an Existing Crate When you’ve made changes to your crate and are ready to release a new version, you change the `version` value specified in your *Cargo.toml* file and republish. Use the [Semantic Versioning rules](http://semver.org/) to decide what an appropriate next version number is based on the kinds of changes you’ve made. Then run `cargo publish` to upload the new version. ### Deprecating Versions from Crates.io with `cargo yank` Although you can’t remove previous versions of a crate, you can prevent any future projects from adding them as a new dependency. This is useful when a crate version is broken for one reason or another. In such situations, Cargo supports *yanking* a crate version. Yanking a version prevents new projects from depending on that version while allowing all existing projects that depend on it to continue. Essentially, a yank means that all projects with a *Cargo.lock* will not break, and any future *Cargo.lock* files generated will not use the yanked version. To yank a version of a crate, in the directory of the crate that you’ve previously published, run `cargo yank` and specify which version you want to yank. For example, if we've published a crate named `guessing_game` version 1.0.1 and we want to yank it, in the project directory for `guessing_game` we'd run: ``` $ cargo yank --vers 1.0.1 Updating crates.io index Yank guessing_game:1.0.1 ``` By adding `--undo` to the command, you can also undo a yank and allow projects to start depending on a version again: ``` $ cargo yank --vers 1.0.1 --undo Updating crates.io index Unyank guessing_game_:1.0.1 ``` A yank *does not* delete any code. It cannot, for example, delete accidentally uploaded secrets. If that happens, you must reset those secrets immediately.
programming_docs
rust Hello, World! Hello, World! ============= Now that you’ve installed Rust, let’s write your first Rust program. It’s traditional when learning a new language to write a little program that prints the text `Hello, world!` to the screen, so we’ll do the same here! > Note: This book assumes basic familiarity with the command line. Rust makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an integrated development environment (IDE) instead of the command line, feel free to use your favorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s documentation for details. The Rust team has been focusing on enabling great IDE support via `rust-analyzer`. See [Appendix D](appendix-04-useful-development-tools) for more details! > > ### Creating a Project Directory You’ll start by making a directory to store your Rust code. It doesn’t matter to Rust where your code lives, but for the exercises and projects in this book, we suggest making a *projects* directory in your home directory and keeping all your projects there. Open a terminal and enter the following commands to make a *projects* directory and a directory for the “Hello, world!” project within the *projects* directory. For Linux, macOS, and PowerShell on Windows, enter this: ``` $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world ``` For Windows CMD, enter this: ``` > mkdir "%USERPROFILE%\projects" > cd /d "%USERPROFILE%\projects" > mkdir hello_world > cd hello_world ``` ### Writing and Running a Rust Program Next, make a new source file and call it *main.rs*. Rust files always end with the *.rs* extension. If you’re using more than one word in your filename, the convention is to use an underscore to separate them. For example, use *hello\_world.rs* rather than *helloworld.rs*. Now open the *main.rs* file you just created and enter the code in Listing 1-1. Filename: main.rs ``` fn main() { println!("Hello, world!"); } ``` Listing 1-1: A program that prints `Hello, world!` Save the file and go back to your terminal window in the *~/projects/hello\_world* directory. On Linux or macOS, enter the following commands to compile and run the file: ``` $ rustc main.rs $ ./main Hello, world! ``` On Windows, enter the command `.\main.exe` instead of `./main`: ``` > rustc main.rs > .\main.exe Hello, world! ``` Regardless of your operating system, the string `Hello, world!` should print to the terminal. If you don’t see this output, refer back to the [“Troubleshooting”](ch01-01-installation#troubleshooting) part of the Installation section for ways to get help. If `Hello, world!` did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome! ### Anatomy of a Rust Program Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle: ``` fn main() { } ``` These lines define a function named `main`. The `main` function is special: it is always the first code that runs in every executable Rust program. Here, the first line declares a function named `main` that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses `()`. The function body is wrapped in `{}`. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between. > Note: If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called `rustfmt` to format your code in a particular style (more on `rustfmt` in [Appendix D](appendix-04-useful-development-tools)). The Rust team has included this tool with the standard Rust distribution, like `rustc`, so it should already be installed on your computer! > > The body of the `main` function holds the following code: ``` #![allow(unused)] fn main() { println!("Hello, world!"); } ``` This line does all the work in this little program: it prints text to the screen. There are four important details to notice here. First, Rust style is to indent with four spaces, not a tab. Second, `println!` calls a Rust macro. If it had called a function instead, it would be entered as `println` (without the `!`). We’ll discuss Rust macros in more detail in Chapter 19. For now, you just need to know that using a `!` means that you’re calling a macro instead of a normal function, and that macros don’t always follow the same rules as functions. Third, you see the `"Hello, world!"` string. We pass this string as an argument to `println!`, and the string is printed to the screen. Fourth, we end the line with a semicolon (`;`), which indicates that this expression is over and the next one is ready to begin. Most lines of Rust code end with a semicolon. ### Compiling and Running Are Separate Steps You’ve just run a newly created program, so let’s examine each step in the process. Before running a Rust program, you must compile it using the Rust compiler by entering the `rustc` command and passing it the name of your source file, like this: ``` $ rustc main.rs ``` If you have a C or C++ background, you’ll notice that this is similar to `gcc` or `clang`. After compiling successfully, Rust outputs a binary executable. On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the `ls` command in your shell. On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll see the same three files that you would see using CMD. ``` $ ls main main.rs ``` With CMD on Windows, you would enter the following: ``` > dir /B %= the /B option says to only show the file names =% main.exe main.pdb main.rs ``` This shows the source code file with the *.rs* extension, the executable file (*main.exe* on Windows, but *main* on all other platforms), and, when using Windows, a file containing debugging information with the *.pdb* extension. From here, you run the *main* or *main.exe* file, like this: ``` $ ./main # or .\main.exe on Windows ``` If your *main.rs* is your “Hello, world!” program, this line prints `Hello, world!` to your terminal. If you’re more familiar with a dynamic language, such as Ruby, Python, or JavaScript, you might not be used to compiling and running a program as separate steps. Rust is an *ahead-of-time compiled* language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed. If you give someone a *.rb*, *.py*, or *.js* file, they need to have a Ruby, Python, or JavaScript implementation installed (respectively). But in those languages, you only need one command to compile and run your program. Everything is a trade-off in language design. Just compiling with `rustc` is fine for simple programs, but as your project grows, you’ll want to manage all the options and make it easy to share your code. Next, we’ll introduce you to the Cargo tool, which will help you write real-world Rust programs. rust Appendix A: Keywords Appendix A: Keywords ==================== The following list contains keywords that are reserved for current or future use by the Rust language. As such, they cannot be used as identifiers (except as raw identifiers as we’ll discuss in the “[Raw Identifiers](#raw-identifiers)” section). Identifiers are names of functions, variables, parameters, struct fields, modules, crates, constants, macros, static values, attributes, types, traits, or lifetimes. ### Keywords Currently in Use The following is a list of keywords currently in use, with their functionality described. * `as` - perform primitive casting, disambiguate the specific trait containing an item, or rename items in `use` statements * `async` - return a `Future` instead of blocking the current thread * `await` - suspend execution until the result of a `Future` is ready * `break` - exit a loop immediately * `const` - define constant items or constant raw pointers * `continue` - continue to the next loop iteration * `crate` - in a module path, refers to the crate root * `dyn` - dynamic dispatch to a trait object * `else` - fallback for `if` and `if let` control flow constructs * `enum` - define an enumeration * `extern` - link an external function or variable * `false` - Boolean false literal * `fn` - define a function or the function pointer type * `for` - loop over items from an iterator, implement a trait, or specify a higher-ranked lifetime * `if` - branch based on the result of a conditional expression * `impl` - implement inherent or trait functionality * `in` - part of `for` loop syntax * `let` - bind a variable * `loop` - loop unconditionally * `match` - match a value to patterns * `mod` - define a module * `move` - make a closure take ownership of all its captures * `mut` - denote mutability in references, raw pointers, or pattern bindings * `pub` - denote public visibility in struct fields, `impl` blocks, or modules * `ref` - bind by reference * `return` - return from function * `Self` - a type alias for the type we are defining or implementing * `self` - method subject or current module * `static` - global variable or lifetime lasting the entire program execution * `struct` - define a structure * `super` - parent module of the current module * `trait` - define a trait * `true` - Boolean true literal * `type` - define a type alias or associated type * `union` - define a [union](../reference/items/unions); is only a keyword when used in a union declaration * `unsafe` - denote unsafe code, functions, traits, or implementations * `use` - bring symbols into scope * `where` - denote clauses that constrain a type * `while` - loop conditionally based on the result of an expression ### Keywords Reserved for Future Use The following keywords do not yet have any functionality but are reserved by Rust for potential future use. * `abstract` * `become` * `box` * `do` * `final` * `macro` * `override` * `priv` * `try` * `typeof` * `unsized` * `virtual` * `yield` ### Raw Identifiers *Raw identifiers* are the syntax that lets you use keywords where they wouldn’t normally be allowed. You use a raw identifier by prefixing a keyword with `r#`. For example, `match` is a keyword. If you try to compile the following function that uses `match` as its name: Filename: src/main.rs ``` fn match(needle: &str, haystack: &str) -> bool { haystack.contains(needle) } ``` you’ll get this error: ``` error: expected identifier, found keyword `match` --> src/main.rs:4:4 | 4 | fn match(needle: &str, haystack: &str) -> bool { | ^^^^^ expected identifier, found keyword ``` The error shows that you can’t use the keyword `match` as the function identifier. To use `match` as a function name, you need to use the raw identifier syntax, like this: Filename: src/main.rs ``` fn r#match(needle: &str, haystack: &str) -> bool { haystack.contains(needle) } fn main() { assert!(r#match("foo", "foobar")); } ``` This code will compile without any errors. Note the `r#` prefix on the function name in its definition as well as where the function is called in `main`. Raw identifiers allow you to use any word you choose as an identifier, even if that word happens to be a reserved keyword. This gives us more freedom to choose identifier names, as well as lets us integrate with programs written in a language where these words aren’t keywords. In addition, raw identifiers allow you to use libraries written in a different Rust edition than your crate uses. For example, `try` isn’t a keyword in the 2015 edition but is in the 2018 edition. If you depend on a library that’s written using the 2015 edition and has a `try` function, you’ll need to use the raw identifier syntax, `r#try` in this case, to call that function from your 2018 edition code. See [Appendix E](appendix-05-editions) for more information on editions. rust Cargo Workspaces Cargo Workspaces ================ In Chapter 12, we built a package that included a binary crate and a library crate. As your project develops, you might find that the library crate continues to get bigger and you want to split your package further into multiple library crates. Cargo offers a feature called *workspaces* that can help manage multiple related packages that are developed in tandem. ### Creating a Workspace A *workspace* is a set of packages that share the same *Cargo.lock* and output directory. Let’s make a project using a workspace—we’ll use trivial code so we can concentrate on the structure of the workspace. There are multiple ways to structure a workspace, so we'll just show one common way. We’ll have a workspace containing a binary and two libraries. The binary, which will provide the main functionality, will depend on the two libraries. One library will provide an `add_one` function, and a second library an `add_two` function. These three crates will be part of the same workspace. We’ll start by creating a new directory for the workspace: ``` $ mkdir add $ cd add ``` Next, in the *add* directory, we create the *Cargo.toml* file that will configure the entire workspace. This file won’t have a `[package]` section. Instead, it will start with a `[workspace]` section that will allow us to add members to the workspace by specifying the path to the package with our binary crate; in this case, that path is *adder*: Filename: Cargo.toml ``` [workspace] members = [ "adder", ] ``` Next, we’ll create the `adder` binary crate by running `cargo new` within the *add* directory: ``` $ cargo new adder Created binary (application) `adder` package ``` At this point, we can build the workspace by running `cargo build`. The files in your *add* directory should look like this: ``` ├── Cargo.lock ├── Cargo.toml ├── adder │ ├── Cargo.toml │ └── src │ └── main.rs └── target ``` The workspace has one *target* directory at the top level that the compiled artifacts will be placed into; the `adder` package doesn’t have its own *target* directory. Even if we were to run `cargo build` from inside the *adder* directory, the compiled artifacts would still end up in *add/target* rather than *add/adder/target*. Cargo structures the *target* directory in a workspace like this because the crates in a workspace are meant to depend on each other. If each crate had its own *target* directory, each crate would have to recompile each of the other crates in the workspace to place the artifacts in its own *target* directory. By sharing one *target* directory, the crates can avoid unnecessary rebuilding. ### Creating the Second Package in the Workspace Next, let’s create another member package in the workspace and call it `add_one`. Change the top-level *Cargo.toml* to specify the *add\_one* path in the `members` list: Filename: Cargo.toml ``` [workspace] members = [ "adder", "add_one", ] ``` Then generate a new library crate named `add_one`: ``` $ cargo new add_one --lib Created library `add_one` package ``` Your *add* directory should now have these directories and files: ``` ├── Cargo.lock ├── Cargo.toml ├── add_one │ ├── Cargo.toml │ └── src │ └── lib.rs ├── adder │ ├── Cargo.toml │ └── src │ └── main.rs └── target ``` In the *add\_one/src/lib.rs* file, let’s add an `add_one` function: Filename: add\_one/src/lib.rs ``` pub fn add_one(x: i32) -> i32 { x + 1 } ``` Now we can have the `adder` package with our binary depend on the `add_one` package that has our library. First, we’ll need to add a path dependency on `add_one` to *adder/Cargo.toml*. Filename: adder/Cargo.toml ``` [dependencies] add_one = { path = "../add_one" } ``` Cargo doesn’t assume that crates in a workspace will depend on each other, so we need to be explicit about the dependency relationships. Next, let’s use the `add_one` function (from the `add_one` crate) in the `adder` crate. Open the *adder/src/main.rs* file and add a `use` line at the top to bring the new `add_one` library crate into scope. Then change the `main` function to call the `add_one` function, as in Listing 14-7. Filename: adder/src/main.rs ``` use add_one; fn main() { let num = 10; println!("Hello, world! {num} plus one is {}!", add_one::add_one(num)); } ``` Listing 14-7: Using the `add_one` library crate from the `adder` crate Let’s build the workspace by running `cargo build` in the top-level *add* directory! ``` $ cargo build Compiling add_one v0.1.0 (file:///projects/add/add_one) Compiling adder v0.1.0 (file:///projects/add/adder) Finished dev [unoptimized + debuginfo] target(s) in 0.68s ``` To run the binary crate from the *add* directory, we can specify which package in the workspace we want to run by using the `-p` argument and the package name with `cargo run`: ``` $ cargo run -p adder Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/adder` Hello, world! 10 plus one is 11! ``` This runs the code in *adder/src/main.rs*, which depends on the `add_one` crate. #### Depending on an External Package in a Workspace Notice that the workspace has only one *Cargo.lock* file at the top level, rather than having a *Cargo.lock* in each crate’s directory. This ensures that all crates are using the same version of all dependencies. If we add the `rand` package to the *adder/Cargo.toml* and *add\_one/Cargo.toml* files, Cargo will resolve both of those to one version of `rand` and record that in the one *Cargo.lock*. Making all crates in the workspace use the same dependencies means the crates will always be compatible with each other. Let’s add the `rand` crate to the `[dependencies]` section in the *add\_one/Cargo.toml* file so we can use the `rand` crate in the `add_one` crate: Filename: add\_one/Cargo.toml ``` [dependencies] rand = "0.8.3" ``` We can now add `use rand;` to the *add\_one/src/lib.rs* file, and building the whole workspace by running `cargo build` in the *add* directory will bring in and compile the `rand` crate. We will get one warning because we aren’t referring to the `rand` we brought into scope: ``` $ cargo build Updating crates.io index Downloaded rand v0.8.3 --snip-- Compiling rand v0.8.3 Compiling add_one v0.1.0 (file:///projects/add/add_one) warning: unused import: `rand` --> add_one/src/lib.rs:1:5 | 1 | use rand; | ^^^^ | = note: `#[warn(unused_imports)]` on by default warning: 1 warning emitted Compiling adder v0.1.0 (file:///projects/add/adder) Finished dev [unoptimized + debuginfo] target(s) in 10.18s ``` The top-level *Cargo.lock* now contains information about the dependency of `add_one` on `rand`. However, even though `rand` is used somewhere in the workspace, we can’t use it in other crates in the workspace unless we add `rand` to their *Cargo.toml* files as well. For example, if we add `use rand;` to the *adder/src/main.rs* file for the `adder` package, we’ll get an error: ``` $ cargo build --snip-- Compiling adder v0.1.0 (file:///projects/add/adder) error[E0432]: unresolved import `rand` --> adder/src/main.rs:2:5 | 2 | use rand; | ^^^^ no external crate `rand` ``` To fix this, edit the *Cargo.toml* file for the `adder` package and indicate that `rand` is a dependency for it as well. Building the `adder` package will add `rand` to the list of dependencies for `adder` in *Cargo.lock*, but no additional copies of `rand` will be downloaded. Cargo has ensured that every crate in every package in the workspace using the `rand` package will be using the same version, saving us space and ensuring that the crates in the workspace will be compatible with each other. #### Adding a Test to a Workspace For another enhancement, let’s add a test of the `add_one::add_one` function within the `add_one` crate: Filename: add\_one/src/lib.rs ``` pub fn add_one(x: i32) -> i32 { x + 1 } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(3, add_one(2)); } } ``` Now run `cargo test` in the top-level *add* directory. Running `cargo test` in a workspace structured like this one will run the tests for all the crates in the workspace: ``` $ cargo test Compiling add_one v0.1.0 (file:///projects/add/add_one) Compiling adder v0.1.0 (file:///projects/add/adder) Finished test [unoptimized + debuginfo] target(s) in 0.27s Running target/debug/deps/add_one-f0253159197f7841 running 1 test test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running target/debug/deps/adder-49979ff40686fa8e running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests add_one running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` The first section of the output shows that the `it_works` test in the `add_one` crate passed. The next section shows that zero tests were found in the `adder` crate, and then the last section shows zero documentation tests were found in the `add_one` crate. We can also run tests for one particular crate in a workspace from the top-level directory by using the `-p` flag and specifying the name of the crate we want to test: ``` $ cargo test -p add_one Finished test [unoptimized + debuginfo] target(s) in 0.00s Running target/debug/deps/add_one-b3235fea9a156f74 running 1 test test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests add_one running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` This output shows `cargo test` only ran the tests for the `add_one` crate and didn’t run the `adder` crate tests. If you publish the crates in the workspace to [crates.io](https://crates.io/), each crate in the workspace will need to be published separately. Like `cargo test`, we can publish a particular crate in our workspace by using the `-p` flag and specifying the name of the crate we want to publish. For additional practice, add an `add_two` crate to this workspace in a similar way as the `add_one` crate! As your project grows, consider using a workspace: it’s easier to understand smaller, individual components than one big blob of code. Furthermore, keeping the crates in a workspace can make coordination between crates easier if they are often changed at the same time.
programming_docs
rust RefCell<T> and the Interior Mutability Pattern `RefCell<T>` and the Interior Mutability Pattern ================================================= *Interior mutability* is a design pattern in Rust that allows you to mutate data even when there are immutable references to that data; normally, this action is disallowed by the borrowing rules. To mutate data, the pattern uses `unsafe` code inside a data structure to bend Rust’s usual rules that govern mutation and borrowing. Unsafe code indicates to the compiler that we’re checking the rules manually instead of relying on the compiler to check them for us; we will discuss unsafe code more in Chapter 19. We can use types that use the interior mutability pattern only when we can ensure that the borrowing rules will be followed at runtime, even though the compiler can’t guarantee that. The `unsafe` code involved is then wrapped in a safe API, and the outer type is still immutable. Let’s explore this concept by looking at the `RefCell<T>` type that follows the interior mutability pattern. ### Enforcing Borrowing Rules at Runtime with `RefCell<T>` Unlike `Rc<T>`, the `RefCell<T>` type represents single ownership over the data it holds. So, what makes `RefCell<T>` different from a type like `Box<T>`? Recall the borrowing rules you learned in Chapter 4: * At any given time, you can have *either* (but not both) one mutable reference or any number of immutable references. * References must always be valid. With references and `Box<T>`, the borrowing rules’ invariants are enforced at compile time. With `RefCell<T>`, these invariants are enforced *at runtime*. With references, if you break these rules, you’ll get a compiler error. With `RefCell<T>`, if you break these rules, your program will panic and exit. The advantages of checking the borrowing rules at compile time are that errors will be caught sooner in the development process, and there is no impact on runtime performance because all the analysis is completed beforehand. For those reasons, checking the borrowing rules at compile time is the best choice in the majority of cases, which is why this is Rust’s default. The advantage of checking the borrowing rules at runtime instead is that certain memory-safe scenarios are then allowed, where they would’ve been disallowed by the compile-time checks. Static analysis, like the Rust compiler, is inherently conservative. Some properties of code are impossible to detect by analyzing the code: the most famous example is the Halting Problem, which is beyond the scope of this book but is an interesting topic to research. Because some analysis is impossible, if the Rust compiler can’t be sure the code complies with the ownership rules, it might reject a correct program; in this way, it’s conservative. If Rust accepted an incorrect program, users wouldn’t be able to trust in the guarantees Rust makes. However, if Rust rejects a correct program, the programmer will be inconvenienced, but nothing catastrophic can occur. The `RefCell<T>` type is useful when you’re sure your code follows the borrowing rules but the compiler is unable to understand and guarantee that. Similar to `Rc<T>`, `RefCell<T>` is only for use in single-threaded scenarios and will give you a compile-time error if you try using it in a multithreaded context. We’ll talk about how to get the functionality of `RefCell<T>` in a multithreaded program in Chapter 16. Here is a recap of the reasons to choose `Box<T>`, `Rc<T>`, or `RefCell<T>`: * `Rc<T>` enables multiple owners of the same data; `Box<T>` and `RefCell<T>` have single owners. * `Box<T>` allows immutable or mutable borrows checked at compile time; `Rc<T>` allows only immutable borrows checked at compile time; `RefCell<T>` allows immutable or mutable borrows checked at runtime. * Because `RefCell<T>` allows mutable borrows checked at runtime, you can mutate the value inside the `RefCell<T>` even when the `RefCell<T>` is immutable. Mutating the value inside an immutable value is the *interior mutability* pattern. Let’s look at a situation in which interior mutability is useful and examine how it’s possible. ### Interior Mutability: A Mutable Borrow to an Immutable Value A consequence of the borrowing rules is that when you have an immutable value, you can’t borrow it mutably. For example, this code won’t compile: ``` fn main() { let x = 5; let y = &mut x; } ``` If you tried to compile this code, you’d get the following error: ``` $ cargo run Compiling borrowing v0.1.0 (file:///projects/borrowing) error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> src/main.rs:3:13 | 2 | let x = 5; | - help: consider changing this to be mutable: `mut x` 3 | let y = &mut x; | ^^^^^^ cannot borrow as mutable For more information about this error, try `rustc --explain E0596`. error: could not compile `borrowing` due to previous error ``` However, there are situations in which it would be useful for a value to mutate itself in its methods but appear immutable to other code. Code outside the value’s methods would not be able to mutate the value. Using `RefCell<T>` is one way to get the ability to have interior mutability, but `RefCell<T>` doesn’t get around the borrowing rules completely: the borrow checker in the compiler allows this interior mutability, and the borrowing rules are checked at runtime instead. If you violate the rules, you’ll get a `panic!` instead of a compiler error. Let’s work through a practical example where we can use `RefCell<T>` to mutate an immutable value and see why that is useful. #### A Use Case for Interior Mutability: Mock Objects Sometimes during testing a programmer will use a type in place of another type, in order to observe particular behavior and assert it's implemented correctly. This placeholder type is called a *test double*. Think of it in the sense of a "stunt double" in filmmaking, where a person steps in and substitutes for an actor to do a particular tricky scene. Test doubles stand in for other types when we're running tests. *Mock objects* are specific types of test doubles that record what happens during a test so you can assert that the correct actions took place. Rust doesn’t have objects in the same sense as other languages have objects, and Rust doesn’t have mock object functionality built into the standard library as some other languages do. However, you can definitely create a struct that will serve the same purposes as a mock object. Here’s the scenario we’ll test: we’ll create a library that tracks a value against a maximum value and sends messages based on how close to the maximum value the current value is. This library could be used to keep track of a user’s quota for the number of API calls they’re allowed to make, for example. Our library will only provide the functionality of tracking how close to the maximum a value is and what the messages should be at what times. Applications that use our library will be expected to provide the mechanism for sending the messages: the application could put a message in the application, send an email, send a text message, or something else. The library doesn’t need to know that detail. All it needs is something that implements a trait we’ll provide called `Messenger`. Listing 15-20 shows the library code: Filename: src/lib.rs ``` pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percentage_of_max = self.value as f64 / self.max as f64; if percentage_of_max >= 1.0 { self.messenger.send("Error: You are over your quota!"); } else if percentage_of_max >= 0.9 { self.messenger .send("Urgent warning: You've used up over 90% of your quota!"); } else if percentage_of_max >= 0.75 { self.messenger .send("Warning: You've used up over 75% of your quota!"); } } } ``` Listing 15-20: A library to keep track of how close a value is to a maximum value and warn when the value is at certain levels One important part of this code is that the `Messenger` trait has one method called `send` that takes an immutable reference to `self` and the text of the message. This trait is the interface our mock object needs to implement so that the mock can be used in the same way a real object is. The other important part is that we want to test the behavior of the `set_value` method on the `LimitTracker`. We can change what we pass in for the `value` parameter, but `set_value` doesn’t return anything for us to make assertions on. We want to be able to say that if we create a `LimitTracker` with something that implements the `Messenger` trait and a particular value for `max`, when we pass different numbers for `value`, the messenger is told to send the appropriate messages. We need a mock object that, instead of sending an email or text message when we call `send`, will only keep track of the messages it’s told to send. We can create a new instance of the mock object, create a `LimitTracker` that uses the mock object, call the `set_value` method on `LimitTracker`, and then check that the mock object has the messages we expect. Listing 15-21 shows an attempt to implement a mock object to do just that, but the borrow checker won’t allow it: Filename: src/lib.rs ``` pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percentage_of_max = self.value as f64 / self.max as f64; if percentage_of_max >= 1.0 { self.messenger.send("Error: You are over your quota!"); } else if percentage_of_max >= 0.9 { self.messenger .send("Urgent warning: You've used up over 90% of your quota!"); } else if percentage_of_max >= 0.75 { self.messenger .send("Warning: You've used up over 75% of your quota!"); } } } #[cfg(test)] mod tests { use super::*; struct MockMessenger { sent_messages: Vec<String>, } impl MockMessenger { fn new() -> MockMessenger { MockMessenger { sent_messages: vec![], } } } impl Messenger for MockMessenger { fn send(&self, message: &str) { self.sent_messages.push(String::from(message)); } } #[test] fn it_sends_an_over_75_percent_warning_message() { let mock_messenger = MockMessenger::new(); let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); limit_tracker.set_value(80); assert_eq!(mock_messenger.sent_messages.len(), 1); } } ``` Listing 15-21: An attempt to implement a `MockMessenger` that isn’t allowed by the borrow checker This test code defines a `MockMessenger` struct that has a `sent_messages` field with a `Vec` of `String` values to keep track of the messages it’s told to send. We also define an associated function `new` to make it convenient to create new `MockMessenger` values that start with an empty list of messages. We then implement the `Messenger` trait for `MockMessenger` so we can give a `MockMessenger` to a `LimitTracker`. In the definition of the `send` method, we take the message passed in as a parameter and store it in the `MockMessenger` list of `sent_messages`. In the test, we’re testing what happens when the `LimitTracker` is told to set `value` to something that is more than 75 percent of the `max` value. First, we create a new `MockMessenger`, which will start with an empty list of messages. Then we create a new `LimitTracker` and give it a reference to the new `MockMessenger` and a `max` value of 100. We call the `set_value` method on the `LimitTracker` with a value of 80, which is more than 75 percent of 100. Then we assert that the list of messages that the `MockMessenger` is keeping track of should now have one message in it. However, there’s one problem with this test, as shown here: ``` $ cargo test Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference --> src/lib.rs:58:13 | 2 | fn send(&self, msg: &str); | ----- help: consider changing that to be a mutable reference: `&mut self` ... 58 | self.sent_messages.push(String::from(message)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable For more information about this error, try `rustc --explain E0596`. error: could not compile `limit-tracker` due to previous error warning: build failed, waiting for other jobs to finish... ``` We can’t modify the `MockMessenger` to keep track of the messages, because the `send` method takes an immutable reference to `self`. We also can’t take the suggestion from the error text to use `&mut self` instead, because then the signature of `send` wouldn’t match the signature in the `Messenger` trait definition (feel free to try and see what error message you get). This is a situation in which interior mutability can help! We’ll store the `sent_messages` within a `RefCell<T>`, and then the `send` method will be able to modify `sent_messages` to store the messages we’ve seen. Listing 15-22 shows what that looks like: Filename: src/lib.rs ``` pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percentage_of_max = self.value as f64 / self.max as f64; if percentage_of_max >= 1.0 { self.messenger.send("Error: You are over your quota!"); } else if percentage_of_max >= 0.9 { self.messenger .send("Urgent warning: You've used up over 90% of your quota!"); } else if percentage_of_max >= 0.75 { self.messenger .send("Warning: You've used up over 75% of your quota!"); } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; struct MockMessenger { sent_messages: RefCell<Vec<String>>, } impl MockMessenger { fn new() -> MockMessenger { MockMessenger { sent_messages: RefCell::new(vec![]), } } } impl Messenger for MockMessenger { fn send(&self, message: &str) { self.sent_messages.borrow_mut().push(String::from(message)); } } #[test] fn it_sends_an_over_75_percent_warning_message() { // --snip-- let mock_messenger = MockMessenger::new(); let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); limit_tracker.set_value(80); assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); } } ``` Listing 15-22: Using `RefCell<T>` to mutate an inner value while the outer value is considered immutable The `sent_messages` field is now of type `RefCell<Vec<String>>` instead of `Vec<String>`. In the `new` function, we create a new `RefCell<Vec<String>>` instance around the empty vector. For the implementation of the `send` method, the first parameter is still an immutable borrow of `self`, which matches the trait definition. We call `borrow_mut` on the `RefCell<Vec<String>>` in `self.sent_messages` to get a mutable reference to the value inside the `RefCell<Vec<String>>`, which is the vector. Then we can call `push` on the mutable reference to the vector to keep track of the messages sent during the test. The last change we have to make is in the assertion: to see how many items are in the inner vector, we call `borrow` on the `RefCell<Vec<String>>` to get an immutable reference to the vector. Now that you’ve seen how to use `RefCell<T>`, let’s dig into how it works! #### Keeping Track of Borrows at Runtime with `RefCell<T>` When creating immutable and mutable references, we use the `&` and `&mut` syntax, respectively. With `RefCell<T>`, we use the `borrow` and `borrow_mut` methods, which are part of the safe API that belongs to `RefCell<T>`. The `borrow` method returns the smart pointer type `Ref<T>`, and `borrow_mut` returns the smart pointer type `RefMut<T>`. Both types implement `Deref`, so we can treat them like regular references. The `RefCell<T>` keeps track of how many `Ref<T>` and `RefMut<T>` smart pointers are currently active. Every time we call `borrow`, the `RefCell<T>` increases its count of how many immutable borrows are active. When a `Ref<T>` value goes out of scope, the count of immutable borrows goes down by one. Just like the compile-time borrowing rules, `RefCell<T>` lets us have many immutable borrows or one mutable borrow at any point in time. If we try to violate these rules, rather than getting a compiler error as we would with references, the implementation of `RefCell<T>` will panic at runtime. Listing 15-23 shows a modification of the implementation of `send` in Listing 15-22. We’re deliberately trying to create two mutable borrows active for the same scope to illustrate that `RefCell<T>` prevents us from doing this at runtime. Filename: src/lib.rs ``` pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percentage_of_max = self.value as f64 / self.max as f64; if percentage_of_max >= 1.0 { self.messenger.send("Error: You are over your quota!"); } else if percentage_of_max >= 0.9 { self.messenger .send("Urgent warning: You've used up over 90% of your quota!"); } else if percentage_of_max >= 0.75 { self.messenger .send("Warning: You've used up over 75% of your quota!"); } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; struct MockMessenger { sent_messages: RefCell<Vec<String>>, } impl MockMessenger { fn new() -> MockMessenger { MockMessenger { sent_messages: RefCell::new(vec![]), } } } impl Messenger for MockMessenger { fn send(&self, message: &str) { let mut one_borrow = self.sent_messages.borrow_mut(); let mut two_borrow = self.sent_messages.borrow_mut(); one_borrow.push(String::from(message)); two_borrow.push(String::from(message)); } } #[test] fn it_sends_an_over_75_percent_warning_message() { let mock_messenger = MockMessenger::new(); let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); limit_tracker.set_value(80); assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); } } ``` Listing 15-23: Creating two mutable references in the same scope to see that `RefCell<T>` will panic We create a variable `one_borrow` for the `RefMut<T>` smart pointer returned from `borrow_mut`. Then we create another mutable borrow in the same way in the variable `two_borrow`. This makes two mutable references in the same scope, which isn’t allowed. When we run the tests for our library, the code in Listing 15-23 will compile without any errors, but the test will fail: ``` $ cargo test Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) Finished test [unoptimized + debuginfo] target(s) in 0.91s Running unittests src/lib.rs (target/debug/deps/limit_tracker-e599811fa246dbde) running 1 test test tests::it_sends_an_over_75_percent_warning_message ... FAILED failures: ---- tests::it_sends_an_over_75_percent_warning_message stdout ---- thread 'main' panicked at 'already borrowed: BorrowMutError', src/lib.rs:60:53 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::it_sends_an_over_75_percent_warning_message test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Notice that the code panicked with the message `already borrowed: BorrowMutError`. This is how `RefCell<T>` handles violations of the borrowing rules at runtime. Choosing to catch borrowing errors at runtime rather than compile time, as we've done here, means you'd potentially be finding mistakes in your code later in the development process: possibly not until your code was deployed to production. Also, your code would incur a small runtime performance penalty as a result of keeping track of the borrows at runtime rather than compile time. However, using `RefCell<T>` makes it possible to write a mock object that can modify itself to keep track of the messages it has seen while you’re using it in a context where only immutable values are allowed. You can use `RefCell<T>` despite its trade-offs to get more functionality than regular references provide. ### Having Multiple Owners of Mutable Data by Combining `Rc<T>` and `RefCell<T>` A common way to use `RefCell<T>` is in combination with `Rc<T>`. Recall that `Rc<T>` lets you have multiple owners of some data, but it only gives immutable access to that data. If you have an `Rc<T>` that holds a `RefCell<T>`, you can get a value that can have multiple owners *and* that you can mutate! For example, recall the cons list example in Listing 15-18 where we used `Rc<T>` to allow multiple lists to share ownership of another list. Because `Rc<T>` holds only immutable values, we can’t change any of the values in the list once we’ve created them. Let’s add in `RefCell<T>` to gain the ability to change the values in the lists. Listing 15-24 shows that by using a `RefCell<T>` in the `Cons` definition, we can modify the value stored in all the lists: Filename: src/main.rs ``` #[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; fn main() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a)); *value.borrow_mut() += 10; println!("a after = {:?}", a); println!("b after = {:?}", b); println!("c after = {:?}", c); } ``` Listing 15-24: Using `Rc<RefCell<i32>>` to create a `List` that we can mutate We create a value that is an instance of `Rc<RefCell<i32>>` and store it in a variable named `value` so we can access it directly later. Then we create a `List` in `a` with a `Cons` variant that holds `value`. We need to clone `value` so both `a` and `value` have ownership of the inner `5` value rather than transferring ownership from `value` to `a` or having `a` borrow from `value`. We wrap the list `a` in an `Rc<T>` so when we create lists `b` and `c`, they can both refer to `a`, which is what we did in Listing 15-18. After we’ve created the lists in `a`, `b`, and `c`, we want to add 10 to the value in `value`. We do this by calling `borrow_mut` on `value`, which uses the automatic dereferencing feature we discussed in Chapter 5 (see the section [“Where’s the `->` Operator?”](ch05-03-method-syntax#wheres-the---operator)) to dereference the `Rc<T>` to the inner `RefCell<T>` value. The `borrow_mut` method returns a `RefMut<T>` smart pointer, and we use the dereference operator on it and change the inner value. When we print `a`, `b`, and `c`, we can see that they all have the modified value of 15 rather than 5: ``` $ cargo run Compiling cons-list v0.1.0 (file:///projects/cons-list) Finished dev [unoptimized + debuginfo] target(s) in 0.63s Running `target/debug/cons-list` a after = Cons(RefCell { value: 15 }, Nil) b after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil)) c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil)) ``` This technique is pretty neat! By using `RefCell<T>`, we have an outwardly immutable `List` value. But we can use the methods on `RefCell<T>` that provide access to its interior mutability so we can modify our data when we need to. The runtime checks of the borrowing rules protect us from data races, and it’s sometimes worth trading a bit of speed for this flexibility in our data structures. Note that `RefCell<T>` does not work for multithreaded code! `Mutex<T>` is the thread-safe version of `RefCell<T>` and we’ll discuss `Mutex<T>` in Chapter 16.
programming_docs
rust More About Cargo and Crates.io More About Cargo and Crates.io ============================== So far we’ve used only the most basic features of Cargo to build, run, and test our code, but it can do a lot more. In this chapter, we’ll discuss some of its other, more advanced features to show you how to do the following: * Customize your build through release profiles * Publish libraries on [crates.io](https://crates.io/) * Organize large projects with workspaces * Install binaries from [crates.io](https://crates.io/) * Extend Cargo using custom commands Cargo can do even more than the functionality we cover in this chapter, so for a full explanation of all its features, see [its documentation](https://doc.rust-lang.org/cargo/index.html). rust None Closures: Anonymous Functions that Capture Their Environment ------------------------------------------------------------ Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined. We’ll demonstrate how these closure features allow for code reuse and behavior customization. ### Capturing the Environment with Closures We’ll first examine how we can use closures to capture values from the environment they’re defined in for later use. Here’s the scenario: Every so often, our t-shirt company gives away an exclusive, limited-edition shirt to someone on our mailing list as a promotion. People on the mailing list can optionally add their favorite color to their profile. If the person chosen for a free shirt has their favorite color set, they get that color shirt. If the person hasn’t specified a favorite color, they get whatever color the company currently has the most of. There are many ways to implement this. For this example, we’re going to use an enum called `ShirtColor` that has the variants `Red` and `Blue` (limiting the number of colors available for simplicity). We represent the company’s inventory with an `Inventory` struct that has a field named `shirts` that contains a `Vec<ShirtColor>` representing the shirt colors currently in stock. The method `giveaway` defined on `Inventory` gets the optional shirt color preference of the free shirt winner, and returns the shirt color the person will get. This setup is shown in Listing 13-1: Filename: src/main.rs ``` #[derive(Debug, PartialEq, Copy, Clone)] enum ShirtColor { Red, Blue, } struct Inventory { shirts: Vec<ShirtColor>, } impl Inventory { fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor { user_preference.unwrap_or_else(|| self.most_stocked()) } fn most_stocked(&self) -> ShirtColor { let mut num_red = 0; let mut num_blue = 0; for color in &self.shirts { match color { ShirtColor::Red => num_red += 1, ShirtColor::Blue => num_blue += 1, } } if num_red > num_blue { ShirtColor::Red } else { ShirtColor::Blue } } } fn main() { let store = Inventory { shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue], }; let user_pref1 = Some(ShirtColor::Red); let giveaway1 = store.giveaway(user_pref1); println!( "The user with preference {:?} gets {:?}", user_pref1, giveaway1 ); let user_pref2 = None; let giveaway2 = store.giveaway(user_pref2); println!( "The user with preference {:?} gets {:?}", user_pref2, giveaway2 ); } ``` Listing 13-1: Shirt company giveaway situation The `store` defined in `main` has two blue shirts and one red shirt remaining to distribute for this limited-edition promotion. We call the `giveaway` method for a user with a preference for a red shirt and a user without any preference. Again, this code could be implemented in many ways, and here, to focus on closures, we’ve stuck to concepts you’ve already learned except for the body of the `giveaway` method that uses a closure. In the `giveaway` method, we get the user preference as a parameter of type `Option<ShirtColor>` and call the `unwrap_or_else` method on `user_preference`. The [`unwrap_or_else` method on `Option<T>`](../std/option/enum.option#method.unwrap_or_else) is defined by the standard library. It takes one argument: a closure without any arguments that returns a value `T` (the same type stored in the `Some` variant of the `Option<T>`, in this case `ShirtColor`). If the `Option<T>` is the `Some` variant, `unwrap_or_else` returns the value from within the `Some`. If the `Option<T>` is the `None` variant, `unwrap_or_else` calls the closure and returns the value returned by the closure. We specify the closure expression `|| self.most_stocked()` as the argument to `unwrap_or_else`. This is a closure that takes no parameters itself (if the closure had parameters, they would appear between the two vertical bars). The body of the closure calls `self.most_stocked()`. We’re defining the closure here, and the implementation of `unwrap_or_else` will evaluate the closure later if the result is needed. Running this code prints: ``` $ cargo run Compiling shirt-company v0.1.0 (file:///projects/shirt-company) Finished dev [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/shirt-company` The user with preference Some(Red) gets Red The user with preference None gets Blue ``` One interesting aspect here is that we’ve passed a closure that calls `self.most_stocked()` on the current `Inventory` instance. The standard library didn’t need to know anything about the `Inventory` or `ShirtColor` types we defined, or the logic we want to use in this scenario. The closure captures an immutable reference to the `self` `Inventory` instance and passes it with the code we specify to the `unwrap_or_else` method. Functions, on the other hand, are not able to capture their environment in this way. ### Closure Type Inference and Annotation There are more differences between functions and closures. Closures don’t usually require you to annotate the types of the parameters or the return value like `fn` functions do. Type annotations are required on functions because the types are part of an explicit interface exposed to your users. Defining this interface rigidly is important for ensuring that everyone agrees on what types of values a function uses and returns. Closures, on the other hand, aren’t used in an exposed interface like this: they’re stored in variables and used without naming them and exposing them to users of our library. Closures are typically short and relevant only within a narrow context rather than in any arbitrary scenario. Within these limited contexts, the compiler can infer the types of the parameters and the return type, similar to how it’s able to infer the types of most variables (there are rare cases where the compiler needs closure type annotations too). As with variables, we can add type annotations if we want to increase explicitness and clarity at the cost of being more verbose than is strictly necessary. Annotating the types for a closure would look like the definition shown in Listing 13-2. In this example, we’re defining a closure and storing it in a variable rather than defining the closure in the spot we pass it as an argument as we did in Listing 13-1. Filename: src/main.rs ``` use std::thread; use std::time::Duration; fn generate_workout(intensity: u32, random_number: u32) { let expensive_closure = |num: u32| -> u32 { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }; if intensity < 25 { println!("Today, do {} pushups!", expensive_closure(intensity)); println!("Next, do {} situps!", expensive_closure(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure(intensity) ); } } } fn main() { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout(simulated_user_specified_value, simulated_random_number); } ``` Listing 13-2: Adding optional type annotations of the parameter and return value types in the closure With type annotations added, the syntax of closures looks more similar to the syntax of functions. Here we define a function that adds 1 to its parameter and a closure that has the same behavior, for comparison. We’ve added some spaces to line up the relevant parts. This illustrates how closure syntax is similar to function syntax except for the use of pipes and the amount of syntax that is optional: ``` fn add_one_v1 (x: u32) -> u32 { x + 1 } let add_one_v2 = |x: u32| -> u32 { x + 1 }; let add_one_v3 = |x| { x + 1 }; let add_one_v4 = |x| x + 1 ; ``` The first line shows a function definition, and the second line shows a fully annotated closure definition. In the third line, we remove the type annotations from the closure definition. In the fourth line, we remove the brackets, which are optional because the closure body has only one expression. These are all valid definitions that will produce the same behavior when they’re called. The `add_one_v3` and `add_one_v4` lines require the closures to be evaluated to be able to compile because the types will be inferred from their usage. This is similar to `let v = Vec::new();` needing either type annotations or values of some type to be inserted into the `Vec` for Rust to be able to infer the type. For closure definitions, the compiler will infer one concrete type for each of their parameters and for their return value. For instance, Listing 13-3 shows the definition of a short closure that just returns the value it receives as a parameter. This closure isn’t very useful except for the purposes of this example. Note that we haven’t added any type annotations to the definition. Because there are no type annotations, we can call the closure with any type, which we’ve done here with `String` the first time. If we then try to call `example_closure` with an integer, we’ll get an error. Filename: src/main.rs ``` fn main() { let example_closure = |x| x; let s = example_closure(String::from("hello")); let n = example_closure(5); } ``` Listing 13-3: Attempting to call a closure whose types are inferred with two different types The compiler gives us this error: ``` $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) error[E0308]: mismatched types --> src/main.rs:5:29 | 5 | let n = example_closure(5); | ^- help: try using a conversion method: `.to_string()` | | | expected struct `String`, found integer For more information about this error, try `rustc --explain E0308`. error: could not compile `closure-example` due to previous error ``` The first time we call `example_closure` with the `String` value, the compiler infers the type of `x` and the return type of the closure to be `String`. Those types are then locked into the closure in `example_closure`, and we get a type error when we next try to use a different type with the same closure. ### Capturing References or Moving Ownership Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership. The closure will decide which of these to use based on what the body of the function does with the captured values. In Listing 13-4, we define a closure that captures an immutable reference to the vector named `list` because it only needs an immutable reference to print the value: Filename: src/main.rs ``` fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); let only_borrows = || println!("From closure: {:?}", list); println!("Before calling closure: {:?}", list); only_borrows(); println!("After calling closure: {:?}", list); } ``` Listing 13-4: Defining and calling a closure that captures an immutable reference This example also illustrates that a variable can bind to a closure definition, and we can later call the closure by using the variable name and parentheses as if the variable name were a function name. Because we can have multiple immutable references to `list` at the same time, `list` is still accessible from the code before the closure definition, after the closure definition but before the closure is called, and after the closure is called. This code compiles, runs, and prints: ``` $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/closure-example` Before defining closure: [1, 2, 3] Before calling closure: [1, 2, 3] From closure: [1, 2, 3] After calling closure: [1, 2, 3] ``` Next, in Listing 13-5, we change the closure body so that it adds an element to the `list` vector. The closure now captures a mutable reference: Filename: src/main.rs ``` fn main() { let mut list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); let mut borrows_mutably = || list.push(7); borrows_mutably(); println!("After calling closure: {:?}", list); } ``` Listing 13-5: Defining and calling a closure that captures a mutable reference This code compiles, runs, and prints: ``` $ cargo run Compiling closure-example v0.1.0 (file:///projects/closure-example) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/closure-example` Before defining closure: [1, 2, 3] After calling closure: [1, 2, 3, 7] ``` Note that there’s no longer a `println!` between the definition and the call of the `borrows_mutably` closure: when `borrows_mutably` is defined, it captures a mutable reference to `list`. We don’t use the closure again after the closure is called, so the mutable borrow ends. Between the closure definition and the closure call, an immutable borrow to print isn’t allowed because no other borrows are allowed when there’s a mutable borrow. Try adding a `println!` there to see what error message you get! If you want to force the closure to take ownership of the values it uses in the environment even though the body of the closure doesn’t strictly need ownership, you can use the `move` keyword before the parameter list. This technique is mostly useful when passing a closure to a new thread to move the data so that it’s owned by the new thread. We’ll discuss threads and why you would want to use them in detail in Chapter 16 when we talk about concurrency, but for now, let’s briefly explore spawning a new thread using a closure that needs the `move` keyword. Listing 13-6 shows Listing 13-4 modified to print the vector in a new thread rather than in the main thread: Filename: src/main.rs ``` use std::thread; fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); thread::spawn(move || println!("From thread: {:?}", list)) .join() .unwrap(); } ``` Listing 13-6: Using `move` to force the closure for the thread to take ownership of `list` We spawn a new thread, giving the thread a closure to run as an argument. The closure body prints out the list. In Listing 13-4, the closure only captured `list` using an immutable reference because that's the least amount of access to `list` needed to print it. In this example, even though the closure body still only needs an immutable reference, we need to specify that `list` should be moved into the closure by putting the `move` keyword at the beginning of the closure definition. The new thread might finish before the rest of the main thread finishes, or the main thread might finish first. If the main thread maintained ownership of `list` but ended before the new thread did and dropped `list`, the immutable reference in the thread would be invalid. Therefore, the compiler requires that `list` be moved into the closure given to the new thread so the reference will be valid. Try removing the `move` keyword or using `list` in the main thread after the closure is defined to see what compiler errors you get! ### Moving Captured Values Out of Closures and the `Fn` Traits Once a closure has captured a reference or captured ownership of a value from the environment where the closure is defined (thus affecting what, if anything, is moved *into* the closure), the code in the body of the closure defines what happens to the references or values when the closure is evaluated later (thus affecting what, if anything, is moved *out of* the closure). A closure body can do any of the following: move a captured value out of the closure, mutate the captured value, neither move nor mutate the value, or capture nothing from the environment to begin with. The way a closure captures and handles values from the environment affects which traits the closure implements, and traits are how functions and structs can specify what kinds of closures they can use. Closures will automatically implement one, two, or all three of these `Fn` traits, in an additive fashion, depending on how the closure’s body handles the values: 1. `FnOnce` applies to closures that can be called once. All closures implement at least this trait, because all closures can be called. A closure that moves captured values out of its body will only implement `FnOnce` and none of the other `Fn` traits, because it can only be called once. 2. `FnMut` applies to closures that don’t move captured values out of their body, but that might mutate the captured values. These closures can be called more than once. 3. `Fn` applies to closures that don’t move captured values out of their body and that don’t mutate captured values, as well as closures that capture nothing from their environment. These closures can be called more than once without mutating their environment, which is important in cases such as calling a closure multiple times concurrently. Let’s look at the definition of the `unwrap_or_else` method on `Option<T>` that we used in Listing 13-1: ``` impl<T> Option<T> { pub fn unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T { match self { Some(x) => x, None => f(), } } } ``` Recall that `T` is the generic type representing the type of the value in the `Some` variant of an `Option`. That type `T` is also the return type of the `unwrap_or_else` function: code that calls `unwrap_or_else` on an `Option<String>`, for example, will get a `String`. Next, notice that the `unwrap_or_else` function has the additional generic type parameter `F`. The `F` type is the type of the parameter named `f`, which is the closure we provide when calling `unwrap_or_else`. The trait bound specified on the generic type `F` is `FnOnce() -> T`, which means `F` must be able to be called once, take no arguments, and return a `T`. Using `FnOnce` in the trait bound expresses the constraint that `unwrap_or_else` is only going to call `f` at most one time. In the body of `unwrap_or_else`, we can see that if the `Option` is `Some`, `f` won’t be called. If the `Option` is `None`, `f` will be called once. Because all closures implement `FnOnce`, `unwrap_or_else` accepts the most different kinds of closures and is as flexible as it can be. > Note: Functions can implement all three of the `Fn` traits too. If what we want to do doesn’t require capturing a value from the environment, we can use the name of a function rather than a closure where we need something that implements one of the `Fn` traits. For example, on an `Option<Vec<T>>` value, we could call `unwrap_or_else(Vec::new)` to get a new, empty vector if the value is `None`. > > Now let’s look at the standard library method `sort_by_key` defined on slices, to see how that differs from `unwrap_or_else` and why `sort_by_key` uses `FnMut` instead of `FnOnce` for the trait bound. The closure gets one argument in the form of a reference to the current item in the slice being considered, and returns a value of type `K` that can be ordered. This function is useful when you want to sort a slice by a particular attribute of each item. In Listing 13-7, we have a list of `Rectangle` instances and we use `sort_by_key` to order them by their `width` attribute from low to high: Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [ Rectangle { width: 10, height: 1 }, Rectangle { width: 3, height: 5 }, Rectangle { width: 7, height: 12 }, ]; list.sort_by_key(|r| r.width); println!("{:#?}", list); } ``` Listing 13-7: Using `sort_by_key` to order rectangles by width This code prints: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished dev [unoptimized + debuginfo] target(s) in 0.41s Running `target/debug/rectangles` [ Rectangle { width: 3, height: 5, }, Rectangle { width: 7, height: 12, }, Rectangle { width: 10, height: 1, }, ] ``` The reason `sort_by_key` is defined to take an `FnMut` closure is that it calls the closure multiple times: once for each item in the slice. The closure `|r| r.width` doesn’t capture, mutate, or move out anything from its environment, so it meets the trait bound requirements. In contrast, Listing 13-8 shows an example of a closure that implements just the `FnOnce` trait, because it moves a value out of the environment. The compiler won’t let us use this closure with `sort_by_key`: Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [ Rectangle { width: 10, height: 1 }, Rectangle { width: 3, height: 5 }, Rectangle { width: 7, height: 12 }, ]; let mut sort_operations = vec![]; let value = String::from("by key called"); list.sort_by_key(|r| { sort_operations.push(value); r.width }); println!("{:#?}", list); } ``` Listing 13-8: Attempting to use an `FnOnce` closure with `sort_by_key` This is a contrived, convoluted way (that doesn’t work) to try and count the number of times `sort_by_key` gets called when sorting `list`. This code attempts to do this counting by pushing `value`—a `String` from the closure’s environment—into the `sort_operations` vector. The closure captures `value` then moves `value` out of the closure by transferring ownership of `value` to the `sort_operations` vector. This closure can be called once; trying to call it a second time wouldn’t work because `value` would no longer be in the environment to be pushed into `sort_operations` again! Therefore, this closure only implements `FnOnce`. When we try to compile this code, we get this error that `value` can’t be moved out of the closure because the closure must implement `FnMut`: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure --> src/main.rs:18:30 | 15 | let value = String::from("by key called"); | ----- captured outer variable 16 | 17 | list.sort_by_key(|r| { | ______________________- 18 | | sort_operations.push(value); | | ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait 19 | | r.width 20 | | }); | |_____- captured by this `FnMut` closure For more information about this error, try `rustc --explain E0507`. error: could not compile `rectangles` due to previous error ``` The error points to the line in the closure body that moves `value` out of the environment. To fix this, we need to change the closure body so that it doesn’t move values out of the environment. To count the number of times `sort_by_key` is called, keeping a counter in the environment and incrementing its value in the closure body is a more straightforward way to calculate that. The closure in Listing 13-9 works with `sort_by_key` because it is only capturing a mutable reference to the `num_sort_operations` counter and can therefore be called more than once: Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [ Rectangle { width: 10, height: 1 }, Rectangle { width: 3, height: 5 }, Rectangle { width: 7, height: 12 }, ]; let mut num_sort_operations = 0; list.sort_by_key(|r| { num_sort_operations += 1; r.width }); println!("{:#?}, sorted in {num_sort_operations} operations", list); } ``` Listing 13-9: Using an `FnMut` closure with `sort_by_key` is allowed The `Fn` traits are important when defining or using functions or types that make use of closures. In the next section, we’ll discuss iterators. Many iterator methods take closure arguments, so keep these closure details in mind as we continue!
programming_docs
rust Patterns and Matching Patterns and Matching ===================== *Patterns* are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with `match` expressions and other constructs gives you more control over a program’s control flow. A pattern consists of some combination of the following: * Literals * Destructured arrays, enums, structs, or tuples * Variables * Wildcards * Placeholders Some example patterns include `x`, `(a, 3)`, and `Some(Color::Red)`. In the contexts in which patterns are valid, these components describe the shape of data. Our program then matches values against the patterns to determine whether it has the correct shape of data to continue running a particular piece of code. To use a pattern, we compare it to some value. If the pattern matches the value, we use the value parts in our code. Recall the `match` expressions in Chapter 6 that used patterns, such as the coin-sorting machine example. If the value fits the shape of the pattern, we can use the named pieces. If it doesn’t, the code associated with the pattern won’t run. This chapter is a reference on all things related to patterns. We’ll cover the valid places to use patterns, the difference between refutable and irrefutable patterns, and the different kinds of pattern syntax that you might see. By the end of the chapter, you’ll know how to use patterns to express many concepts in a clear way. rust Turning Our Single-Threaded Server into a Multithreaded Server Turning Our Single-Threaded Server into a Multithreaded Server ============================================================== Right now, the server will process each request in turn, meaning it won’t process a second connection until the first is finished processing. If the server received more and more requests, this serial execution would be less and less optimal. If the server receives a request that takes a long time to process, subsequent requests will have to wait until the long request is finished, even if the new requests can be processed quickly. We’ll need to fix this, but first, we’ll look at the problem in action. ### Simulating a Slow Request in the Current Server Implementation We’ll look at how a slow-processing request can affect other requests made to our current server implementation. Listing 20-10 implements handling a request to */sleep* with a simulated slow response that will cause the server to sleep for 5 seconds before responding. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; // --snip-- fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { // --snip-- let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; // --snip-- let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-10: Simulating a slow request by sleeping for 5 seconds We switched from `if` to `match` now that we have three cases. We need to explicitly match on a slice of `request_line` to pattern match against the string literal values; `match` doesn’t do automatic referencing and dereferencing like the equality method does. The first arm is the same as the `if` block from Listing 20-9. The second arm matches a request to */sleep*. When that request is received, the server will sleep for 5 seconds before rendering the successful HTML page. The third arm is the same as the `else` block from Listing 20-9. You can see how primitive our server is: real libraries would handle the recognition of multiple requests in a much less verbose way! Start the server using `cargo run`. Then open two browser windows: one for *http://127.0.0.1:7878/* and the other for *http://127.0.0.1:7878/sleep*. If you enter the */* URI a few times, as before, you’ll see it respond quickly. But if you enter */sleep* and then load */*, you’ll see that */* waits until `sleep` has slept for its full 5 seconds before loading. There are multiple techniques we could use to avoid requests backing up behind a slow request; the one we’ll implement is a thread pool. ### Improving Throughput with a Thread Pool A *thread pool* is a group of spawned threads that are waiting and ready to handle a task. When the program receives a new task, it assigns one of the threads in the pool to the task, and that thread will process the task. The remaining threads in the pool are available to handle any other tasks that come in while the first thread is processing. When the first thread is done processing its task, it’s returned to the pool of idle threads, ready to handle a new task. A thread pool allows you to process connections concurrently, increasing the throughput of your server. We’ll limit the number of threads in the pool to a small number to protect us from Denial of Service (DoS) attacks; if we had our program create a new thread for each request as it came in, someone making 10 million requests to our server could create havoc by using up all our server’s resources and grinding the processing of requests to a halt. Rather than spawning unlimited threads, then, we’ll have a fixed number of threads waiting in the pool. Requests that come in are sent to the pool for processing. The pool will maintain a queue of incoming requests. Each of the threads in the pool will pop off a request from this queue, handle the request, and then ask the queue for another request. With this design, we can process up to `N` requests concurrently, where `N` is the number of threads. If each thread is responding to a long-running request, subsequent requests can still back up in the queue, but we’ve increased the number of long-running requests we can handle before reaching that point. This technique is just one of many ways to improve the throughput of a web server. Other options you might explore are the *fork/join model*, the *single-threaded async I/O model*, or the *multi-threaded async I/O model*. If you’re interested in this topic, you can read more about other solutions and try to implement them; with a low-level language like Rust, all of these options are possible. Before we begin implementing a thread pool, let’s talk about what using the pool should look like. When you’re trying to design code, writing the client interface first can help guide your design. Write the API of the code so it’s structured in the way you want to call it; then implement the functionality within that structure rather than implementing the functionality and then designing the public API. Similar to how we used test-driven development in the project in Chapter 12, we’ll use compiler-driven development here. We’ll write the code that calls the functions we want, and then we’ll look at errors from the compiler to determine what we should change next to get the code to work. Before we do that, however, we’ll explore the technique we’re not going to use as a starting point. #### Spawning a Thread for Each Request First, let’s explore how our code might look if it did create a new thread for every connection. As mentioned earlier, this isn’t our final plan due to the problems with potentially spawning an unlimited number of threads, but it is a starting point to get a working multithreaded server first. Then we’ll add the thread pool as an improvement, and contrasting the two solutions will be easier. Listing 20-11 shows the changes to make to `main` to spawn a new thread to handle each stream within the `for` loop. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); thread::spawn(|| { handle_connection(stream); }); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-11: Spawning a new thread for each stream As you learned in Chapter 16, `thread::spawn` will create a new thread and then run the code in the closure in the new thread. If you run this code and load */sleep* in your browser, then */* in two more browser tabs, you’ll indeed see that the requests to */* don’t have to wait for */sleep* to finish. However, as we mentioned, this will eventually overwhelm the system because you’d be making new threads without any limit. #### Creating a Finite Number of Threads We want our thread pool to work in a similar, familiar way so switching from threads to a thread pool doesn’t require large changes to the code that uses our API. Listing 20-12 shows the hypothetical interface for a `ThreadPool` struct we want to use instead of `thread::spawn`. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming() { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-12: Our ideal `ThreadPool` interface We use `ThreadPool::new` to create a new thread pool with a configurable number of threads, in this case four. Then, in the `for` loop, `pool.execute` has a similar interface as `thread::spawn` in that it takes a closure the pool should run for each stream. We need to implement `pool.execute` so it takes the closure and gives it to a thread in the pool to run. This code won’t yet compile, but we’ll try so the compiler can guide us in how to fix it. #### Building `ThreadPool` Using Compiler Driven Development Make the changes in Listing 20-12 to *src/main.rs*, and then let’s use the compiler errors from `cargo check` to drive our development. Here is the first error we get: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0433]: failed to resolve: use of undeclared type `ThreadPool` --> src/main.rs:11:16 | 11 | let pool = ThreadPool::new(4); | ^^^^^^^^^^ use of undeclared type `ThreadPool` For more information about this error, try `rustc --explain E0433`. error: could not compile `hello` due to previous error ``` Great! This error tells us we need a `ThreadPool` type or module, so we’ll build one now. Our `ThreadPool` implementation will be independent of the kind of work our web server is doing. So, let’s switch the `hello` crate from a binary crate to a library crate to hold our `ThreadPool` implementation. After we change to a library crate, we could also use the separate thread pool library for any work we want to do using a thread pool, not just for serving web requests. Create a *src/lib.rs* that contains the following, which is the simplest definition of a `ThreadPool` struct that we can have for now: Filename: src/lib.rs ``` pub struct ThreadPool; ``` Then edit *main.rs* file to bring `ThreadPool` into scope from the library crate by adding the following code to the top of *src/main.rs*: Filename: src/main.rs ``` use hello::ThreadPool; use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming() { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` This code still won’t work, but let’s check it again to get the next error that we need to address: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0599]: no function or associated item named `new` found for struct `ThreadPool` in the current scope --> src/main.rs:12:28 | 12 | let pool = ThreadPool::new(4); | ^^^ function or associated item not found in `ThreadPool` For more information about this error, try `rustc --explain E0599`. error: could not compile `hello` due to previous error ``` This error indicates that next we need to create an associated function named `new` for `ThreadPool`. We also know that `new` needs to have one parameter that can accept `4` as an argument and should return a `ThreadPool` instance. Let’s implement the simplest `new` function that will have those characteristics: Filename: src/lib.rs ``` pub struct ThreadPool; impl ThreadPool { pub fn new(size: usize) -> ThreadPool { ThreadPool } } ``` We chose `usize` as the type of the `size` parameter, because we know that a negative number of threads doesn’t make any sense. We also know we’ll use this 4 as the number of elements in a collection of threads, which is what the `usize` type is for, as discussed in the [“Integer Types”](ch03-02-data-types#integer-types) section of Chapter 3. Let’s check the code again: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope --> src/main.rs:17:14 | 17 | pool.execute(|| { | ^^^^^^^ method not found in `ThreadPool` For more information about this error, try `rustc --explain E0599`. error: could not compile `hello` due to previous error ``` Now the error occurs because we don’t have an `execute` method on `ThreadPool`. Recall from the [“Creating a Finite Number of Threads”](#creating-a-finite-number-of-threads) section that we decided our thread pool should have an interface similar to `thread::spawn`. In addition, we’ll implement the `execute` function so it takes the closure it’s given and gives it to an idle thread in the pool to run. We’ll define the `execute` method on `ThreadPool` to take a closure as a parameter. Recall from the [“Moving Captured Values Out of the Closure and the `Fn` Traits”](ch13-01-closures#moving-captured-values-out-of-the-closure-and-the-fn-traits) section in Chapter 13 that we can take closures as parameters with three different traits: `Fn`, `FnMut`, and `FnOnce`. We need to decide which kind of closure to use here. We know we’ll end up doing something similar to the standard library `thread::spawn` implementation, so we can look at what bounds the signature of `thread::spawn` has on its parameter. The documentation shows us the following: ``` pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static, ``` The `F` type parameter is the one we’re concerned with here; the `T` type parameter is related to the return value, and we’re not concerned with that. We can see that `spawn` uses `FnOnce` as the trait bound on `F`. This is probably what we want as well, because we’ll eventually pass the argument we get in `execute` to `spawn`. We can be further confident that `FnOnce` is the trait we want to use because the thread for running a request will only execute that request’s closure one time, which matches the `Once` in `FnOnce`. The `F` type parameter also has the trait bound `Send` and the lifetime bound `'static`, which are useful in our situation: we need `Send` to transfer the closure from one thread to another and `'static` because we don’t know how long the thread will take to execute. Let’s create an `execute` method on `ThreadPool` that will take a generic parameter of type `F` with these bounds: Filename: src/lib.rs ``` pub struct ThreadPool; impl ThreadPool { // --snip-- pub fn new(size: usize) -> ThreadPool { ThreadPool } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } ``` We still use the `()` after `FnOnce` because this `FnOnce` represents a closure that takes no parameters and returns the unit type `()`. Just like function definitions, the return type can be omitted from the signature, but even if we have no parameters, we still need the parentheses. Again, this is the simplest implementation of the `execute` method: it does nothing, but we’re trying only to make our code compile. Let’s check it again: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) Finished dev [unoptimized + debuginfo] target(s) in 0.24s ``` It compiles! But note that if you try `cargo run` and make a request in the browser, you’ll see the errors in the browser that we saw at the beginning of the chapter. Our library isn’t actually calling the closure passed to `execute` yet! > Note: A saying you might hear about languages with strict compilers, such as Haskell and Rust, is “if the code compiles, it works.” But this saying is not universally true. Our project compiles, but it does absolutely nothing! If we were building a real, complete project, this would be a good time to start writing unit tests to check that the code compiles *and* has the behavior we want. > > #### Validating the Number of Threads in `new` We aren’t doing anything with the parameters to `new` and `execute`. Let’s implement the bodies of these functions with the behavior we want. To start, let’s think about `new`. Earlier we chose an unsigned type for the `size` parameter, because a pool with a negative number of threads makes no sense. However, a pool with zero threads also makes no sense, yet zero is a perfectly valid `usize`. We’ll add code to check that `size` is greater than zero before we return a `ThreadPool` instance and have the program panic if it receives a zero by using the `assert!` macro, as shown in Listing 20-13. Filename: src/lib.rs ``` pub struct ThreadPool; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); ThreadPool } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } ``` Listing 20-13: Implementing `ThreadPool::new` to panic if `size` is zero We’ve also added some documentation for our `ThreadPool` with doc comments. Note that we followed good documentation practices by adding a section that calls out the situations in which our function can panic, as discussed in Chapter 14. Try running `cargo doc --open` and clicking the `ThreadPool` struct to see what the generated docs for `new` look like! Instead of adding the `assert!` macro as we’ve done here, we could change `new` into `build` and return a `Result` like we did with `Config::build` in the I/O project in Listing 12-9. But we’ve decided in this case that trying to create a thread pool without any threads should be an unrecoverable error. If you’re feeling ambitious, try to write a function named `build` with the following signature to compare with the `new` function: ``` pub fn build(size: usize) -> Result<ThreadPool, PoolCreationError> { ``` #### Creating Space to Store the Threads Now that we have a way to know we have a valid number of threads to store in the pool, we can create those threads and store them in the `ThreadPool` struct before returning the struct. But how do we “store” a thread? Let’s take another look at the `thread::spawn` signature: ``` pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static, ``` The `spawn` function returns a `JoinHandle<T>`, where `T` is the type that the closure returns. Let’s try using `JoinHandle` too and see what happens. In our case, the closures we’re passing to the thread pool will handle the connection and not return anything, so `T` will be the unit type `()`. The code in Listing 20-14 will compile but doesn’t create any threads yet. We’ve changed the definition of `ThreadPool` to hold a vector of `thread::JoinHandle<()>` instances, initialized the vector with a capacity of `size`, set up a `for` loop that will run some code to create the threads, and returned a `ThreadPool` instance containing them. Filename: src/lib.rs ``` use std::thread; pub struct ThreadPool { threads: Vec<thread::JoinHandle<()>>, } impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let mut threads = Vec::with_capacity(size); for _ in 0..size { // create some threads and store them in the vector } ThreadPool { threads } } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } ``` Listing 20-14: Creating a vector for `ThreadPool` to hold the threads We’ve brought `std::thread` into scope in the library crate, because we’re using `thread::JoinHandle` as the type of the items in the vector in `ThreadPool`. Once a valid size is received, our `ThreadPool` creates a new vector that can hold `size` items. The `with_capacity` function performs the same task as `Vec::new` but with an important difference: it preallocates space in the vector. Because we know we need to store `size` elements in the vector, doing this allocation up front is slightly more efficient than using `Vec::new`, which resizes itself as elements are inserted. When you run `cargo check` again, it should succeed. #### A `Worker` Struct Responsible for Sending Code from the `ThreadPool` to a Thread We left a comment in the `for` loop in Listing 20-14 regarding the creation of threads. Here, we’ll look at how we actually create threads. The standard library provides `thread::spawn` as a way to create threads, and `thread::spawn` expects to get some code the thread should run as soon as the thread is created. However, in our case, we want to create the threads and have them *wait* for code that we’ll send later. The standard library’s implementation of threads doesn’t include any way to do that; we have to implement it manually. We’ll implement this behavior by introducing a new data structure between the `ThreadPool` and the threads that will manage this new behavior. We’ll call this data structure *Worker*, which is a common term in pooling implementations. The Worker picks up code that needs to be run and runs the code in the Worker’s thread. Think of people working in the kitchen at a restaurant: the workers wait until orders come in from customers, and then they’re responsible for taking those orders and fulfilling them. Instead of storing a vector of `JoinHandle<()>` instances in the thread pool, we’ll store instances of the `Worker` struct. Each `Worker` will store a single `JoinHandle<()>` instance. Then we’ll implement a method on `Worker` that will take a closure of code to run and send it to the already running thread for execution. We’ll also give each worker an `id` so we can distinguish between the different workers in the pool when logging or debugging. Here is the new process that will happen when we create a `ThreadPool`. We’ll implement the code that sends the closure to the thread after we have `Worker` set up in this way: 1. Define a `Worker` struct that holds an `id` and a `JoinHandle<()>`. 2. Change `ThreadPool` to hold a vector of `Worker` instances. 3. Define a `Worker::new` function that takes an `id` number and returns a `Worker` instance that holds the `id` and a thread spawned with an empty closure. 4. In `ThreadPool::new`, use the `for` loop counter to generate an `id`, create a new `Worker` with that `id`, and store the worker in the vector. If you’re up for a challenge, try implementing these changes on your own before looking at the code in Listing 20-15. Ready? Here is Listing 20-15 with one way to make the preceding modifications. Filename: src/lib.rs ``` use std::thread; pub struct ThreadPool { workers: Vec<Worker>, } impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id)); } ThreadPool { workers } } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize) -> Worker { let thread = thread::spawn(|| {}); Worker { id, thread } } } ``` Listing 20-15: Modifying `ThreadPool` to hold `Worker` instances instead of holding threads directly We’ve changed the name of the field on `ThreadPool` from `threads` to `workers` because it’s now holding `Worker` instances instead of `JoinHandle<()>` instances. We use the counter in the `for` loop as an argument to `Worker::new`, and we store each new `Worker` in the vector named `workers`. External code (like our server in *src/main.rs*) doesn’t need to know the implementation details regarding using a `Worker` struct within `ThreadPool`, so we make the `Worker` struct and its `new` function private. The `Worker::new` function uses the `id` we give it and stores a `JoinHandle<()>` instance that is created by spawning a new thread using an empty closure. > Note: If the operating system can’t create a thread because there aren’t enough system resources, `thread::spawn` will panic. That will cause our whole server to panic, even though the creation of some threads might succeed. For simplicity’s sake, this behavior is fine, but in a production thread pool implementation, you’d likely want to use [`std::thread::Builder`](../std/thread/struct.builder) and its [`spawn`](../std/thread/struct.builder#method.spawn) method that returns `Result` instead. > > This code will compile and will store the number of `Worker` instances we specified as an argument to `ThreadPool::new`. But we’re *still* not processing the closure that we get in `execute`. Let’s look at how to do that next. #### Sending Requests to Threads via Channels The next problem we’ll tackle is that the closures given to `thread::spawn` do absolutely nothing. Currently, we get the closure we want to execute in the `execute` method. But we need to give `thread::spawn` a closure to run when we create each `Worker` during the creation of the `ThreadPool`. We want the `Worker` structs that we just created to fetch the code to run from a queue held in the `ThreadPool` and send that code to its thread to run. The channels we learned about in Chapter 16—a simple way to communicate between two threads—would be perfect for this use case. We’ll use a channel to function as the queue of jobs, and `execute` will send a job from the `ThreadPool` to the `Worker` instances, which will send the job to its thread. Here is the plan: 1. The `ThreadPool` will create a channel and hold on to the sender. 2. Each `Worker` will hold on to the receiver. 3. We’ll create a new `Job` struct that will hold the closures we want to send down the channel. 4. The `execute` method will send the job it wants to execute through the sender. 5. In its thread, the `Worker` will loop over its receiver and execute the closures of any jobs it receives. Let’s start by creating a channel in `ThreadPool::new` and holding the sender in the `ThreadPool` instance, as shown in Listing 20-16. The `Job` struct doesn’t hold anything for now but will be the type of item we’re sending down the channel. Filename: src/lib.rs ``` use std::{sync::mpsc, thread}; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } struct Job; impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id)); } ThreadPool { workers, sender } } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize) -> Worker { let thread = thread::spawn(|| {}); Worker { id, thread } } } ``` Listing 20-16: Modifying `ThreadPool` to store the sender of a channel that transmits `Job` instances In `ThreadPool::new`, we create our new channel and have the pool hold the sender. This will successfully compile. Let’s try passing a receiver of the channel into each worker as the thread pool creates the channel. We know we want to use the receiver in the thread that the workers spawn, so we’ll reference the `receiver` parameter in the closure. The code in Listing 20-17 won’t quite compile yet. Filename: src/lib.rs ``` use std::{sync::mpsc, thread}; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } struct Job; impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, receiver)); } ThreadPool { workers, sender } } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } // --snip-- struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize, receiver: mpsc::Receiver<Job>) -> Worker { let thread = thread::spawn(|| { receiver; }); Worker { id, thread } } } ``` Listing 20-17: Passing the receiver to the workers We’ve made some small and straightforward changes: we pass the receiver into `Worker::new`, and then we use it inside the closure. When we try to check this code, we get this error: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0382]: use of moved value: `receiver` --> src/lib.rs:26:42 | 21 | let (sender, receiver) = mpsc::channel(); | -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver<Job>`, which does not implement the `Copy` trait ... 26 | workers.push(Worker::new(id, receiver)); | ^^^^^^^^ value moved here, in previous iteration of loop For more information about this error, try `rustc --explain E0382`. error: could not compile `hello` due to previous error ``` The code is trying to pass `receiver` to multiple `Worker` instances. This won’t work, as you’ll recall from Chapter 16: the channel implementation that Rust provides is multiple *producer*, single *consumer*. This means we can’t just clone the consuming end of the channel to fix this code. We also don’t want to send a message multiple times to multiple consumers; we want one list of messages with multiple workers such that each message gets processed once. Additionally, taking a job off the channel queue involves mutating the `receiver`, so the threads need a safe way to share and modify `receiver`; otherwise, we might get race conditions (as covered in Chapter 16). Recall the thread-safe smart pointers discussed in Chapter 16: to share ownership across multiple threads and allow the threads to mutate the value, we need to use `Arc<Mutex<T>>`. The `Arc` type will let multiple workers own the receiver, and `Mutex` will ensure that only one worker gets a job from the receiver at a time. Listing 20-18 shows the changes we need to make. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; // --snip-- pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } struct Job; impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } // --snip-- pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { } } // --snip-- struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { // --snip-- let thread = thread::spawn(|| { receiver; }); Worker { id, thread } } } ``` Listing 20-18: Sharing the receiver among the workers using `Arc` and `Mutex` In `ThreadPool::new`, we put the receiver in an `Arc` and a `Mutex`. For each new worker, we clone the `Arc` to bump the reference count so the workers can share ownership of the receiver. With these changes, the code compiles! We’re getting there! #### Implementing the `execute` Method Let’s finally implement the `execute` method on `ThreadPool`. We’ll also change `Job` from a struct to a type alias for a trait object that holds the type of closure that `execute` receives. As discussed in the [“Creating Type Synonyms with Type Aliases”](ch19-04-advanced-types#creating-type-synonyms-with-type-aliases) section of Chapter 19, type aliases allow us to make long types shorter for ease of use. Look at Listing 20-19. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } // --snip-- type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { // --snip-- /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } // --snip-- struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(|| { receiver; }); Worker { id, thread } } } ``` Listing 20-19: Creating a `Job` type alias for a `Box` that holds each closure and then sending the job down the channel After creating a new `Job` instance using the closure we get in `execute`, we send that job down the sending end of the channel. We’re calling `unwrap` on `send` for the case that sending fails. This might happen if, for example, we stop all our threads from executing, meaning the receiving end has stopped receiving new messages. At the moment, we can’t stop our threads from executing: our threads continue executing as long as the pool exists. The reason we use `unwrap` is that we know the failure case won’t happen, but the compiler doesn’t know that. But we’re not quite done yet! In the worker, our closure being passed to `thread::spawn` still only *references* the receiving end of the channel. Instead, we need the closure to loop forever, asking the receiving end of the channel for a job and running the job when it gets one. Let’s make the change shown in Listing 20-20 to `Worker::new`. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } // --snip-- impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread } } } ``` Listing 20-20: Receiving and executing the jobs in the worker’s thread Here, we first call `lock` on the `receiver` to acquire the mutex, and then we call `unwrap` to panic on any errors. Acquiring a lock might fail if the mutex is in a *poisoned* state, which can happen if some other thread panicked while holding the lock rather than releasing the lock. In this situation, calling `unwrap` to have this thread panic is the correct action to take. Feel free to change this `unwrap` to an `expect` with an error message that is meaningful to you. If we get the lock on the mutex, we call `recv` to receive a `Job` from the channel. A final `unwrap` moves past any errors here as well, which might occur if the thread holding the sender has shut down, similar to how the `send` method returns `Err` if the receiver shuts down. The call to `recv` blocks, so if there is no job yet, the current thread will wait until a job becomes available. The `Mutex<T>` ensures that only one `Worker` thread at a time is trying to request a job. Our thread pool is now in a working state! Give it a `cargo run` and make some requests: ``` $ cargo run Compiling hello v0.1.0 (file:///projects/hello) warning: field is never read: `workers` --> src/lib.rs:7:5 | 7 | workers: Vec<Worker>, | ^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(dead_code)]` on by default warning: field is never read: `id` --> src/lib.rs:48:5 | 48 | id: usize, | ^^^^^^^^^ warning: field is never read: `thread` --> src/lib.rs:49:5 | 49 | thread: thread::JoinHandle<()>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: `hello` (lib) generated 3 warnings Finished dev [unoptimized + debuginfo] target(s) in 1.40s Running `target/debug/hello` Worker 0 got a job; executing. Worker 2 got a job; executing. Worker 1 got a job; executing. Worker 3 got a job; executing. Worker 0 got a job; executing. Worker 2 got a job; executing. Worker 1 got a job; executing. Worker 3 got a job; executing. Worker 0 got a job; executing. Worker 2 got a job; executing. ``` Success! We now have a thread pool that executes connections asynchronously. There are never more than four threads created, so our system won’t get overloaded if the server receives a lot of requests. If we make a request to */sleep*, the server will be able to serve other requests by having another thread run them. > Note: if you open */sleep* in multiple browser windows simultaneously, they might load one at a time in 5 second intervals. Some web browsers execute multiple instances of the same request sequentially for caching reasons. This limitation is not caused by our web server. > > After learning about the `while let` loop in Chapter 18, you might be wondering why we didn’t write the worker thread code as shown in Listing 20-21. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } // --snip-- impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || { while let Ok(job) = receiver.lock().unwrap().recv() { println!("Worker {id} got a job; executing."); job(); } }); Worker { id, thread } } } ``` Listing 20-21: An alternative implementation of `Worker::new` using `while let` This code compiles and runs but doesn’t result in the desired threading behavior: a slow request will still cause other requests to wait to be processed. The reason is somewhat subtle: the `Mutex` struct has no public `unlock` method because the ownership of the lock is based on the lifetime of the `MutexGuard<T>` within the `LockResult<MutexGuard<T>>` that the `lock` method returns. At compile time, the borrow checker can then enforce the rule that a resource guarded by a `Mutex` cannot be accessed unless we hold the lock. However, this implementation can also result in the lock being held longer than intended if we aren’t mindful of the lifetime of the `MutexGuard<T>`. The code in Listing 20-20 that uses `let job = receiver.lock().unwrap().recv().unwrap();` works because with `let`, any temporary values used in the expression on the right hand side of the equals sign are immediately dropped when the `let` statement ends. However, `while let` (and `if let` and `match`) does not drop temporary values until the end of the associated block. In Listing 20-21, the lock remains held for the duration of the call to `job()`, meaning other workers cannot receive jobs.
programming_docs
rust Managing Growing Projects with Packages, Crates, and Modules Managing Growing Projects with Packages, Crates, and Modules ============================================================ As you write large programs, organizing your code will become increasingly important. By grouping related functionality and separating code with distinct features, you’ll clarify where to find code that implements a particular feature and where to go to change how a feature works. The programs we’ve written so far have been in one module in one file. As a project grows, you should organize code by splitting it into multiple modules and then multiple files. A package can contain multiple binary crates and optionally one library crate. As a package grows, you can extract parts into separate crates that become external dependencies. This chapter covers all these techniques. For very large projects comprising a set of interrelated packages that evolve together, Cargo provides *workspaces*, which we’ll cover in the [“Cargo Workspaces”](ch14-03-cargo-workspaces) section in Chapter 14. We’ll also discuss encapsulating implementation details, which lets you reuse code at a higher level: once you’ve implemented an operation, other code can call your code via its public interface without having to know how the implementation works. The way you write code defines which parts are public for other code to use and which parts are private implementation details that you reserve the right to change. This is another way to limit the amount of detail you have to keep in your head. A related concept is scope: the nested context in which code is written has a set of names that are defined as “in scope.” When reading, writing, and compiling code, programmers and compilers need to know whether a particular name at a particular spot refers to a variable, function, struct, enum, module, constant, or other item and what that item means. You can create scopes and change which names are in or out of scope. You can’t have two items with the same name in the same scope; tools are available to resolve name conflicts. Rust has a number of features that allow you to manage your code’s organization, including which details are exposed, which details are private, and what names are in each scope in your programs. These features, sometimes collectively referred to as the *module system*, include: * **Packages:** A Cargo feature that lets you build, test, and share crates * **Crates:** A tree of modules that produces a library or executable * **Modules** and **use:** Let you control the organization, scope, and privacy of paths * **Paths:** A way of naming an item, such as a struct, function, or module In this chapter, we’ll cover all these features, discuss how they interact, and explain how to use them to manage scope. By the end, you should have a solid understanding of the module system and be able to work with scopes like a pro! rust Defining an Enum Defining an Enum ================ Where structs give you a way of grouping together related fields and data, like a `Rectangle` with its `width` and `height`, enums give you a way of saying a value is one of a possible set of values. For example, we may want to say that `Rectangle` is one of a set of possible shapes that also includes `Circle` and `Triangle`. To do this, Rust allows us to encode these possibilities as an enum. Let’s look at a situation we might want to express in code and see why enums are useful and more appropriate than structs in this case. Say we need to work with IP addresses. Currently, two major standards are used for IP addresses: version four and version six. Because these are the only possibilities for an IP address that our program will come across, we can *enumerate* all possible variants, which is where enumeration gets its name. Any IP address can be either a version four or a version six address, but not both at the same time. That property of IP addresses makes the enum data structure appropriate, because an enum value can only be one of its variants. Both version four and version six addresses are still fundamentally IP addresses, so they should be treated as the same type when the code is handling situations that apply to any kind of IP address. We can express this concept in code by defining an `IpAddrKind` enumeration and listing the possible kinds an IP address can be, `V4` and `V6`. These are the variants of the enum: ``` enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {} ``` `IpAddrKind` is now a custom data type that we can use elsewhere in our code. ### Enum Values We can create instances of each of the two variants of `IpAddrKind` like this: ``` enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {} ``` Note that the variants of the enum are namespaced under its identifier, and we use a double colon to separate the two. This is useful because now both values `IpAddrKind::V4` and `IpAddrKind::V6` are of the same type: `IpAddrKind`. We can then, for instance, define a function that takes any `IpAddrKind`: ``` enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {} ``` And we can call this function with either variant: ``` enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {} ``` Using enums has even more advantages. Thinking more about our IP address type, at the moment we don’t have a way to store the actual IP address *data*; we only know what *kind* it is. Given that you just learned about structs in Chapter 5, you might be tempted to tackle this problem with structs as shown in Listing 6-1. ``` fn main() { enum IpAddrKind { V4, V6, } struct IpAddr { kind: IpAddrKind, address: String, } let home = IpAddr { kind: IpAddrKind::V4, address: String::from("127.0.0.1"), }; let loopback = IpAddr { kind: IpAddrKind::V6, address: String::from("::1"), }; } ``` Listing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a `struct` Here, we’ve defined a struct `IpAddr` that has two fields: a `kind` field that is of type `IpAddrKind` (the enum we defined previously) and an `address` field of type `String`. We have two instances of this struct. The first is `home`, and it has the value `IpAddrKind::V4` as its `kind` with associated address data of `127.0.0.1`. The second instance is `loopback`. It has the other variant of `IpAddrKind` as its `kind` value, `V6`, and has address `::1` associated with it. We’ve used a struct to bundle the `kind` and `address` values together, so now the variant is associated with the value. However, representing the same concept using just an enum is more concise: rather than an enum inside a struct, we can put data directly into each enum variant. This new definition of the `IpAddr` enum says that both `V4` and `V6` variants will have associated `String` values: ``` fn main() { enum IpAddr { V4(String), V6(String), } let home = IpAddr::V4(String::from("127.0.0.1")); let loopback = IpAddr::V6(String::from("::1")); } ``` We attach data to each variant of the enum directly, so there is no need for an extra struct. Here it’s also easier to see another detail of how enums work: the name of each enum variant that we define also becomes a function that constructs an instance of the enum. That is, `IpAddr::V4()` is a function call that takes a `String` argument and returns an instance of the `IpAddr` type. We automatically get this constructor function defined as a result of defining the enum. There’s another advantage to using an enum rather than a struct: each variant can have different types and amounts of associated data. Version four type IP addresses will always have four numeric components that will have values between 0 and 255. If we wanted to store `V4` addresses as four `u8` values but still express `V6` addresses as one `String` value, we wouldn’t be able to with a struct. Enums handle this case with ease: ``` fn main() { enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); } ``` We’ve shown several different ways to define data structures to store version four and version six IP addresses. However, as it turns out, wanting to store IP addresses and encode which kind they are is so common that [the standard library has a definition we can use!](../std/net/enum.ipaddr) Let’s look at how the standard library defines `IpAddr`: it has the exact enum and variants that we’ve defined and used, but it embeds the address data inside the variants in the form of two different structs, which are defined differently for each variant: ``` #![allow(unused)] fn main() { struct Ipv4Addr { // --snip-- } struct Ipv6Addr { // --snip-- } enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr), } } ``` This code illustrates that you can put any kind of data inside an enum variant: strings, numeric types, or structs, for example. You can even include another enum! Also, standard library types are often not much more complicated than what you might come up with. Note that even though the standard library contains a definition for `IpAddr`, we can still create and use our own definition without conflict because we haven’t brought the standard library’s definition into our scope. We’ll talk more about bringing types into scope in Chapter 7. Let’s look at another example of an enum in Listing 6-2: this one has a wide variety of types embedded in its variants. ``` enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() {} ``` Listing 6-2: A `Message` enum whose variants each store different amounts and types of values This enum has four variants with different types: * `Quit` has no data associated with it at all. * `Move` has named fields like a struct does. * `Write` includes a single `String`. * `ChangeColor` includes three `i32` values. Defining an enum with variants such as the ones in Listing 6-2 is similar to defining different kinds of struct definitions, except the enum doesn’t use the `struct` keyword and all the variants are grouped together under the `Message` type. The following structs could hold the same data that the preceding enum variants hold: ``` struct QuitMessage; // unit struct struct MoveMessage { x: i32, y: i32, } struct WriteMessage(String); // tuple struct struct ChangeColorMessage(i32, i32, i32); // tuple struct fn main() {} ``` But if we used the different structs, which each have their own type, we couldn’t as easily define a function to take any of these kinds of messages as we could with the `Message` enum defined in Listing 6-2, which is a single type. There is one more similarity between enums and structs: just as we’re able to define methods on structs using `impl`, we’re also able to define methods on enums. Here’s a method named `call` that we could define on our `Message` enum: ``` fn main() { enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } impl Message { fn call(&self) { // method body would be defined here } } let m = Message::Write(String::from("hello")); m.call(); } ``` The body of the method would use `self` to get the value that we called the method on. In this example, we’ve created a variable `m` that has the value `Message::Write(String::from("hello"))`, and that is what `self` will be in the body of the `call` method when `m.call()` runs. Let’s look at another enum in the standard library that is very common and useful: `Option`. ### The `Option` Enum and Its Advantages Over Null Values This section explores a case study of `Option`, which is another enum defined by the standard library. The `Option` type encodes the very common scenario in which a value could be something or it could be nothing. For example, if you request the first of a list containing items, you would get a value. If you request the first item of an empty list, you would get nothing. Expressing this concept in terms of the type system means the compiler can check whether you’ve handled all the cases you should be handling; this functionality can prevent bugs that are extremely common in other programming languages. Programming language design is often thought of in terms of which features you include, but the features you exclude are important too. Rust doesn’t have the null feature that many other languages have. *Null* is a value that means there is no value there. In languages with null, variables can always be in one of two states: null or not-null. In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony Hoare, the inventor of null, has this to say: > I call it my billion-dollar mistake. At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. > > The problem with null values is that if you try to use a null value as a not-null value, you’ll get an error of some kind. Because this null or not-null property is pervasive, it’s extremely easy to make this kind of error. However, the concept that null is trying to express is still a useful one: a null is a value that is currently invalid or absent for some reason. The problem isn’t really with the concept but with the particular implementation. As such, Rust does not have nulls, but it does have an enum that can encode the concept of a value being present or absent. This enum is `Option<T>`, and it is [defined by the standard library](../std/option/enum.option) as follows: ``` #![allow(unused)] fn main() { enum Option<T> { None, Some(T), } } ``` The `Option<T>` enum is so useful that it’s even included in the prelude; you don’t need to bring it into scope explicitly. Its variants are also included in the prelude: you can use `Some` and `None` directly without the `Option::` prefix. The `Option<T>` enum is still just a regular enum, and `Some(T)` and `None` are still variants of type `Option<T>`. The `<T>` syntax is a feature of Rust we haven’t talked about yet. It’s a generic type parameter, and we’ll cover generics in more detail in Chapter 10. For now, all you need to know is that `<T>` means the `Some` variant of the `Option` enum can hold one piece of data of any type, and that each concrete type that gets used in place of `T` makes the overall `Option<T>` type a different type. Here are some examples of using `Option` values to hold number types and string types: ``` fn main() { let some_number = Some(5); let some_char = Some('e'); let absent_number: Option<i32> = None; } ``` The type of `some_number` is `Option<i32>`. The type of `some_char` is `Option<char>`, which is a different type. Rust can infer these types because we’ve specified a value inside the `Some` variant. For `absent_number`, Rust requires us to annotate the overall `Option` type: the compiler can’t infer the type that the corresponding `Some` variant will hold by looking only at a `None` value. Here, we tell Rust that we mean for `absent_number` to be of type `Option<i32>`. When we have a `Some` value, we know that a value is present and the value is held within the `Some`. When we have a `None` value, in some sense, it means the same thing as null: we don’t have a valid value. So why is having `Option<T>` any better than having null? In short, because `Option<T>` and `T` (where `T` can be any type) are different types, the compiler won’t let us use an `Option<T>` value as if it were definitely a valid value. For example, this code won’t compile because it’s trying to add an `i8` to an `Option<i8>`: ``` fn main() { let x: i8 = 5; let y: Option<i8> = Some(5); let sum = x + y; } ``` If we run this code, we get an error message like this: ``` $ cargo run Compiling enums v0.1.0 (file:///projects/enums) error[E0277]: cannot add `Option<i8>` to `i8` --> src/main.rs:5:17 | 5 | let sum = x + y; | ^ no implementation for `i8 + Option<i8>` | = help: the trait `Add<Option<i8>>` is not implemented for `i8` = help: the following other types implement trait `Add<Rhs>`: <&'a f32 as Add<f32>> <&'a f64 as Add<f64>> <&'a i128 as Add<i128>> <&'a i16 as Add<i16>> <&'a i32 as Add<i32>> <&'a i64 as Add<i64>> <&'a i8 as Add<i8>> <&'a isize as Add<isize>> and 48 others For more information about this error, try `rustc --explain E0277`. error: could not compile `enums` due to previous error ``` Intense! In effect, this error message means that Rust doesn’t understand how to add an `i8` and an `Option<i8>`, because they’re different types. When we have a value of a type like `i8` in Rust, the compiler will ensure that we always have a valid value. We can proceed confidently without having to check for null before using that value. Only when we have an `Option<i8>` (or whatever type of value we’re working with) do we have to worry about possibly not having a value, and the compiler will make sure we handle that case before using the value. In other words, you have to convert an `Option<T>` to a `T` before you can perform `T` operations with it. Generally, this helps catch one of the most common issues with null: assuming that something isn’t null when it actually is. Eliminating the risk of incorrectly assuming a not-null value helps you to be more confident in your code. In order to have a value that can possibly be null, you must explicitly opt in by making the type of that value `Option<T>`. Then, when you use that value, you are required to explicitly handle the case when the value is null. Everywhere that a value has a type that isn’t an `Option<T>`, you *can* safely assume that the value isn’t null. This was a deliberate design decision for Rust to limit null’s pervasiveness and increase the safety of Rust code. So, how do you get the `T` value out of a `Some` variant when you have a value of type `Option<T>` so you can use that value? The `Option<T>` enum has a large number of methods that are useful in a variety of situations; you can check them out in [its documentation](../std/option/enum.option). Becoming familiar with the methods on `Option<T>` will be extremely useful in your journey with Rust. In general, in order to use an `Option<T>` value, you want to have code that will handle each variant. You want some code that will run only when you have a `Some(T)` value, and this code is allowed to use the inner `T`. You want some other code to run if you have a `None` value, and that code doesn’t have a `T` value available. The `match` expression is a control flow construct that does just this when used with enums: it will run different code depending on which variant of the enum it has, and that code can use the data inside the matching value.
programming_docs
rust Error Handling Error Handling ============== Errors are a fact of life in software, so Rust has a number of features for handling situations in which something goes wrong. In many cases, Rust requires you to acknowledge the possibility of an error and take some action before your code will compile. This requirement makes your program more robust by ensuring that you’ll discover errors and handle them appropriately before you’ve deployed your code to production! Rust groups errors into two major categories: *recoverable* and *unrecoverable* errors. For a recoverable error, such as a *file not found* error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, like trying to access a location beyond the end of an array, and so we want to immediately stop the program. Most languages don’t distinguish between these two kinds of errors and handle both in the same way, using mechanisms such as exceptions. Rust doesn’t have exceptions. Instead, it has the type `Result<T, E>` for recoverable errors and the `panic!` macro that stops execution when the program encounters an unrecoverable error. This chapter covers calling `panic!` first and then talks about returning `Result<T, E>` values. Additionally, we’ll explore considerations when deciding whether to try to recover from an error or to stop execution. rust Generic Data Types Generic Data Types ================== We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let’s first look at how to define functions, structs, enums, and methods using generics. Then we’ll discuss how generics affect code performance. ### In Function Definitions When defining a function that uses generics, we place the generics in the signature of the function where we would usually specify the data types of the parameters and return value. Doing so makes our code more flexible and provides more functionality to callers of our function while preventing code duplication. Continuing with our `largest` function, Listing 10-4 shows two functions that both find the largest value in a slice. We'll then combine these into a single function that uses generics. Filename: src/main.rs ``` fn largest_i32(list: &[i32]) -> &i32 { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn largest_char(list: &[char]) -> &char { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest_i32(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 100); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest_char(&char_list); println!("The largest char is {}", result); assert_eq!(*result, 'y'); } ``` Listing 10-4: Two functions that differ only in their names and the types in their signatures The `largest_i32` function is the one we extracted in Listing 10-3 that finds the largest `i32` in a slice. The `largest_char` function finds the largest `char` in a slice. The function bodies have the same code, so let’s eliminate the duplication by introducing a generic type parameter in a single function. To parameterize the types in a new single function, we need to name the type parameter, just as we do for the value parameters to a function. You can use any identifier as a type parameter name. But we’ll use `T` because, by convention, type parameter names in Rust are short, often just a letter, and Rust’s type-naming convention is CamelCase. Short for “type,” `T` is the default choice of most Rust programmers. When we use a parameter in the body of the function, we have to declare the parameter name in the signature so the compiler knows what that name means. Similarly, when we use a type parameter name in a function signature, we have to declare the type parameter name before we use it. To define the generic `largest` function, place type name declarations inside angle brackets, `<>`, between the name of the function and the parameter list, like this: ``` fn largest<T>(list: &[T]) -> &T { ``` We read this definition as: the function `largest` is generic over some type `T`. This function has one parameter named `list`, which is a slice of values of type `T`. The `largest` function will return a reference to a value of the same type `T`. Listing 10-5 shows the combined `largest` function definition using the generic data type in its signature. The listing also shows how we can call the function with either a slice of `i32` values or `char` values. Note that this code won’t compile yet, but we’ll fix it later in this chapter. Filename: src/main.rs ``` fn largest<T>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest(&number_list); println!("The largest number is {}", result); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest(&char_list); println!("The largest char is {}", result); } ``` Listing 10-5: The `largest` function using generic type parameters; this doesn’t yet compile If we compile this code right now, we’ll get this error: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0369]: binary operation `>` cannot be applied to type `&T` --> src/main.rs:5:17 | 5 | if item > largest { | ---- ^ ------- &T | | | &T | help: consider restricting type parameter `T` | 1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T { | ++++++++++++++++++++++ For more information about this error, try `rustc --explain E0369`. error: could not compile `chapter10` due to previous error ``` The help text mentions `std::cmp::PartialOrd`, which is a *trait*, and we’re going to talk about traits in the next section. For now, know that this error states that the body of `largest` won’t work for all possible types that `T` could be. Because we want to compare values of type `T` in the body, we can only use types whose values can be ordered. To enable comparisons, the standard library has the `std::cmp::PartialOrd` trait that you can implement on types (see Appendix C for more on this trait). By following the help text's suggestion, we restrict the types valid for `T` to only those that implement `PartialOrd` and this example will compile, because the standard library implements `PartialOrd` on both `i32` and `char`. ### In Struct Definitions We can also define structs to use a generic type parameter in one or more fields using the `<>` syntax. Listing 10-6 defines a `Point<T>` struct to hold `x` and `y` coordinate values of any type. Filename: src/main.rs ``` struct Point<T> { x: T, y: T, } fn main() { let integer = Point { x: 5, y: 10 }; let float = Point { x: 1.0, y: 4.0 }; } ``` Listing 10-6: A `Point<T>` struct that holds `x` and `y` values of type `T` The syntax for using generics in struct definitions is similar to that used in function definitions. First, we declare the name of the type parameter inside angle brackets just after the name of the struct. Then we use the generic type in the struct definition where we would otherwise specify concrete data types. Note that because we’ve used only one generic type to define `Point<T>`, this definition says that the `Point<T>` struct is generic over some type `T`, and the fields `x` and `y` are *both* that same type, whatever that type may be. If we create an instance of a `Point<T>` that has values of different types, as in Listing 10-7, our code won’t compile. Filename: src/main.rs ``` struct Point<T> { x: T, y: T, } fn main() { let wont_work = Point { x: 5, y: 4.0 }; } ``` Listing 10-7: The fields `x` and `y` must be the same type because both have the same generic data type `T`. In this example, when we assign the integer value 5 to `x`, we let the compiler know that the generic type `T` will be an integer for this instance of `Point<T>`. Then when we specify 4.0 for `y`, which we’ve defined to have the same type as `x`, we’ll get a type mismatch error like this: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0308]: mismatched types --> src/main.rs:7:38 | 7 | let wont_work = Point { x: 5, y: 4.0 }; | ^^^ expected integer, found floating-point number For more information about this error, try `rustc --explain E0308`. error: could not compile `chapter10` due to previous error ``` To define a `Point` struct where `x` and `y` are both generics but could have different types, we can use multiple generic type parameters. For example, in Listing 10-8, we change the definition of `Point` to be generic over types `T` and `U` where `x` is of type `T` and `y` is of type `U`. Filename: src/main.rs ``` struct Point<T, U> { x: T, y: U, } fn main() { let both_integer = Point { x: 5, y: 10 }; let both_float = Point { x: 1.0, y: 4.0 }; let integer_and_float = Point { x: 5, y: 4.0 }; } ``` Listing 10-8: A `Point<T, U>` generic over two types so that `x` and `y` can be values of different types Now all the instances of `Point` shown are allowed! You can use as many generic type parameters in a definition as you want, but using more than a few makes your code hard to read. If you're finding you need lots of generic types in your code, it could indicate that your code needs restructuring into smaller pieces. ### In Enum Definitions As we did with structs, we can define enums to hold generic data types in their variants. Let’s take another look at the `Option<T>` enum that the standard library provides, which we used in Chapter 6: ``` #![allow(unused)] fn main() { enum Option<T> { Some(T), None, } } ``` This definition should now make more sense to you. As you can see, the `Option<T>` enum is generic over type `T` and has two variants: `Some`, which holds one value of type `T`, and a `None` variant that doesn’t hold any value. By using the `Option<T>` enum, we can express the abstract concept of an optional value, and because `Option<T>` is generic, we can use this abstraction no matter what the type of the optional value is. Enums can use multiple generic types as well. The definition of the `Result` enum that we used in Chapter 9 is one example: ``` #![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } } ``` The `Result` enum is generic over two types, `T` and `E`, and has two variants: `Ok`, which holds a value of type `T`, and `Err`, which holds a value of type `E`. This definition makes it convenient to use the `Result` enum anywhere we have an operation that might succeed (return a value of some type `T`) or fail (return an error of some type `E`). In fact, this is what we used to open a file in Listing 9-3, where `T` was filled in with the type `std::fs::File` when the file was opened successfully and `E` was filled in with the type `std::io::Error` when there were problems opening the file. When you recognize situations in your code with multiple struct or enum definitions that differ only in the types of the values they hold, you can avoid duplication by using generic types instead. ### In Method Definitions We can implement methods on structs and enums (as we did in Chapter 5) and use generic types in their definitions, too. Listing 10-9 shows the `Point<T>` struct we defined in Listing 10-6 with a method named `x` implemented on it. Filename: src/main.rs ``` struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } } fn main() { let p = Point { x: 5, y: 10 }; println!("p.x = {}", p.x()); } ``` Listing 10-9: Implementing a method named `x` on the `Point<T>` struct that will return a reference to the `x` field of type `T` Here, we’ve defined a method named `x` on `Point<T>` that returns a reference to the data in the field `x`. Note that we have to declare `T` just after `impl` so we can use `T` to specify that we’re implementing methods on the type `Point<T>`. By declaring `T` as a generic type after `impl`, Rust can identify that the type in the angle brackets in `Point` is a generic type rather than a concrete type. We could have chosen a different name for this generic parameter than the generic parameter declared in the struct definition, but using the same name is conventional. Methods written within an `impl` that declares the generic type will be defined on any instance of the type, no matter what concrete type ends up substituting for the generic type. We can also specify constraints on generic types when defining methods on the type. We could, for example, implement methods only on `Point<f32>` instances rather than on `Point<T>` instances with any generic type. In Listing 10-10 we use the concrete type `f32`, meaning we don’t declare any types after `impl`. Filename: src/main.rs ``` struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } } impl Point<f32> { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } fn main() { let p = Point { x: 5, y: 10 }; println!("p.x = {}", p.x()); } ``` Listing 10-10: An `impl` block that only applies to a struct with a particular concrete type for the generic type parameter `T` This code means the type `Point<f32>` will have a `distance_from_origin` method; other instances of `Point<T>` where `T` is not of type `f32` will not have this method defined. The method measures how far our point is from the point at coordinates (0.0, 0.0) and uses mathematical operations that are available only for floating point types. Generic type parameters in a struct definition aren’t always the same as those you use in that same struct’s method signatures. Listing 10-11 uses the generic types `X1` and `Y1` for the `Point` struct and `X2` `Y2` for the `mixup` method signature to make the example clearer. The method creates a new `Point` instance with the `x` value from the `self` `Point` (of type `X1`) and the `y` value from the passed-in `Point` (of type `Y2`). Filename: src/main.rs ``` struct Point<X1, Y1> { x: X1, y: Y1, } impl<X1, Y1> Point<X1, Y1> { fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> { Point { x: self.x, y: other.y, } } } fn main() { let p1 = Point { x: 5, y: 10.4 }; let p2 = Point { x: "Hello", y: 'c' }; let p3 = p1.mixup(p2); println!("p3.x = {}, p3.y = {}", p3.x, p3.y); } ``` Listing 10-11: A method that uses generic types different from its struct’s definition In `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`) and an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct that has a string slice for `x` (with value `"Hello"`) and a `char` for `y` (with value `c`). Calling `mixup` on `p1` with the argument `p2` gives us `p3`, which will have an `i32` for `x`, because `x` came from `p1`. The `p3` variable will have a `char` for `y`, because `y` came from `p2`. The `println!` macro call will print `p3.x = 5, p3.y = c`. The purpose of this example is to demonstrate a situation in which some generic parameters are declared with `impl` and some are declared with the method definition. Here, the generic parameters `X1` and `Y1` are declared after `impl` because they go with the struct definition. The generic parameters `X2` and `Y2` are declared after `fn mixup`, because they’re only relevant to the method. ### Performance of Code Using Generics You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types. Rust accomplishes this by performing monomorphization of the code using generics at compile time. *Monomorphization* is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. In this process, the compiler does the opposite of the steps we used to create the generic function in Listing 10-5: the compiler looks at all the places where generic code is called and generates code for the concrete types the generic code is called with. Let’s look at how this works by using the standard library’s generic `Option<T>` enum: ``` #![allow(unused)] fn main() { let integer = Some(5); let float = Some(5.0); } ``` When Rust compiles this code, it performs monomorphization. During that process, the compiler reads the values that have been used in `Option<T>` instances and identifies two kinds of `Option<T>`: one is `i32` and the other is `f64`. As such, it expands the generic definition of `Option<T>` into two definitions specialized to `i32` and `f64`, thereby replacing the generic definition with the specific ones. The monomorphized version of the code looks similar to the following (the compiler uses different names than what we’re using here for illustration): Filename: src/main.rs ``` enum Option_i32 { Some(i32), None, } enum Option_f64 { Some(f64), None, } fn main() { let integer = Option_i32::Some(5); let float = Option_f64::Some(5.0); } ``` The generic `Option<T>` is replaced with the specific definitions created by the compiler. Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics. When the code runs, it performs just as it would if we had duplicated each definition by hand. The process of monomorphization makes Rust’s generics extremely efficient at runtime. rust Packages and Crates Packages and Crates =================== The first parts of the module system we’ll cover are packages and crates. A *crate* is the smallest amount of code that the Rust compiler considers at a time. Even if you run `rustc` rather than `cargo` and pass a single source code file (as we did all the way back in the “Writing and Running a Rust Program” section of Chapter 1), the compiler considers that file to be a crate. Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. A crate can come in one of two forms: a binary crate or a library crate. *Binary crates* are programs you can compile to an executable that you can run, such as a command-line program or a server. Each must have a function called `main` that defines what happens when the executable runs. All the crates we’ve created so far have been binary crates. *Library crates* don’t have a `main` function, and they don’t compile to an executable. Instead, they define functionality intended to be shared with multiple projects. For example, the `rand` crate we used in [Chapter 2](ch02-00-guessing-game-tutorial#generating-a-random-number) provides functionality that generates random numbers. Most of the time when Rustaceans say “crate”, they mean library crate, and they use “crate” interchangeably with the general programming concept of a “library". The *crate root* is a source file that the Rust compiler starts from and makes up the root module of your crate (we’ll explain modules in depth in the [“Defining Modules to Control Scope and Privacy”](ch07-02-defining-modules-to-control-scope-and-privacy) section). A *package* is a bundle of one or more crates that provides a set of functionality. A package contains a *Cargo.toml* file that describes how to build those crates. Cargo is actually a package that contains the binary crate for the command-line tool you’ve been using to build your code. The Cargo package also contains a library crate that the binary crate depends on. Other projects can depend on the Cargo library crate to use the same logic the Cargo command-line tool uses. A package can contain as many binary crates as you like, but at most only one library crate. A package must contain at least one crate, whether that’s a library or binary crate. Let’s walk through what happens when we create a package. First, we enter the command `cargo new`: ``` $ cargo new my-project Created binary (application) `my-project` package $ ls my-project Cargo.toml src $ ls my-project/src main.rs ``` After we run `cargo new`, we use `ls` to see what Cargo creates. In the project directory, there’s a *Cargo.toml* file, giving us a package. There’s also a *src* directory that contains *main.rs*. Open *Cargo.toml* in your text editor, and note there’s no mention of *src/main.rs*. Cargo follows a convention that *src/main.rs* is the crate root of a binary crate with the same name as the package. Likewise, Cargo knows that if the package directory contains *src/lib.rs*, the package contains a library crate with the same name as the package, and *src/lib.rs* is its crate root. Cargo passes the crate root files to `rustc` to build the library or binary. Here, we have a package that only contains *src/main.rs*, meaning it only contains a binary crate named `my-project`. If a package contains *src/main.rs* and *src/lib.rs*, it has two crates: a binary and a library, both with the same name as the package. A package can have multiple binary crates by placing files in the *src/bin* directory: each file will be a separate binary crate.
programming_docs
rust Hello, Cargo! Hello, Cargo! ============= Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs *dependencies*.) The simplest Rust programs, like the one we’ve written so far, don’t have any dependencies. If we had built the “Hello, world!” project with Cargo, it would only use the part of Cargo that handles building your code. As you write more complex Rust programs, you’ll add dependencies, and if you start a project using Cargo, adding dependencies will be much easier to do. Because the vast majority of Rust projects use Cargo, the rest of this book assumes that you’re using Cargo too. Cargo comes installed with Rust if you used the official installers discussed in the [“Installation”](ch01-01-installation#installation) section. If you installed Rust through some other means, check whether Cargo is installed by entering the following into your terminal: ``` $ cargo --version ``` If you see a version number, you have it! If you see an error, such as `command not found`, look at the documentation for your method of installation to determine how to install Cargo separately. ### Creating a Project with Cargo Let’s create a new project using Cargo and look at how it differs from our original “Hello, world!” project. Navigate back to your *projects* directory (or wherever you decided to store your code). Then, on any operating system, run the following: ``` $ cargo new hello_cargo $ cd hello_cargo ``` The first command creates a new directory and project called *hello\_cargo*. We’ve named our project *hello\_cargo*, and Cargo creates its files in a directory of the same name. Go into the *hello\_cargo* directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a *Cargo.toml* file and a *src* directory with a *main.rs* file inside. It has also initialized a new Git repository along with a *.gitignore* file. Git files won’t be generated if you run `cargo new` within an existing Git repository; you can override this behavior by using `cargo new --vcs=git`. > Note: Git is a common version control system. You can change `cargo new` to use a different version control system or no version control system by using the `--vcs` flag. Run `cargo new --help` to see the available options. > > Open *Cargo.toml* in your text editor of choice. It should look similar to the code in Listing 1-2. Filename: Cargo.toml ``` [package] name = "hello_cargo" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ``` Listing 1-2: Contents of *Cargo.toml* generated by `cargo new` This file is in the [*TOML*](https://toml.io) (*Tom’s Obvious, Minimal Language*) format, which is Cargo’s configuration format. The first line, `[package]`, is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections. The next three lines set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. We’ll talk about the `edition` key in [Appendix E](appendix-05-editions). The last line, `[dependencies]`, is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as *crates*. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then. Now open *src/main.rs* and take a look: Filename: src/main.rs ``` fn main() { println!("Hello, world!"); } ``` Cargo has generated a “Hello, world!” program for you, just like the one we wrote in Listing 1-1! So far, the differences between our project and the project Cargo generated are that Cargo placed the code in the *src* directory, and we have a *Cargo.toml* configuration file in the top directory. Cargo expects your source files to live inside the *src* directory. The top-level project directory is just for README files, license information, configuration files, and anything else not related to your code. Using Cargo helps you organize your projects. There’s a place for everything, and everything is in its place. If you started a project that doesn’t use Cargo, as we did with the “Hello, world!” project, you can convert it to a project that does use Cargo. Move the project code into the *src* directory and create an appropriate *Cargo.toml* file. ### Building and Running a Cargo Project Now let’s look at what’s different when we build and run the “Hello, world!” program with Cargo! From your *hello\_cargo* directory, build your project by entering the following command: ``` $ cargo build Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs ``` This command creates an executable file in *target/debug/hello\_cargo* (or *target\debug\hello\_cargo.exe* on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named *debug*. You can run the executable with this command: ``` $ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows Hello, world! ``` If all goes well, `Hello, world!` should print to the terminal. Running `cargo build` for the first time also causes Cargo to create a new file at the top level: *Cargo.lock*. This file keeps track of the exact versions of dependencies in your project. This project doesn’t have dependencies, so the file is a bit sparse. You won’t ever need to change this file manually; Cargo manages its contents for you. We just built a project with `cargo build` and ran it with `./target/debug/hello_cargo`, but we can also use `cargo run` to compile the code and then run the resulting executable all in one command: ``` $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/hello_cargo` Hello, world! ``` Using `cargo run` is more convenient than having to remember to run `cargo build` and then use the whole path to the binary, so most developers use `cargo run`. Notice that this time we didn’t see output indicating that Cargo was compiling `hello_cargo`. Cargo figured out that the files hadn’t changed, so it didn’t rebuild but just ran the binary. If you had modified your source code, Cargo would have rebuilt the project before running it, and you would have seen this output: ``` $ cargo run Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs Running `target/debug/hello_cargo` Hello, world! ``` Cargo also provides a command called `cargo check`. This command quickly checks your code to make sure it compiles but doesn’t produce an executable: ``` $ cargo check Checking hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs ``` Why would you not want an executable? Often, `cargo check` is much faster than `cargo build`, because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using `cargo check` will speed up the process of letting you know if your project is still compiling! As such, many Rustaceans run `cargo check` periodically as they write their program to make sure it compiles. Then they run `cargo build` when they’re ready to use the executable. Let’s recap what we’ve learned so far about Cargo: * We can create a project using `cargo new`. * We can build a project using `cargo build`. * We can build and run a project in one step using `cargo run`. * We can build a project without producing a binary to check for errors using `cargo check`. * Instead of saving the result of the build in the same directory as our code, Cargo stores it in the *target/debug* directory. An additional advantage of using Cargo is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows. ### Building for Release When your project is finally ready for release, you can use `cargo build --release` to compile it with optimizations. This command will create an executable in *target/release* instead of *target/debug*. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run `cargo build --release` and benchmark with the executable in *target/release*. ### Cargo as Convention With simple projects, Cargo doesn’t provide a lot of value over just using `rustc`, but it will prove its worth as your programs become more intricate. Once programs grow to multiple files or need a dependency, it’s much easier to let Cargo coordinate the build. Even though the `hello_cargo` project is simple, it now uses much of the real tooling you’ll use in the rest of your Rust career. In fact, to work on any existing projects, you can use the following commands to check out the code using Git, change to that project’s directory, and build: ``` $ git clone example.org/someproject $ cd someproject $ cargo build ``` For more information about Cargo, check out [its documentation](https://doc.rust-lang.org/cargo/index.html). Summary ------- You’re already off to a great start on your Rust journey! In this chapter, you’ve learned how to: * Install the latest stable version of Rust using `rustup` * Update to a newer Rust version * Open locally installed documentation * Write and run a “Hello, world!” program using `rustc` directly * Create and run a new project using the conventions of Cargo This is a great time to build a more substantial program to get used to reading and writing Rust code. So, in Chapter 2, we’ll build a guessing game program. If you would rather start by learning how common programming concepts work in Rust, see Chapter 3 and then return to Chapter 2. rust Foreword Foreword ======== It wasn’t always so clear, but the Rust programming language is fundamentally about *empowerment*: no matter what kind of code you are writing now, Rust empowers you to reach farther, to program with confidence in a wider variety of domains than you did before. Take, for example, “systems-level” work that deals with low-level details of memory management, data representation, and concurrency. Traditionally, this realm of programming is seen as arcane, accessible only to a select few who have devoted the necessary years learning to avoid its infamous pitfalls. And even those who practice it do so with caution, lest their code be open to exploits, crashes, or corruption. Rust breaks down these barriers by eliminating the old pitfalls and providing a friendly, polished set of tools to help you along the way. Programmers who need to “dip down” into lower-level control can do so with Rust, without taking on the customary risk of crashes or security holes, and without having to learn the fine points of a fickle toolchain. Better yet, the language is designed to guide you naturally towards reliable code that is efficient in terms of speed and memory usage. Programmers who are already working with low-level code can use Rust to raise their ambitions. For example, introducing parallelism in Rust is a relatively low-risk operation: the compiler will catch the classical mistakes for you. And you can tackle more aggressive optimizations in your code with the confidence that you won’t accidentally introduce crashes or vulnerabilities. But Rust isn’t limited to low-level systems programming. It’s expressive and ergonomic enough to make CLI apps, web servers, and many other kinds of code quite pleasant to write — you’ll find simple examples of both later in the book. Working with Rust allows you to build skills that transfer from one domain to another; you can learn Rust by writing a web app, then apply those same skills to target your Raspberry Pi. This book fully embraces the potential of Rust to empower its users. It’s a friendly and approachable text intended to help you level up not just your knowledge of Rust, but also your reach and confidence as a programmer in general. So dive in, get ready to learn—and welcome to the Rust community! — Nicholas Matsakis and Aaron Turon rust Controlling How Tests Are Run Controlling How Tests Are Run ============================= Just as `cargo run` compiles your code and then runs the resulting binary, `cargo test` compiles your code in test mode and runs the resulting test binary. The default behavior of the binary produced by `cargo test` is to run all the tests in parallel and capture output generated during test runs, preventing the output from being displayed and making it easier to read the output related to the test results. You can, however, specify command line options to change this default behavior. Some command line options go to `cargo test`, and some go to the resulting test binary. To separate these two types of arguments, you list the arguments that go to `cargo test` followed by the separator `--` and then the ones that go to the test binary. Running `cargo test --help` displays the options you can use with `cargo test`, and running `cargo test -- --help` displays the options you can use after the separator. ### Running Tests in Parallel or Consecutively When you run multiple tests, by default they run in parallel using threads, meaning they finish running faster and you get feedback quicker. Because the tests are running at the same time, you must make sure your tests don’t depend on each other or on any shared state, including a shared environment, such as the current working directory or environment variables. For example, say each of your tests runs some code that creates a file on disk named *test-output.txt* and writes some data to that file. Then each test reads the data in that file and asserts that the file contains a particular value, which is different in each test. Because the tests run at the same time, one test might overwrite the file in the time between another test writing and reading the file. The second test will then fail, not because the code is incorrect but because the tests have interfered with each other while running in parallel. One solution is to make sure each test writes to a different file; another solution is to run the tests one at a time. If you don’t want to run the tests in parallel or if you want more fine-grained control over the number of threads used, you can send the `--test-threads` flag and the number of threads you want to use to the test binary. Take a look at the following example: ``` $ cargo test -- --test-threads=1 ``` We set the number of test threads to `1`, telling the program not to use any parallelism. Running the tests using one thread will take longer than running them in parallel, but the tests won’t interfere with each other if they share state. ### Showing Function Output By default, if a test passes, Rust’s test library captures anything printed to standard output. For example, if we call `println!` in a test and the test passes, we won’t see the `println!` output in the terminal; we’ll see only the line that indicates the test passed. If a test fails, we’ll see whatever was printed to standard output with the rest of the failure message. As an example, Listing 11-10 has a silly function that prints the value of its parameter and returns 10, as well as a test that passes and a test that fails. Filename: src/lib.rs ``` fn prints_and_returns_10(a: i32) -> i32 { println!("I got the value {}", a); 10 } #[cfg(test)] mod tests { use super::*; #[test] fn this_test_will_pass() { let value = prints_and_returns_10(4); assert_eq!(10, value); } #[test] fn this_test_will_fail() { let value = prints_and_returns_10(8); assert_eq!(5, value); } } ``` Listing 11-10: Tests for a function that calls `println!` When we run these tests with `cargo test`, we’ll see the following output: ``` $ cargo test Compiling silly-function v0.1.0 (file:///projects/silly-function) Finished test [unoptimized + debuginfo] target(s) in 0.58s Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166) running 2 tests test tests::this_test_will_fail ... FAILED test tests::this_test_will_pass ... ok failures: ---- tests::this_test_will_fail stdout ---- I got the value 8 thread 'main' panicked at 'assertion failed: `(left == right)` left: `5`, right: `10`', src/lib.rs:19:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::this_test_will_fail test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Note that nowhere in this output do we see `I got the value 4`, which is what is printed when the test that passes runs. That output has been captured. The output from the test that failed, `I got the value 8`, appears in the section of the test summary output, which also shows the cause of the test failure. If we want to see printed values for passing tests as well, we can tell Rust to also show the output of successful tests with `--show-output`. ``` $ cargo test -- --show-output ``` When we run the tests in Listing 11-10 again with the `--show-output` flag, we see the following output: ``` $ cargo test -- --show-output Compiling silly-function v0.1.0 (file:///projects/silly-function) Finished test [unoptimized + debuginfo] target(s) in 0.60s Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166) running 2 tests test tests::this_test_will_fail ... FAILED test tests::this_test_will_pass ... ok successes: ---- tests::this_test_will_pass stdout ---- I got the value 4 successes: tests::this_test_will_pass failures: ---- tests::this_test_will_fail stdout ---- I got the value 8 thread 'main' panicked at 'assertion failed: `(left == right)` left: `5`, right: `10`', src/lib.rs:19:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::this_test_will_fail test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` ### Running a Subset of Tests by Name Sometimes, running a full test suite can take a long time. If you’re working on code in a particular area, you might want to run only the tests pertaining to that code. You can choose which tests to run by passing `cargo test` the name or names of the test(s) you want to run as an argument. To demonstrate how to run a subset of tests, we’ll first create three tests for our `add_two` function, as shown in Listing 11-11, and choose which ones to run. Filename: src/lib.rs ``` pub fn add_two(a: i32) -> i32 { a + 2 } #[cfg(test)] mod tests { use super::*; #[test] fn add_two_and_two() { assert_eq!(4, add_two(2)); } #[test] fn add_three_and_two() { assert_eq!(5, add_two(3)); } #[test] fn one_hundred() { assert_eq!(102, add_two(100)); } } ``` Listing 11-11: Three tests with three different names If we run the tests without passing any arguments, as we saw earlier, all the tests will run in parallel: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.62s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 3 tests test tests::add_three_and_two ... ok test tests::add_two_and_two ... ok test tests::one_hundred ... ok test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` #### Running Single Tests We can pass the name of any test function to `cargo test` to run only that test: ``` $ cargo test one_hundred Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.69s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::one_hundred ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s ``` Only the test with the name `one_hundred` ran; the other two tests didn’t match that name. The test output lets us know we had more tests that didn’t run by displaying `2 filtered out` at the end. We can’t specify the names of multiple tests in this way; only the first value given to `cargo test` will be used. But there is a way to run multiple tests. #### Filtering to Run Multiple Tests We can specify part of a test name, and any test whose name matches that value will be run. For example, because two of our tests’ names contain `add`, we can run those two by running `cargo test add`: ``` $ cargo test add Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.61s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 2 tests test tests::add_three_and_two ... ok test tests::add_two_and_two ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s ``` This command ran all tests with `add` in the name and filtered out the test named `one_hundred`. Also note that the module in which a test appears becomes part of the test’s name, so we can run all the tests in a module by filtering on the module’s name. ### Ignoring Some Tests Unless Specifically Requested Sometimes a few specific tests can be very time-consuming to execute, so you might want to exclude them during most runs of `cargo test`. Rather than listing as arguments all tests you do want to run, you can instead annotate the time-consuming tests using the `ignore` attribute to exclude them, as shown here: Filename: src/lib.rs ``` #[test] fn it_works() { assert_eq!(2 + 2, 4); } #[test] #[ignore] fn expensive_test() { // code that takes an hour to run } ``` After `#[test]` we add the `#[ignore]` line to the test we want to exclude. Now when we run our tests, `it_works` runs, but `expensive_test` doesn’t: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.60s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 2 tests test expensive_test ... ignored test it_works ... ok test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` The `expensive_test` function is listed as `ignored`. If we want to run only the ignored tests, we can use `cargo test -- --ignored`: ``` $ cargo test -- --ignored Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.61s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test expensive_test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` By controlling which tests run, you can make sure your `cargo test` results will be fast. When you’re at a point where it makes sense to check the results of the `ignored` tests and you have time to wait for the results, you can run `cargo test -- --ignored` instead. If you want to run all tests whether they’re ignored or not, you can run `cargo test -- --include-ignored`.
programming_docs
rust Introduction Introduction ============ > Note: This edition of the book is the same as [The Rust Programming Language](https://nostarch.com/rust) available in print and ebook format from [No Starch Press](https://nostarch.com/). > > Welcome to *The Rust Programming Language*, an introductory book about Rust. The Rust programming language helps you write faster, more reliable software. High-level ergonomics and low-level control are often at odds in programming language design; Rust challenges that conflict. Through balancing powerful technical capacity and a great developer experience, Rust gives you the option to control low-level details (such as memory usage) without all the hassle traditionally associated with such control. Who Rust Is For --------------- Rust is ideal for many people for a variety of reasons. Let’s look at a few of the most important groups. ### Teams of Developers Rust is proving to be a productive tool for collaborating among large teams of developers with varying levels of systems programming knowledge. Low-level code is prone to a variety of subtle bugs, which in most other languages can be caught only through extensive testing and careful code review by experienced developers. In Rust, the compiler plays a gatekeeper role by refusing to compile code with these elusive bugs, including concurrency bugs. By working alongside the compiler, the team can spend their time focusing on the program’s logic rather than chasing down bugs. Rust also brings contemporary developer tools to the systems programming world: * Cargo, the included dependency manager and build tool, makes adding, compiling, and managing dependencies painless and consistent across the Rust ecosystem. * Rustfmt ensures a consistent coding style across developers. * The Rust Language Server powers Integrated Development Environment (IDE) integration for code completion and inline error messages. By using these and other tools in the Rust ecosystem, developers can be productive while writing systems-level code. ### Students Rust is for students and those who are interested in learning about systems concepts. Using Rust, many people have learned about topics like operating systems development. The community is very welcoming and happy to answer student questions. Through efforts such as this book, the Rust teams want to make systems concepts more accessible to more people, especially those new to programming. ### Companies Hundreds of companies, large and small, use Rust in production for a variety of tasks. Those tasks include command line tools, web services, DevOps tooling, embedded devices, audio and video analysis and transcoding, cryptocurrencies, bioinformatics, search engines, Internet of Things applications, machine learning, and even major parts of the Firefox web browser. ### Open Source Developers Rust is for people who want to build the Rust programming language, community, developer tools, and libraries. We’d love to have you contribute to the Rust language. ### People Who Value Speed and Stability Rust is for people who crave speed and stability in a language. By speed, we mean the speed of the programs that you can create with Rust and the speed at which Rust lets you write them. The Rust compiler’s checks ensure stability through feature additions and refactoring. This is in contrast to the brittle legacy code in languages without these checks, which developers are often afraid to modify. By striving for zero-cost abstractions, higher-level features that compile to lower-level code as fast as code written manually, Rust endeavors to make safe code be fast code as well. The Rust language hopes to support many other users as well; those mentioned here are merely some of the biggest stakeholders. Overall, Rust’s greatest ambition is to eliminate the trade-offs that programmers have accepted for decades by providing safety *and* productivity, speed *and* ergonomics. Give Rust a try and see if its choices work for you. Who This Book Is For -------------------- This book assumes that you’ve written code in another programming language but doesn’t make any assumptions about which one. We’ve tried to make the material broadly accessible to those from a wide variety of programming backgrounds. We don’t spend a lot of time talking about what programming *is* or how to think about it. If you’re entirely new to programming, you would be better served by reading a book that specifically provides an introduction to programming. How to Use This Book -------------------- In general, this book assumes that you’re reading it in sequence from front to back. Later chapters build on concepts in earlier chapters, and earlier chapters might not delve into details on a topic; we typically revisit the topic in a later chapter. You’ll find two kinds of chapters in this book: concept chapters and project chapters. In concept chapters, you’ll learn about an aspect of Rust. In project chapters, we’ll build small programs together, applying what you’ve learned so far. Chapters 2, 12, and 20 are project chapters; the rest are concept chapters. Chapter 1 explains how to install Rust, how to write a “Hello, world!” program, and how to use Cargo, Rust’s package manager and build tool. Chapter 2 is a hands-on introduction to the Rust language. Here we cover concepts at a high level, and later chapters will provide additional detail. If you want to get your hands dirty right away, Chapter 2 is the place for that. At first, you might even want to skip Chapter 3, which covers Rust features similar to those of other programming languages, and head straight to Chapter 4 to learn about Rust’s ownership system. However, if you’re a particularly meticulous learner who prefers to learn every detail before moving on to the next, you might want to skip Chapter 2 and go straight to Chapter 3, returning to Chapter 2 when you’d like to work on a project applying the details you’ve learned. Chapter 5 discusses structs and methods, and Chapter 6 covers enums, `match` expressions, and the `if let` control flow construct. You’ll use structs and enums to make custom types in Rust. In Chapter 7, you’ll learn about Rust’s module system and about privacy rules for organizing your code and its public Application Programming Interface (API). Chapter 8 discusses some common collection data structures that the standard library provides, such as vectors, strings, and hash maps. Chapter 9 explores Rust’s error-handling philosophy and techniques. Chapter 10 digs into generics, traits, and lifetimes, which give you the power to define code that applies to multiple types. Chapter 11 is all about testing, which even with Rust’s safety guarantees is necessary to ensure your program’s logic is correct. In Chapter 12, we’ll build our own implementation of a subset of functionality from the `grep` command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters. Chapter 13 explores closures and iterators: features of Rust that come from functional programming languages. In Chapter 14, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. Chapter 15 discusses smart pointers that the standard library provides and the traits that enable their functionality. In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you to program in multiple threads fearlessly. Chapter 17 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. Chapter 18 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 19 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures. In Chapter 20, we’ll complete a project in which we’ll implement a low-level multithreaded web server! Finally, some appendices contain useful information about the language in a more reference-like format. Appendix A covers Rust’s keywords, Appendix B covers Rust’s operators and symbols, Appendix C covers derivable traits provided by the standard library, Appendix D covers some useful development tools, and Appendix E explains Rust editions. In Appendix F, you can find translations of the book, and in Appendix G we’ll cover how Rust is made and what nightly Rust is. There is no wrong way to read this book: if you want to skip ahead, go for it! You might have to jump back to earlier chapters if you experience any confusion. But do whatever works for you. An important part of the process of learning Rust is learning how to read the error messages the compiler displays: these will guide you toward working code. As such, we’ll provide many examples that don’t compile along with the error message the compiler will show you in each situation. Know that if you enter and run a random example, it may not compile! Make sure you read the surrounding text to see whether the example you’re trying to run is meant to error. Ferris will also help you distinguish code that isn’t meant to work: | Ferris | Meaning | | --- | --- | | | This code does not compile! | | | This code panics! | | | This code does not produce the desired behavior. | In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Source Code ----------- The source files from which this book is generated can be found on [GitHub](https://github.com/rust-lang/book/tree/main/src). rust Improving Our I/O Project Improving Our I/O Project ========================= With this new knowledge about iterators, we can improve the I/O project in Chapter 12 by using iterators to make places in the code clearer and more concise. Let’s look at how iterators can improve our implementation of the `Config::build` function and the `search` function. ### Removing a `clone` Using an Iterator In Listing 12-6, we added code that took a slice of `String` values and created an instance of the `Config` struct by indexing into the slice and cloning the values, allowing the `Config` struct to own those values. In Listing 13-17, we’ve reproduced the implementation of the `Config::build` function as it was in Listing 12-23: Filename: src/lib.rs ``` use std::env; use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config { query, file_path, ignore_case, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 13-17: Reproduction of the `Config::build` function from Listing 12-23 At the time, we said not to worry about the inefficient `clone` calls because we would remove them in the future. Well, that time is now! We needed `clone` here because we have a slice with `String` elements in the parameter `args`, but the `build` function doesn’t own `args`. To return ownership of a `Config` instance, we had to clone the values from the `query` and `filename` fields of `Config` so the `Config` instance can own its values. With our new knowledge about iterators, we can change the `build` function to take ownership of an iterator as its argument instead of borrowing a slice. We’ll use the iterator functionality instead of the code that checks the length of the slice and indexes into specific locations. This will clarify what the `Config::build` function is doing because the iterator will access the values. Once `Config::build` takes ownership of the iterator and stops using indexing operations that borrow, we can move the `String` values from the iterator into `Config` rather than calling `clone` and making a new allocation. #### Using the Returned Iterator Directly Open your I/O project’s *src/main.rs* file, which should look like this: Filename: src/main.rs ``` use std::env; use std::process; use minigrep::Config; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {err}"); process::exit(1); }); // --snip-- if let Err(e) = minigrep::run(config) { eprintln!("Application error: {e}"); process::exit(1); } } ``` We’ll first change the start of the `main` function that we had in Listing 12-24 to the code in Listing 13-18, which this time uses an iterator. This won’t compile until we update `Config::build` as well. Filename: src/main.rs ``` use std::env; use std::process; use minigrep::Config; fn main() { let config = Config::build(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {err}"); process::exit(1); }); // --snip-- if let Err(e) = minigrep::run(config) { eprintln!("Application error: {e}"); process::exit(1); } } ``` Listing 13-18: Passing the return value of `env::args` to `Config::build` The `env::args` function returns an iterator! Rather than collecting the iterator values into a vector and then passing a slice to `Config::build`, now we’re passing ownership of the iterator returned from `env::args` to `Config::build` directly. Next, we need to update the definition of `Config::build`. In your I/O project’s *src/lib.rs* file, let’s change the signature of `Config::build` to look like Listing 13-19. This still won’t compile because we need to update the function body. Filename: src/lib.rs ``` use std::env; use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build( mut args: impl Iterator<Item = String>, ) -> Result<Config, &'static str> { // --snip-- if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config { query, file_path, ignore_case, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 13-19: Updating the signature of `Config::build` to expect an iterator The standard library documentation for the `env::args` function shows that the type of the iterator it returns is `std::env::Args`, and that type implements the `Iterator` trait and returns `String` values. We’ve updated the signature of the `Config::build` function so the parameter `args` has a generic type with the trait bounds `impl Iterator<Item = String>` instead of `&[String]`. This usage of the `impl Trait` syntax we discussed in the [“Traits as Parameters”](ch10-02-traits#traits-as-parameters) section of Chapter 10 means that `args` can be any type that implements the `Iterator` type and returns `String` items. Because we’re taking ownership of `args` and we’ll be mutating `args` by iterating over it, we can add the `mut` keyword into the specification of the `args` parameter to make it mutable. #### Using `Iterator` Trait Methods Instead of Indexing Next, we’ll fix the body of `Config::build`. Because `args` implements the `Iterator` trait, we know we can call the `next` method on it! Listing 13-20 updates the code from Listing 12-23 to use the `next` method: Filename: src/lib.rs ``` use std::env; use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build( mut args: impl Iterator<Item = String>, ) -> Result<Config, &'static str> { args.next(); let query = match args.next() { Some(arg) => arg, None => return Err("Didn't get a query string"), }; let file_path = match args.next() { Some(arg) => arg, None => return Err("Didn't get a file path"), }; let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config { query, file_path, ignore_case, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 13-20: Changing the body of `Config::build` to use iterator methods Remember that the first value in the return value of `env::args` is the name of the program. We want to ignore that and get to the next value, so first we call `next` and do nothing with the return value. Second, we call `next` to get the value we want to put in the `query` field of `Config`. If `next` returns a `Some`, we use a `match` to extract the value. If it returns `None`, it means not enough arguments were given and we return early with an `Err` value. We do the same thing for the `filename` value. ### Making Code Clearer with Iterator Adaptors We can also take advantage of iterators in the `search` function in our I/O project, which is reproduced here in Listing 13-21 as it was in Listing 12-19: Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } } ``` Listing 13-21: The implementation of the `search` function from Listing 12-19 We can write this code in a more concise way using iterator adaptor methods. Doing so also lets us avoid having a mutable intermediate `results` vector. The functional programming style prefers to minimize the amount of mutable state to make code clearer. Removing the mutable state might enable a future enhancement to make searching happen in parallel, because we wouldn’t have to manage concurrent access to the `results` vector. Listing 13-22 shows this change: Filename: src/lib.rs ``` use std::env; use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build( mut args: impl Iterator<Item = String>, ) -> Result<Config, &'static str> { args.next(); let query = match args.next() { Some(arg) => arg, None => return Err("Didn't get a query string"), }; let file_path = match args.next() { Some(arg) => arg, None => return Err("Didn't get a file path"), }; let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config { query, file_path, ignore_case, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { contents .lines() .filter(|line| line.contains(query)) .collect() } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 13-22: Using iterator adaptor methods in the implementation of the `search` function Recall that the purpose of the `search` function is to return all lines in `contents` that contain the `query`. Similar to the `filter` example in Listing 13-16, this code uses the `filter` adaptor to keep only the lines that `line.contains(query)` returns `true` for. We then collect the matching lines into another vector with `collect`. Much simpler! Feel free to make the same change to use iterator methods in the `search_case_insensitive` function as well. ### Choosing Between Loops or Iterators The next logical question is which style you should choose in your own code and why: the original implementation in Listing 13-21 or the version using iterators in Listing 13-22. Most Rust programmers prefer to use the iterator style. It’s a bit tougher to get the hang of at first, but once you get a feel for the various iterator adaptors and what they do, iterators can be easier to understand. Instead of fiddling with the various bits of looping and building new vectors, the code focuses on the high-level objective of the loop. This abstracts away some of the commonplace code so it’s easier to see the concepts that are unique to this code, such as the filtering condition each element in the iterator must pass. But are the two implementations truly equivalent? The intuitive assumption might be that the more low-level loop will be faster. Let’s talk about performance.
programming_docs
rust Storing Keys with Associated Values in Hash Maps Storing Keys with Associated Values in Hash Maps ================================================ The last of our common collections is the *hash map*. The type `HashMap<K, V>` stores a mapping of keys of type `K` to values of type `V` using a *hashing function*, which determines how it places these keys and values into memory. Many programming languages support this kind of data structure, but they often use a different name, such as hash, map, object, hash table, dictionary, or associative array, just to name a few. Hash maps are useful when you want to look up data not by using an index, as you can with vectors, but by using a key that can be of any type. For example, in a game, you could keep track of each team’s score in a hash map in which each key is a team’s name and the values are each team’s score. Given a team name, you can retrieve its score. We’ll go over the basic API of hash maps in this section, but many more goodies are hiding in the functions defined on `HashMap<K, V>` by the standard library. As always, check the standard library documentation for more information. ### Creating a New Hash Map One way to create an empty hash map is using `new` and adding elements with `insert`. In Listing 8-20, we’re keeping track of the scores of two teams whose names are *Blue* and *Yellow*. The Blue team starts with 10 points, and the Yellow team starts with 50. ``` fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); } ``` Listing 8-20: Creating a new hash map and inserting some keys and values Note that we need to first `use` the `HashMap` from the collections portion of the standard library. Of our three common collections, this one is the least often used, so it’s not included in the features brought into scope automatically in the prelude. Hash maps also have less support from the standard library; there’s no built-in macro to construct them, for example. Just like vectors, hash maps store their data on the heap. This `HashMap` has keys of type `String` and values of type `i32`. Like vectors, hash maps are homogeneous: all of the keys must have the same type as each other, and all of the values must have the same type. ### Accessing Values in a Hash Map We can get a value out of the hash map by providing its key to the `get` method, as shown in Listing 8-21. ``` fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let team_name = String::from("Blue"); let score = scores.get(&team_name).copied().unwrap_or(0); } ``` Listing 8-21: Accessing the score for the Blue team stored in the hash map Here, `score` will have the value that’s associated with the Blue team, and the result will be `10`. The `get` method returns an `Option<&V>`; if there’s no value for that key in the hash map, `get` will return `None`. This program handles the `Option` by calling `copied` to get an `Option<i32>` rather than an `Option<&i32>`, then `unwrap_or` to set `score` to zero if `scores` doesn't have an entry for the key. We can iterate over each key/value pair in a hash map in a similar manner as we do with vectors, using a `for` loop: ``` fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); for (key, value) in &scores { println!("{}: {}", key, value); } } ``` This code will print each pair in an arbitrary order: ``` Yellow: 50 Blue: 10 ``` ### Hash Maps and Ownership For types that implement the `Copy` trait, like `i32`, the values are copied into the hash map. For owned values like `String`, the values will be moved and the hash map will be the owner of those values, as demonstrated in Listing 8-22. ``` fn main() { use std::collections::HashMap; let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); // field_name and field_value are invalid at this point, try using them and // see what compiler error you get! } ``` Listing 8-22: Showing that keys and values are owned by the hash map once they’re inserted We aren’t able to use the variables `field_name` and `field_value` after they’ve been moved into the hash map with the call to `insert`. If we insert references to values into the hash map, the values won’t be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid. We’ll talk more about these issues in the [“Validating References with Lifetimes”](ch10-03-lifetime-syntax#validating-references-with-lifetimes) section in Chapter 10. ### Updating a Hash Map Although the number of key and value pairs is growable, each unique key can only have one value associated with it at a time (but not vice versa: for example, both the Blue team and the Yellow team could have value 10 stored in the `scores` hash map). When you want to change the data in a hash map, you have to decide how to handle the case when a key already has a value assigned. You could replace the old value with the new value, completely disregarding the old value. You could keep the old value and ignore the new value, only adding the new value if the key *doesn’t* already have a value. Or you could combine the old value and the new value. Let’s look at how to do each of these! #### Overwriting a Value If we insert a key and a value into a hash map and then insert that same key with a different value, the value associated with that key will be replaced. Even though the code in Listing 8-23 calls `insert` twice, the hash map will only contain one key/value pair because we’re inserting the value for the Blue team’s key both times. ``` fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Blue"), 25); println!("{:?}", scores); } ``` Listing 8-23: Replacing a value stored with a particular key This code will print `{"Blue": 25}`. The original value of `10` has been overwritten. #### Adding a Key and Value Only If a Key Isn’t Present It’s common to check whether a particular key already exists in the hash map with a value then take the following actions: if the key does exist in the hash map, the existing value should remain the way it is. If the key doesn’t exist, insert it and a value for it. Hash maps have a special API for this called `entry` that takes the key you want to check as a parameter. The return value of the `entry` method is an enum called `Entry` that represents a value that might or might not exist. Let’s say we want to check whether the key for the Yellow team has a value associated with it. If it doesn’t, we want to insert the value 50, and the same for the Blue team. Using the `entry` API, the code looks like Listing 8-24. ``` fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.entry(String::from("Yellow")).or_insert(50); scores.entry(String::from("Blue")).or_insert(50); println!("{:?}", scores); } ``` Listing 8-24: Using the `entry` method to only insert if the key does not already have a value The `or_insert` method on `Entry` is defined to return a mutable reference to the value for the corresponding `Entry` key if that key exists, and if not, inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker. Running the code in Listing 8-24 will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry` will insert the key for the Yellow team with the value 50 because the Yellow team doesn’t have a value already. The second call to `entry` will not change the hash map because the Blue team already has the value 10. #### Updating a Value Based on the Old Value Another common use case for hash maps is to look up a key’s value and then update it based on the old value. For instance, Listing 8-25 shows code that counts how many times each word appears in some text. We use a hash map with the words as keys and increment the value to keep track of how many times we’ve seen that word. If it’s the first time we’ve seen a word, we’ll first insert the value 0. ``` fn main() { use std::collections::HashMap; let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{:?}", map); } ``` Listing 8-25: Counting occurrences of words using a hash map that stores words and counts This code will print `{"world": 2, "hello": 1, "wonderful": 1}`. You might see the same key/value pairs printed in a different order: recall from the [“Accessing Values in a Hash Map”](#accessing-values-in-a-hash-map) section that iterating over a hash map happens in an arbitrary order. The `split_whitespace` method returns an iterator over sub-slices, separated by whitespace, of the value in `text`. The `or_insert` method returns a mutable reference (`&mut V`) to the value for the specified key. Here we store that mutable reference in the `count` variable, so in order to assign to that value, we must first dereference `count` using the asterisk (`*`). The mutable reference goes out of scope at the end of the `for` loop, so all of these changes are safe and allowed by the borrowing rules. ### Hashing Functions By default, `HashMap` uses a hashing function called *SipHash* that can provide resistance to Denial of Service (DoS) attacks involving hash tables[1](#siphash). This is not the fastest hashing algorithm available, but the trade-off for better security that comes with the drop in performance is worth it. If you profile your code and find that the default hash function is too slow for your purposes, you can switch to another function by specifying a different hasher. A *hasher* is a type that implements the `BuildHasher` trait. We’ll talk about traits and how to implement them in Chapter 10. You don’t necessarily have to implement your own hasher from scratch; [crates.io](https://crates.io/) has libraries shared by other Rust users that provide hashers implementing many common hashing algorithms. 1 <https://en.wikipedia.org/wiki/SipHash> Summary ------- Vectors, strings, and hash maps will provide a large amount of functionality necessary in programs when you need to store, access, and modify data. Here are some exercises you should now be equipped to solve: * Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list. * Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”). Keep in mind the details about UTF-8 encoding! * Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically. The standard library API documentation describes methods that vectors, strings, and hash maps have that will be helpful for these exercises! We’re getting into more complex programs in which operations can fail, so, it’s a perfect time to discuss error handling. We’ll do that next! rust Processing a Series of Items with Iterators Processing a Series of Items with Iterators =========================================== The iterator pattern allows you to perform some task on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don’t have to reimplement that logic yourself. In Rust, iterators are *lazy*, meaning they have no effect until you call methods that consume the iterator to use it up. For example, the code in Listing 13-10 creates an iterator over the items in the vector `v1` by calling the `iter` method defined on `Vec<T>`. This code by itself doesn’t do anything useful. ``` fn main() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); } ``` Listing 13-10: Creating an iterator The iterator is stored in the `v1_iter` variable. Once we’ve created an iterator, we can use it in a variety of ways. In Listing 3-5 in Chapter 3, we iterated over an array using a `for` loop to execute some code on each of its items. Under the hood this implicitly created and then consumed an iterator, but we glossed over how exactly that works until now. In the example in Listing 13-11, we separate the creation of the iterator from the use of the iterator in the `for` loop. When the `for` loop is called using the iterator in `v1_iter`, each element in the iterator is used in one iteration of the loop, which prints out each value. ``` fn main() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); for val in v1_iter { println!("Got: {}", val); } } ``` Listing 13-11: Using an iterator in a `for` loop In languages that don’t have iterators provided by their standard libraries, you would likely write this same functionality by starting a variable at index 0, using that variable to index into the vector to get a value, and incrementing the variable value in a loop until it reached the total number of items in the vector. Iterators handle all that logic for you, cutting down on repetitive code you could potentially mess up. Iterators give you more flexibility to use the same logic with many different kinds of sequences, not just data structures you can index into, like vectors. Let’s examine how iterators do that. ### The `Iterator` Trait and the `next` Method All iterators implement a trait named `Iterator` that is defined in the standard library. The definition of the trait looks like this: ``` #![allow(unused)] fn main() { pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; // methods with default implementations elided } } ``` Notice this definition uses some new syntax: `type Item` and `Self::Item`, which are defining an *associated type* with this trait. We’ll talk about associated types in depth in Chapter 19. For now, all you need to know is that this code says implementing the `Iterator` trait requires that you also define an `Item` type, and this `Item` type is used in the return type of the `next` method. In other words, the `Item` type will be the type returned from the iterator. The `Iterator` trait only requires implementors to define one method: the `next` method, which returns one item of the iterator at a time wrapped in `Some` and, when iteration is over, returns `None`. We can call the `next` method on iterators directly; Listing 13-12 demonstrates what values are returned from repeated calls to `next` on the iterator created from the vector. Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn iterator_demonstration() { let v1 = vec![1, 2, 3]; let mut v1_iter = v1.iter(); assert_eq!(v1_iter.next(), Some(&1)); assert_eq!(v1_iter.next(), Some(&2)); assert_eq!(v1_iter.next(), Some(&3)); assert_eq!(v1_iter.next(), None); } } ``` Listing 13-12: Calling the `next` method on an iterator Note that we needed to make `v1_iter` mutable: calling the `next` method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code *consumes*, or uses up, the iterator. Each call to `next` eats up an item from the iterator. We didn’t need to make `v1_iter` mutable when we used a `for` loop because the loop took ownership of `v1_iter` and made it mutable behind the scenes. Also note that the values we get from the calls to `next` are immutable references to the values in the vector. The `iter` method produces an iterator over immutable references. If we want to create an iterator that takes ownership of `v1` and returns owned values, we can call `into_iter` instead of `iter`. Similarly, if we want to iterate over mutable references, we can call `iter_mut` instead of `iter`. ### Methods that Consume the Iterator The `Iterator` trait has a number of different methods with default implementations provided by the standard library; you can find out about these methods by looking in the standard library API documentation for the `Iterator` trait. Some of these methods call the `next` method in their definition, which is why you’re required to implement the `next` method when implementing the `Iterator` trait. Methods that call `next` are called *consuming adaptors*, because calling them uses up the iterator. One example is the `sum` method, which takes ownership of the iterator and iterates through the items by repeatedly calling `next`, thus consuming the iterator. As it iterates through, it adds each item to a running total and returns the total when iteration is complete. Listing 13-13 has a test illustrating a use of the `sum` method: Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn iterator_sum() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); let total: i32 = v1_iter.sum(); assert_eq!(total, 6); } } ``` Listing 13-13: Calling the `sum` method to get the total of all items in the iterator We aren’t allowed to use `v1_iter` after the call to `sum` because `sum` takes ownership of the iterator we call it on. ### Methods that Produce Other Iterators *Iterator adaptors* are methods defined on the `Iterator` trait that don’t consume the iterator. Instead, they produce different iterators by changing some aspect of the original iterator. Listing 13-17 shows an example of calling the iterator adaptor method `map`, which takes a closure to call on each item as the items are iterated through. The `map` method returns a new iterator that produces the modified items. The closure here creates a new iterator in which each item from the vector will be incremented by 1: Filename: src/main.rs ``` fn main() { let v1: Vec<i32> = vec![1, 2, 3]; v1.iter().map(|x| x + 1); } ``` Listing 13-14: Calling the iterator adaptor `map` to create a new iterator However, this code produces a warning: ``` $ cargo run Compiling iterators v0.1.0 (file:///projects/iterators) warning: unused `Map` that must be used --> src/main.rs:4:5 | 4 | v1.iter().map(|x| x + 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_must_use)]` on by default = note: iterators are lazy and do nothing unless consumed warning: `iterators` (bin "iterators") generated 1 warning Finished dev [unoptimized + debuginfo] target(s) in 0.47s Running `target/debug/iterators` ``` The code in Listing 13-14 doesn’t do anything; the closure we’ve specified never gets called. The warning reminds us why: iterator adaptors are lazy, and we need to consume the iterator here. To fix this warning and consume the iterator, we’ll use the `collect` method, which we used in Chapter 12 with `env::args` in Listing 12-1. This method consumes the iterator and collects the resulting values into a collection data type. In Listing 13-15, we collect the results of iterating over the iterator that’s returned from the call to `map` into a vector. This vector will end up containing each item from the original vector incremented by 1. Filename: src/main.rs ``` fn main() { let v1: Vec<i32> = vec![1, 2, 3]; let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); assert_eq!(v2, vec![2, 3, 4]); } ``` Listing 13-15: Calling the `map` method to create a new iterator and then calling the `collect` method to consume the new iterator and create a vector Because `map` takes a closure, we can specify any operation we want to perform on each item. This is a great example of how closures let you customize some behavior while reusing the iteration behavior that the `Iterator` trait provides. You can chain multiple calls to iterator adaptors to perform complex actions in a readable way. But because all iterators are lazy, you have to call one of the consuming adaptor methods to get results from calls to iterator adaptors. ### Using Closures that Capture Their Environment Many iterator adapters take closures as arguments, and commonly the closures we’ll specify as arguments to iterator adapters will be closures that capture their environment. For this example, we’ll use the `filter` method that takes a closure. The closure gets an item from the iterator and returns a `bool`. If the closure returns `true`, the value will be included in the iteration produced by `filter`. If the closure returns `false`, the value won’t be included. In Listing 13-16, we use `filter` with a closure that captures the `shoe_size` variable from its environment to iterate over a collection of `Shoe` struct instances. It will return only shoes that are the specified size. Filename: src/lib.rs ``` #[derive(PartialEq, Debug)] struct Shoe { size: u32, style: String, } fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn filters_by_size() { let shoes = vec![ Shoe { size: 10, style: String::from("sneaker"), }, Shoe { size: 13, style: String::from("sandal"), }, Shoe { size: 10, style: String::from("boot"), }, ]; let in_my_size = shoes_in_size(shoes, 10); assert_eq!( in_my_size, vec![ Shoe { size: 10, style: String::from("sneaker") }, Shoe { size: 10, style: String::from("boot") }, ] ); } } ``` Listing 13-16: Using the `filter` method with a closure that captures `shoe_size` The `shoes_in_size` function takes ownership of a vector of shoes and a shoe size as parameters. It returns a vector containing only shoes of the specified size. In the body of `shoes_in_size`, we call `into_iter` to create an iterator that takes ownership of the vector. Then we call `filter` to adapt that iterator into a new iterator that only contains elements for which the closure returns `true`. The closure captures the `shoe_size` parameter from the environment and compares the value with each shoe’s size, keeping only shoes of the size specified. Finally, calling `collect` gathers the values returned by the adapted iterator into a vector that’s returned by the function. The test shows that when we call `shoes_in_size`, we get back only shoes that have the same size as the value we specified.
programming_docs
rust Using Threads to Run Code Simultaneously Using Threads to Run Code Simultaneously ======================================== In most current operating systems, an executed program’s code is run in a *process*, and the operating system will manage multiple processes at once. Within a program, you can also have independent parts that run simultaneously. The features that run these independent parts are called *threads*. For example, a web server could have multiple threads so that it could respond to more than one request at the same time. Splitting the computation in your program into multiple threads to run multiple tasks at the same time can improve performance, but it also adds complexity. Because threads can run simultaneously, there’s no inherent guarantee about the order in which parts of your code on different threads will run. This can lead to problems, such as: * Race conditions, where threads are accessing data or resources in an inconsistent order * Deadlocks, where two threads are waiting for each other, preventing both threads from continuing * Bugs that happen only in certain situations and are hard to reproduce and fix reliably Rust attempts to mitigate the negative effects of using threads, but programming in a multithreaded context still takes careful thought and requires a code structure that is different from that in programs running in a single thread. Programming languages implement threads in a few different ways, and many operating systems provide an API the language can call for creating new threads. The Rust standard library uses a *1:1* model of thread implementation, whereby a program uses one operating system thread per one language thread. There are crates that implement other models of threading that make different tradeoffs to the 1:1 model. ### Creating a New Thread with `spawn` To create a new thread, we call the `thread::spawn` function and pass it a closure (we talked about closures in Chapter 13) containing the code we want to run in the new thread. The example in Listing 16-1 prints some text from a main thread and other text from a new thread: Filename: src/main.rs ``` use std::thread; use std::time::Duration; fn main() { thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } } ``` Listing 16-1: Creating a new thread to print one thing while the main thread prints something else Note that when the main thread of a Rust program completes, all spawned threads are shut down, whether or not they have finished running. The output from this program might be a little different every time, but it will look similar to the following: ``` hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the main thread! hi number 2 from the spawned thread! hi number 3 from the main thread! hi number 3 from the spawned thread! hi number 4 from the main thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! ``` The calls to `thread::sleep` force a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that isn’t guaranteed: it depends on how your operating system schedules the threads. In this run, the main thread printed first, even though the print statement from the spawned thread appears first in the code. And even though we told the spawned thread to print until `i` is 9, it only got to 5 before the main thread shut down. If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads. ### Waiting for All Threads to Finish Using `join` Handles The code in Listing 16-1 not only stops the spawned thread prematurely most of the time due to the main thread ending, but because there is no guarantee on the order in which threads run, we also can’t guarantee that the spawned thread will get to run at all! We can fix the problem of the spawned thread not running or ending prematurely by saving the return value of `thread::spawn` in a variable. The return type of `thread::spawn` is `JoinHandle`. A `JoinHandle` is an owned value that, when we call the `join` method on it, will wait for its thread to finish. Listing 16-2 shows how to use the `JoinHandle` of the thread we created in Listing 16-1 and call `join` to make sure the spawned thread finishes before `main` exits: Filename: src/main.rs ``` use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); } ``` Listing 16-2: Saving a `JoinHandle` from `thread::spawn` to guarantee the thread is run to completion Calling `join` on the handle blocks the thread currently running until the thread represented by the handle terminates. *Blocking* a thread means that thread is prevented from performing work or exiting. Because we’ve put the call to `join` after the main thread’s `for` loop, running Listing 16-2 should produce output similar to this: ``` hi number 1 from the main thread! hi number 2 from the main thread! hi number 1 from the spawned thread! hi number 3 from the main thread! hi number 2 from the spawned thread! hi number 4 from the main thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! ``` The two threads continue alternating, but the main thread waits because of the call to `handle.join()` and does not end until the spawned thread is finished. But let’s see what happens when we instead move `handle.join()` before the `for` loop in `main`, like this: Filename: src/main.rs ``` use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); handle.join().unwrap(); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } } ``` The main thread will wait for the spawned thread to finish and then run its `for` loop, so the output won’t be interleaved anymore, as shown here: ``` hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! hi number 1 from the main thread! hi number 2 from the main thread! hi number 3 from the main thread! hi number 4 from the main thread! ``` Small details, such as where `join` is called, can affect whether or not your threads run at the same time. ### Using `move` Closures with Threads We'll often use the `move` keyword with closures passed to `thread::spawn` because the closure will then take ownership of the values it uses from the environment, thus transferring ownership of those values from one thread to another. In the [“Capturing the Environment with Closures”](ch13-01-closures#capturing-the-environment-with-closures) section of Chapter 13, we discussed `move` in the context of closures. Now, we’ll concentrate more on the interaction between `move` and `thread::spawn`. Notice in Listing 16-1 that the closure we pass to `thread::spawn` takes no arguments: we’re not using any data from the main thread in the spawned thread’s code. To use data from the main thread in the spawned thread, the spawned thread’s closure must capture the values it needs. Listing 16-3 shows an attempt to create a vector in the main thread and use it in the spawned thread. However, this won’t yet work, as you’ll see in a moment. Filename: src/main.rs ``` use std::thread; fn main() { let v = vec![1, 2, 3]; let handle = thread::spawn(|| { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } ``` Listing 16-3: Attempting to use a vector created by the main thread in another thread The closure uses `v`, so it will capture `v` and make it part of the closure’s environment. Because `thread::spawn` runs this closure in a new thread, we should be able to access `v` inside that new thread. But when we compile this example, we get the following error: ``` $ cargo run Compiling threads v0.1.0 (file:///projects/threads) error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function --> src/main.rs:6:32 | 6 | let handle = thread::spawn(|| { | ^^ may outlive borrowed value `v` 7 | println!("Here's a vector: {:?}", v); | - `v` is borrowed here | note: function requires argument type to outlive `'static` --> src/main.rs:6:18 | 6 | let handle = thread::spawn(|| { | __________________^ 7 | | println!("Here's a vector: {:?}", v); 8 | | }); | |______^ help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword | 6 | let handle = thread::spawn(move || { | ++++ For more information about this error, try `rustc --explain E0373`. error: could not compile `threads` due to previous error ``` Rust *infers* how to capture `v`, and because `println!` only needs a reference to `v`, the closure tries to borrow `v`. However, there’s a problem: Rust can’t tell how long the spawned thread will run, so it doesn’t know if the reference to `v` will always be valid. Listing 16-4 provides a scenario that’s more likely to have a reference to `v` that won’t be valid: Filename: src/main.rs ``` use std::thread; fn main() { let v = vec![1, 2, 3]; let handle = thread::spawn(|| { println!("Here's a vector: {:?}", v); }); drop(v); // oh no! handle.join().unwrap(); } ``` Listing 16-4: A thread with a closure that attempts to capture a reference to `v` from a main thread that drops `v` If Rust allowed us to run this code, there’s a possibility the spawned thread would be immediately put in the background without running at all. The spawned thread has a reference to `v` inside, but the main thread immediately drops `v`, using the `drop` function we discussed in Chapter 15. Then, when the spawned thread starts to execute, `v` is no longer valid, so a reference to it is also invalid. Oh no! To fix the compiler error in Listing 16-3, we can use the error message’s advice: ``` help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword | 6 | let handle = thread::spawn(move || { | ++++ ``` By adding the `move` keyword before the closure, we force the closure to take ownership of the values it’s using rather than allowing Rust to infer that it should borrow the values. The modification to Listing 16-3 shown in Listing 16-5 will compile and run as we intend: Filename: src/main.rs ``` use std::thread; fn main() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } ``` Listing 16-5: Using the `move` keyword to force a closure to take ownership of the values it uses We might be tempted to try the same thing to fix the code in Listing 16-4 where the main thread called `drop` by using a `move` closure. However, this fix will not work because what Listing 16-4 is trying to do is disallowed for a different reason. If we added `move` to the closure, we would move `v` into the closure’s environment, and we could no longer call `drop` on it in the main thread. We would get this compiler error instead: ``` $ cargo run Compiling threads v0.1.0 (file:///projects/threads) error[E0382]: use of moved value: `v` --> src/main.rs:10:10 | 4 | let v = vec![1, 2, 3]; | - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait 5 | 6 | let handle = thread::spawn(move || { | ------- value moved into closure here 7 | println!("Here's a vector: {:?}", v); | - variable moved due to use in closure ... 10 | drop(v); // oh no! | ^ value used here after move For more information about this error, try `rustc --explain E0382`. error: could not compile `threads` due to previous error ``` Rust’s ownership rules have saved us again! We got an error from the code in Listing 16-3 because Rust was being conservative and only borrowing `v` for the thread, which meant the main thread could theoretically invalidate the spawned thread’s reference. By telling Rust to move ownership of `v` to the spawned thread, we’re guaranteeing Rust that the main thread won’t use `v` anymore. If we change Listing 16-4 in the same way, we’re then violating the ownership rules when we try to use `v` in the main thread. The `move` keyword overrides Rust’s conservative default of borrowing; it doesn’t let us violate the ownership rules. With a basic understanding of threads and the thread API, let’s look at what we can *do* with threads. rust Shared-State Concurrency Shared-State Concurrency ======================== Message passing is a fine way of handling concurrency, but it’s not the only one. Another method would be for multiple threads to access the same shared data. Consider this part of the slogan from the Go language documentation again: “do not communicate by sharing memory.” What would communicating by sharing memory look like? In addition, why would message-passing enthusiasts caution not to use memory sharing? In a way, channels in any programming language are similar to single ownership, because once you transfer a value down a channel, you should no longer use that value. Shared memory concurrency is like multiple ownership: multiple threads can access the same memory location at the same time. As you saw in Chapter 15, where smart pointers made multiple ownership possible, multiple ownership can add complexity because these different owners need managing. Rust’s type system and ownership rules greatly assist in getting this management correct. For an example, let’s look at mutexes, one of the more common concurrency primitives for shared memory. ### Using Mutexes to Allow Access to Data from One Thread at a Time *Mutex* is an abbreviation for *mutual exclusion*, as in, a mutex allows only one thread to access some data at any given time. To access the data in a mutex, a thread must first signal that it wants access by asking to acquire the mutex’s *lock*. The lock is a data structure that is part of the mutex that keeps track of who currently has exclusive access to the data. Therefore, the mutex is described as *guarding* the data it holds via the locking system. Mutexes have a reputation for being difficult to use because you have to remember two rules: * You must attempt to acquire the lock before using the data. * When you’re done with the data that the mutex guards, you must unlock the data so other threads can acquire the lock. For a real-world metaphor for a mutex, imagine a panel discussion at a conference with only one microphone. Before a panelist can speak, they have to ask or signal that they want to use the microphone. When they get the microphone, they can talk for as long as they want to and then hand the microphone to the next panelist who requests to speak. If a panelist forgets to hand the microphone off when they’re finished with it, no one else is able to speak. If management of the shared microphone goes wrong, the panel won’t work as planned! Management of mutexes can be incredibly tricky to get right, which is why so many people are enthusiastic about channels. However, thanks to Rust’s type system and ownership rules, you can’t get locking and unlocking wrong. #### The API of `Mutex<T>` As an example of how to use a mutex, let’s start by using a mutex in a single-threaded context, as shown in Listing 16-12: Filename: src/main.rs ``` use std::sync::Mutex; fn main() { let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } println!("m = {:?}", m); } ``` Listing 16-12: Exploring the API of `Mutex<T>` in a single-threaded context for simplicity As with many types, we create a `Mutex<T>` using the associated function `new`. To access the data inside the mutex, we use the `lock` method to acquire the lock. This call will block the current thread so it can’t do any work until it’s our turn to have the lock. The call to `lock` would fail if another thread holding the lock panicked. In that case, no one would ever be able to get the lock, so we’ve chosen to `unwrap` and have this thread panic if we’re in that situation. After we’ve acquired the lock, we can treat the return value, named `num` in this case, as a mutable reference to the data inside. The type system ensures that we acquire a lock before using the value in `m`. The type of `m` is `Mutex<i32>`, not `i32`, so we *must* call `lock` to be able to use the `i32` value. We can’t forget; the type system won’t let us access the inner `i32` otherwise. As you might suspect, `Mutex<T>` is a smart pointer. More accurately, the call to `lock` *returns* a smart pointer called `MutexGuard`, wrapped in a `LockResult` that we handled with the call to `unwrap`. The `MutexGuard` smart pointer implements `Deref` to point at our inner data; the smart pointer also has a `Drop` implementation that releases the lock automatically when a `MutexGuard` goes out of scope, which happens at the end of the inner scope. As a result, we don’t risk forgetting to release the lock and blocking the mutex from being used by other threads, because the lock release happens automatically. After dropping the lock, we can print the mutex value and see that we were able to change the inner `i32` to 6. #### Sharing a `Mutex<T>` Between Multiple Threads Now, let’s try to share a value between multiple threads using `Mutex<T>`. We’ll spin up 10 threads and have them each increment a counter value by 1, so the counter goes from 0 to 10. The next example in Listing 16-13 will have a compiler error, and we’ll use that error to learn more about using `Mutex<T>` and how Rust helps us use it correctly. Filename: src/main.rs ``` use std::sync::Mutex; use std::thread; fn main() { let counter = Mutex::new(0); let mut handles = vec![]; for _ in 0..10 { let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } ``` Listing 16-13: Ten threads each increment a counter guarded by a `Mutex<T>` We create a `counter` variable to hold an `i32` inside a `Mutex<T>`, as we did in Listing 16-12. Next, we create 10 threads by iterating over a range of numbers. We use `thread::spawn` and give all the threads the same closure: one that moves the counter into the thread, acquires a lock on the `Mutex<T>` by calling the `lock` method, and then adds 1 to the value in the mutex. When a thread finishes running its closure, `num` will go out of scope and release the lock so another thread can acquire it. In the main thread, we collect all the join handles. Then, as we did in Listing 16-2, we call `join` on each handle to make sure all the threads finish. At that point, the main thread will acquire the lock and print the result of this program. We hinted that this example wouldn’t compile. Now let’s find out why! ``` $ cargo run Compiling shared-state v0.1.0 (file:///projects/shared-state) error[E0382]: use of moved value: `counter` --> src/main.rs:9:36 | 5 | let counter = Mutex::new(0); | ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait ... 9 | let handle = thread::spawn(move || { | ^^^^^^^ value moved into closure here, in previous iteration of loop 10 | let mut num = counter.lock().unwrap(); | ------- use occurs due to use in closure For more information about this error, try `rustc --explain E0382`. error: could not compile `shared-state` due to previous error ``` The error message states that the `counter` value was moved in the previous iteration of the loop. Rust is telling us that we can’t move the ownership of lock `counter` into multiple threads. Let’s fix the compiler error with a multiple-ownership method we discussed in Chapter 15. #### Multiple Ownership with Multiple Threads In Chapter 15, we gave a value multiple owners by using the smart pointer `Rc<T>` to create a reference counted value. Let’s do the same here and see what happens. We’ll wrap the `Mutex<T>` in `Rc<T>` in Listing 16-14 and clone the `Rc<T>` before moving ownership to the thread. Filename: src/main.rs ``` use std::rc::Rc; use std::sync::Mutex; use std::thread; fn main() { let counter = Rc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Rc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } ``` Listing 16-14: Attempting to use `Rc<T>` to allow multiple threads to own the `Mutex<T>` Once again, we compile and get... different errors! The compiler is teaching us a lot. ``` $ cargo run Compiling shared-state v0.1.0 (file:///projects/shared-state) error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely --> src/main.rs:11:22 | 11 | let handle = thread::spawn(move || { | ______________________^^^^^^^^^^^^^_- | | | | | `Rc<Mutex<i32>>` cannot be sent between threads safely 12 | | let mut num = counter.lock().unwrap(); 13 | | 14 | | *num += 1; 15 | | }); | |_________- within this `[closure@src/main.rs:11:36: 15:10]` | = help: within `[closure@src/main.rs:11:36: 15:10]`, the trait `Send` is not implemented for `Rc<Mutex<i32>>` = note: required because it appears within the type `[closure@src/main.rs:11:36: 15:10]` note: required by a bound in `spawn` For more information about this error, try `rustc --explain E0277`. error: could not compile `shared-state` due to previous error ``` Wow, that error message is very wordy! Here’s the important part to focus on: ``Rc<Mutex<i32>>` cannot be sent between threads safely`. The compiler is also telling us the reason why: `the trait `Send` is not implemented for `Rc<Mutex<i32>>`` . We’ll talk about `Send` in the next section: it’s one of the traits that ensures the types we use with threads are meant for use in concurrent situations. Unfortunately, `Rc<T>` is not safe to share across threads. When `Rc<T>` manages the reference count, it adds to the count for each call to `clone` and subtracts from the count when each clone is dropped. But it doesn’t use any concurrency primitives to make sure that changes to the count can’t be interrupted by another thread. This could lead to wrong counts—subtle bugs that could in turn lead to memory leaks or a value being dropped before we’re done with it. What we need is a type exactly like `Rc<T>` but one that makes changes to the reference count in a thread-safe way. #### Atomic Reference Counting with `Arc<T>` Fortunately, `Arc<T>` *is* a type like `Rc<T>` that is safe to use in concurrent situations. The *a* stands for *atomic*, meaning it’s an *atomically reference counted* type. Atomics are an additional kind of concurrency primitive that we won’t cover in detail here: see the standard library documentation for [`std::sync::atomic`](../std/sync/atomic/index) for more details. At this point, you just need to know that atomics work like primitive types but are safe to share across threads. You might then wonder why all primitive types aren’t atomic and why standard library types aren’t implemented to use `Arc<T>` by default. The reason is that thread safety comes with a performance penalty that you only want to pay when you really need to. If you’re just performing operations on values within a single thread, your code can run faster if it doesn’t have to enforce the guarantees atomics provide. Let’s return to our example: `Arc<T>` and `Rc<T>` have the same API, so we fix our program by changing the `use` line, the call to `new`, and the call to `clone`. The code in Listing 16-15 will finally compile and run: Filename: src/main.rs ``` use std::sync::{Arc, Mutex}; use std::thread; fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } ``` Listing 16-15: Using an `Arc<T>` to wrap the `Mutex<T>` to be able to share ownership across multiple threads This code will print the following: ``` Result: 10 ``` We did it! We counted from 0 to 10, which may not seem very impressive, but it did teach us a lot about `Mutex<T>` and thread safety. You could also use this program’s structure to do more complicated operations than just incrementing a counter. Using this strategy, you can divide a calculation into independent parts, split those parts across threads, and then use a `Mutex<T>` to have each thread update the final result with its part. Note that if you are doing simple numerical operations, there are types simpler than `Mutex<T>` types provided by the [`std::sync::atomic` module of the standard library](../std/sync/atomic/index). These types provide safe, concurrent, atomic access to primitive types. We chose to use `Mutex<T>` with a primitive type for this example so we could concentrate on how `Mutex<T>` works. ### Similarities Between `RefCell<T>`/`Rc<T>` and `Mutex<T>`/`Arc<T>` You might have noticed that `counter` is immutable but we could get a mutable reference to the value inside it; this means `Mutex<T>` provides interior mutability, as the `Cell` family does. In the same way we used `RefCell<T>` in Chapter 15 to allow us to mutate contents inside an `Rc<T>`, we use `Mutex<T>` to mutate contents inside an `Arc<T>`. Another detail to note is that Rust can’t protect you from all kinds of logic errors when you use `Mutex<T>`. Recall in Chapter 15 that using `Rc<T>` came with the risk of creating reference cycles, where two `Rc<T>` values refer to each other, causing memory leaks. Similarly, `Mutex<T>` comes with the risk of creating *deadlocks*. These occur when an operation needs to lock two resources and two threads have each acquired one of the locks, causing them to wait for each other forever. If you’re interested in deadlocks, try creating a Rust program that has a deadlock; then research deadlock mitigation strategies for mutexes in any language and have a go at implementing them in Rust. The standard library API documentation for `Mutex<T>` and `MutexGuard` offers useful information. We’ll round out this chapter by talking about the `Send` and `Sync` traits and how we can use them with custom types.
programming_docs
rust Appendix B: Operators and Symbols Appendix B: Operators and Symbols ================================= This appendix contains a glossary of Rust’s syntax, including operators and other symbols that appear by themselves or in the context of paths, generics, trait bounds, macros, attributes, comments, tuples, and brackets. ### Operators Table B-1 contains the operators in Rust, an example of how the operator would appear in context, a short explanation, and whether that operator is overloadable. If an operator is overloadable, the relevant trait to use to overload that operator is listed. Table B-1: Operators | Operator | Example | Explanation | Overloadable? | | --- | --- | --- | --- | | `!` | `ident!(...)`, `ident!{...}`, `ident![...]` | Macro expansion | | | `!` | `!expr` | Bitwise or logical complement | `Not` | | `!=` | `expr != expr` | Nonequality comparison | `PartialEq` | | `%` | `expr % expr` | Arithmetic remainder | `Rem` | | `%=` | `var %= expr` | Arithmetic remainder and assignment | `RemAssign` | | `&` | `&expr`, `&mut expr` | Borrow | | | `&` | `&type`, `&mut type`, `&'a type`, `&'a mut type` | Borrowed pointer type | | | `&` | `expr & expr` | Bitwise AND | `BitAnd` | | `&=` | `var &= expr` | Bitwise AND and assignment | `BitAndAssign` | | `&&` | `expr && expr` | Short-circuiting logical AND | | | `*` | `expr * expr` | Arithmetic multiplication | `Mul` | | `*=` | `var *= expr` | Arithmetic multiplication and assignment | `MulAssign` | | `*` | `*expr` | Dereference | `Deref` | | `*` | `*const type`, `*mut type` | Raw pointer | | | `+` | `trait + trait`, `'a + trait` | Compound type constraint | | | `+` | `expr + expr` | Arithmetic addition | `Add` | | `+=` | `var += expr` | Arithmetic addition and assignment | `AddAssign` | | `,` | `expr, expr` | Argument and element separator | | | `-` | `- expr` | Arithmetic negation | `Neg` | | `-` | `expr - expr` | Arithmetic subtraction | `Sub` | | `-=` | `var -= expr` | Arithmetic subtraction and assignment | `SubAssign` | | `->` | `fn(...) -> type`, `|...| -> type` | Function and closure return type | | | `.` | `expr.ident` | Member access | | | `..` | `..`, `expr..`, `..expr`, `expr..expr` | Right-exclusive range literal | `PartialOrd` | | `..=` | `..=expr`, `expr..=expr` | Right-inclusive range literal | `PartialOrd` | | `..` | `..expr` | Struct literal update syntax | | | `..` | `variant(x, ..)`, `struct_type { x, .. }` | “And the rest” pattern binding | | | `...` | `expr...expr` | (Deprecated, use `..=` instead) In a pattern: inclusive range pattern | | | `/` | `expr / expr` | Arithmetic division | `Div` | | `/=` | `var /= expr` | Arithmetic division and assignment | `DivAssign` | | `:` | `pat: type`, `ident: type` | Constraints | | | `:` | `ident: expr` | Struct field initializer | | | `:` | `'a: loop {...}` | Loop label | | | `;` | `expr;` | Statement and item terminator | | | `;` | `[...; len]` | Part of fixed-size array syntax | | | `<<` | `expr << expr` | Left-shift | `Shl` | | `<<=` | `var <<= expr` | Left-shift and assignment | `ShlAssign` | | `<` | `expr < expr` | Less than comparison | `PartialOrd` | | `<=` | `expr <= expr` | Less than or equal to comparison | `PartialOrd` | | `=` | `var = expr`, `ident = type` | Assignment/equivalence | | | `==` | `expr == expr` | Equality comparison | `PartialEq` | | `=>` | `pat => expr` | Part of match arm syntax | | | `>` | `expr > expr` | Greater than comparison | `PartialOrd` | | `>=` | `expr >= expr` | Greater than or equal to comparison | `PartialOrd` | | `>>` | `expr >> expr` | Right-shift | `Shr` | | `>>=` | `var >>= expr` | Right-shift and assignment | `ShrAssign` | | `@` | `ident @ pat` | Pattern binding | | | `^` | `expr ^ expr` | Bitwise exclusive OR | `BitXor` | | `^=` | `var ^= expr` | Bitwise exclusive OR and assignment | `BitXorAssign` | | `|` | `pat | pat` | Pattern alternatives | | | `|` | `expr | expr` | Bitwise OR | `BitOr` | | `|=` | `var |= expr` | Bitwise OR and assignment | `BitOrAssign` | | `||` | `expr || expr` | Short-circuiting logical OR | | | `?` | `expr?` | Error propagation | | ### Non-operator Symbols The following list contains all symbols that don’t function as operators; that is, they don’t behave like a function or method call. Table B-2 shows symbols that appear on their own and are valid in a variety of locations. Table B-2: Stand-Alone Syntax | Symbol | Explanation | | --- | --- | | `'ident` | Named lifetime or loop label | | `...u8`, `...i32`, `...f64`, `...usize`, etc. | Numeric literal of specific type | | `"..."` | String literal | | `r"..."`, `r#"..."#`, `r##"..."##`, etc. | Raw string literal, escape characters not processed | | `b"..."` | Byte string literal; constructs an array of bytes instead of a string | | `br"..."`, `br#"..."#`, `br##"..."##`, etc. | Raw byte string literal, combination of raw and byte string literal | | `'...'` | Character literal | | `b'...'` | ASCII byte literal | | `|...| expr` | Closure | | `!` | Always empty bottom type for diverging functions | | `_` | “Ignored” pattern binding; also used to make integer literals readable | Table B-3 shows symbols that appear in the context of a path through the module hierarchy to an item. Table B-3: Path-Related Syntax | Symbol | Explanation | | --- | --- | | `ident::ident` | Namespace path | | `::path` | Path relative to the crate root (i.e., an explicitly absolute path) | | `self::path` | Path relative to the current module (i.e., an explicitly relative path). | | `super::path` | Path relative to the parent of the current module | | `type::ident`, `<type as trait>::ident` | Associated constants, functions, and types | | `<type>::...` | Associated item for a type that cannot be directly named (e.g., `<&T>::...`, `<[T]>::...`, etc.) | | `trait::method(...)` | Disambiguating a method call by naming the trait that defines it | | `type::method(...)` | Disambiguating a method call by naming the type for which it’s defined | | `<type as trait>::method(...)` | Disambiguating a method call by naming the trait and type | Table B-4 shows symbols that appear in the context of using generic type parameters. Table B-4: Generics | Symbol | Explanation | | --- | --- | | `path<...>` | Specifies parameters to generic type in a type (e.g., `Vec<u8>`) | | `path::<...>`, `method::<...>` | Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., `"42".parse::<i32>()`) | | `fn ident<...> ...` | Define generic function | | `struct ident<...> ...` | Define generic structure | | `enum ident<...> ...` | Define generic enumeration | | `impl<...> ...` | Define generic implementation | | `for<...> type` | Higher-ranked lifetime bounds | | `type<ident=type>` | A generic type where one or more associated types have specific assignments (e.g., `Iterator<Item=T>`) | Table B-5 shows symbols that appear in the context of constraining generic type parameters with trait bounds. Table B-5: Trait Bound Constraints | Symbol | Explanation | | --- | --- | | `T: U` | Generic parameter `T` constrained to types that implement `U` | | `T: 'a` | Generic type `T` must outlive lifetime `'a` (meaning the type cannot transitively contain any references with lifetimes shorter than `'a`) | | `T: 'static` | Generic type `T` contains no borrowed references other than `'static` ones | | `'b: 'a` | Generic lifetime `'b` must outlive lifetime `'a` | | `T: ?Sized` | Allow generic type parameter to be a dynamically sized type | | `'a + trait`, `trait + trait` | Compound type constraint | Table B-6 shows symbols that appear in the context of calling or defining macros and specifying attributes on an item. Table B-6: Macros and Attributes | Symbol | Explanation | | --- | --- | | `#[meta]` | Outer attribute | | `#![meta]` | Inner attribute | | `$ident` | Macro substitution | | `$ident:kind` | Macro capture | | `$(…)…` | Macro repetition | | `ident!(...)`, `ident!{...}`, `ident![...]` | Macro invocation | Table B-7 shows symbols that create comments. Table B-7: Comments | Symbol | Explanation | | --- | --- | | `//` | Line comment | | `//!` | Inner line doc comment | | `///` | Outer line doc comment | | `/*...*/` | Block comment | | `/*!...*/` | Inner block doc comment | | `/**...*/` | Outer block doc comment | Table B-8 shows symbols that appear in the context of using tuples. Table B-8: Tuples | Symbol | Explanation | | --- | --- | | `()` | Empty tuple (aka unit), both literal and type | | `(expr)` | Parenthesized expression | | `(expr,)` | Single-element tuple expression | | `(type,)` | Single-element tuple type | | `(expr, ...)` | Tuple expression | | `(type, ...)` | Tuple type | | `expr(expr, ...)` | Function call expression; also used to initialize tuple `struct`s and tuple `enum` variants | | `expr.0`, `expr.1`, etc. | Tuple indexing | Table B-9 shows the contexts in which curly braces are used. Table B-9: Curly Brackets | Context | Explanation | | --- | --- | | `{...}` | Block expression | | `Type {...}` | `struct` literal | Table B-10 shows the contexts in which square brackets are used. Table B-10: Square Brackets | Context | Explanation | | --- | --- | | `[...]` | Array literal | | `[expr; len]` | Array literal containing `len` copies of `expr` | | `[type; len]` | Array type containing `len` instances of `type` | | `expr[expr]` | Collection indexing. Overloadable (`Index`, `IndexMut`) | | `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]` | Collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, or `RangeFull` as the “index” | rust Data Types Data Types ========== Every value in Rust is of a certain *data type*, which tells Rust what kind of data is being specified so it knows how to work with that data. We’ll look at two data type subsets: scalar and compound. Keep in mind that Rust is a *statically typed* language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. In cases when many types are possible, such as when we converted a `String` to a numeric type using `parse` in the [“Comparing the Guess to the Secret Number”](ch02-00-guessing-game-tutorial#comparing-the-guess-to-the-secret-number) section in Chapter 2, we must add a type annotation, like this: ``` #![allow(unused)] fn main() { let guess: u32 = "42".parse().expect("Not a number!"); } ``` If we don’t add the `: u32` type annotation above, Rust will display the following error, which means the compiler needs more information from us to know which type we want to use: ``` $ cargo build Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations) error[E0282]: type annotations needed --> src/main.rs:2:9 | 2 | let guess = "42".parse().expect("Not a number!"); | ^^^^^ consider giving `guess` a type For more information about this error, try `rustc --explain E0282`. error: could not compile `no_type_annotations` due to previous error ``` You’ll see different type annotations for other data types. ### Scalar Types A *scalar* type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. You may recognize these from other programming languages. Let’s jump into how they work in Rust. #### Integer Types An *integer* is a number without a fractional component. We used one integer type in Chapter 2, the `u32` type. This type declaration indicates that the value it’s associated with should be an unsigned integer (signed integer types start with `i`, instead of `u`) that takes up 32 bits of space. Table 3-1 shows the built-in integer types in Rust. We can use any of these variants to declare the type of an integer value. Table 3-1: Integer Types in Rust | Length | Signed | Unsigned | | --- | --- | --- | | 8-bit | `i8` | `u8` | | 16-bit | `i16` | `u16` | | 32-bit | `i32` | `u32` | | 64-bit | `i64` | `u64` | | 128-bit | `i128` | `u128` | | arch | `isize` | `usize` | Each variant can be either signed or unsigned and has an explicit size. *Signed* and *unsigned* refer to whether it’s possible for the number to be negative—in other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned). It’s like writing numbers on paper: when the sign matters, a number is shown with a plus sign or a minus sign; however, when it’s safe to assume the number is positive, it’s shown with no sign. Signed numbers are stored using [two’s complement](https://en.wikipedia.org/wiki/Two%27s_complement) representation. Each signed variant can store numbers from -(2n - 1) to 2n - 1 - 1 inclusive, where *n* is the number of bits that variant uses. So an `i8` can store numbers from -(27) to 27 - 1, which equals -128 to 127. Unsigned variants can store numbers from 0 to 2n - 1, so a `u8` can store numbers from 0 to 28 - 1, which equals 0 to 255. Additionally, the `isize` and `usize` types depend on the architecture of the computer your program is running on, which is denoted in the table as “arch”: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture. You can write integer literals in any of the forms shown in Table 3-2. Note that number literals that can be multiple numeric types allow a type suffix, such as `57u8`, to designate the type. Number literals can also use `_` as a visual separator to make the number easier to read, such as `1_000`, which will have the same value as if you had specified `1000`. Table 3-2: Integer Literals in Rust | Number literals | Example | | --- | --- | | Decimal | `98_222` | | Hex | `0xff` | | Octal | `0o77` | | Binary | `0b1111_0000` | | Byte (`u8` only) | `b'A'` | So how do you know which type of integer to use? If you’re unsure, Rust’s defaults are generally good places to start: integer types default to `i32`. The primary situation in which you’d use `isize` or `usize` is when indexing some sort of collection. > ##### Integer Overflow > > Let’s say you have a variable of type `u8` that can hold values between 0 and 255. If you try to change the variable to a value outside of that range, such as 256, *integer overflow* will occur, which can result in one of two behaviors. When you’re compiling in debug mode, Rust includes checks for integer overflow that cause your program to *panic* at runtime if this behavior occurs. Rust uses the term panicking when a program exits with an error; we’ll discuss panics in more depth in the [“Unrecoverable Errors with `panic!`”](ch09-01-unrecoverable-errors-with-panic) section in Chapter 9. > > When you’re compiling in release mode with the `--release` flag, Rust does *not* include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs *two’s complement wrapping*. In short, values greater than the maximum value the type can hold “wrap around” to the minimum of the values the type can hold. In the case of a `u8`, the value 256 becomes 0, the value 257 becomes 1, and so on. The program won’t panic, but the variable will have a value that probably isn’t what you were expecting it to have. Relying on integer overflow’s wrapping behavior is considered an error. > > To explicitly handle the possibility of overflow, you can use these families of methods provided by the standard library for primitive numeric types: > > * Wrap in all modes with the `wrapping_*` methods, such as `wrapping_add` > * Return the `None` value if there is overflow with the `checked_*` methods > * Return the value and a boolean indicating whether there was overflow with the `overflowing_*` methods > * Saturate at the value’s minimum or maximum values with `saturating_*` methods > > #### Floating-Point Types Rust also has two primitive types for *floating-point numbers*, which are numbers with decimal points. Rust’s floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively. The default type is `f64` because on modern CPUs it’s roughly the same speed as `f32` but is capable of more precision. All floating-point types are signed. Here’s an example that shows floating-point numbers in action: Filename: src/main.rs ``` fn main() { let x = 2.0; // f64 let y: f32 = 3.0; // f32 } ``` Floating-point numbers are represented according to the IEEE-754 standard. The `f32` type is a single-precision float, and `f64` has double precision. #### Numeric Operations Rust supports the basic mathematical operations you’d expect for all of the number types: addition, subtraction, multiplication, division, and remainder. Integer division rounds down to the nearest integer. The following code shows how you’d use each numeric operation in a `let` statement: Filename: src/main.rs ``` fn main() { // addition let sum = 5 + 10; // subtraction let difference = 95.5 - 4.3; // multiplication let product = 4 * 30; // division let quotient = 56.7 / 32.2; let floored = 2 / 3; // Results in 0 // remainder let remainder = 43 % 5; } ``` Each expression in these statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable. [Appendix B](appendix-02-operators) contains a list of all operators that Rust provides. #### The Boolean Type As in most other programming languages, a Boolean type in Rust has two possible values: `true` and `false`. Booleans are one byte in size. The Boolean type in Rust is specified using `bool`. For example: Filename: src/main.rs ``` fn main() { let t = true; let f: bool = false; // with explicit type annotation } ``` The main way to use Boolean values is through conditionals, such as an `if` expression. We’ll cover how `if` expressions work in Rust in the [“Control Flow”](ch03-05-control-flow#control-flow) section. #### The Character Type Rust’s `char` type is the language’s most primitive alphabetic type. Here’s some examples of declaring `char` values: Filename: src/main.rs ``` fn main() { let c = 'z'; let z: char = 'ℤ'; // with explicit type annotation let heart_eyed_cat = '😻'; } ``` Note that we specify `char` literals with single quotes, as opposed to string literals, which use double quotes. Rust’s `char` type is four bytes in size and represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emoji; and zero-width spaces are all valid `char` values in Rust. Unicode Scalar Values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF` inclusive. However, a “character” isn’t really a concept in Unicode, so your human intuition for what a “character” is may not match up with what a `char` is in Rust. We’ll discuss this topic in detail in [“Storing UTF-8 Encoded Text with Strings”](ch08-02-strings#storing-utf-8-encoded-text-with-strings) in Chapter 8. ### Compound Types *Compound types* can group multiple values into one type. Rust has two primitive compound types: tuples and arrays. #### The Tuple Type A tuple is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size. We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values in the tuple don’t have to be the same. We’ve added optional type annotations in this example: Filename: src/main.rs ``` fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); } ``` The variable `tup` binds to the entire tuple, because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this: Filename: src/main.rs ``` fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of y is: {y}"); } ``` This program first creates a tuple and binds it to the variable `tup`. It then uses a pattern with `let` to take `tup` and turn it into three separate variables, `x`, `y`, and `z`. This is called *destructuring*, because it breaks the single tuple into three parts. Finally, the program prints the value of `y`, which is `6.4`. We can also access a tuple element directly by using a period (`.`) followed by the index of the value we want to access. For example: Filename: src/main.rs ``` fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; } ``` This program creates the tuple `x` and then accesses each element of the tuple using their respective indices. As with most programming languages, the first index in a tuple is 0. The tuple without any values has a special name, *unit*. This value and its corresponding type are both written `()` and represent an empty value or an empty return type. Expressions implicitly return the unit value if they don’t return any other value. #### The Array Type Another way to have a collection of multiple values is with an *array*. Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length. We write the values in an array as a comma-separated list inside square brackets: Filename: src/main.rs ``` fn main() { let a = [1, 2, 3, 4, 5]; } ``` Arrays are useful when you want your data allocated on the stack rather than the heap (we will discuss the stack and the heap more in [Chapter 4](ch04-01-what-is-ownership#the-stack-and-the-heap)) or when you want to ensure you always have a fixed number of elements. An array isn’t as flexible as the vector type, though. A vector is a similar collection type provided by the standard library that *is* allowed to grow or shrink in size. If you’re unsure whether to use an array or a vector, chances are you should use a vector. [Chapter 8](ch08-01-vectors) discusses vectors in more detail. However, arrays are more useful when you know the number of elements will not need to change. For example, if you were using the names of the month in a program, you would probably use an array rather than a vector because you know it will always contain 12 elements: ``` #![allow(unused)] fn main() { let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; } ``` You write an array’s type using square brackets with the type of each element, a semicolon, and then the number of elements in the array, like so: ``` #![allow(unused)] fn main() { let a: [i32; 5] = [1, 2, 3, 4, 5]; } ``` Here, `i32` is the type of each element. After the semicolon, the number `5` indicates the array contains five elements. You can also initialize an array to contain the same value for each element by specifying the initial value, followed by a semicolon, and then the length of the array in square brackets, as shown here: ``` #![allow(unused)] fn main() { let a = [3; 5]; } ``` The array named `a` will contain `5` elements that will all be set to the value `3` initially. This is the same as writing `let a = [3, 3, 3, 3, 3];` but in a more concise way. ##### Accessing Array Elements An array is a single chunk of memory of a known, fixed size that can be allocated on the stack. You can access elements of an array using indexing, like this: Filename: src/main.rs ``` fn main() { let a = [1, 2, 3, 4, 5]; let first = a[0]; let second = a[1]; } ``` In this example, the variable named `first` will get the value `1`, because that is the value at index `[0]` in the array. The variable named `second` will get the value `2` from index `[1]` in the array. ##### Invalid Array Element Access Let’s see what happens if you try to access an element of an array that is past the end of the array. Say you run this code, similar to the guessing game in Chapter 2, to get an array index from the user: Filename: src/main.rs ``` use std::io; fn main() { let a = [1, 2, 3, 4, 5]; println!("Please enter an array index."); let mut index = String::new(); io::stdin() .read_line(&mut index) .expect("Failed to read line"); let index: usize = index .trim() .parse() .expect("Index entered was not a number"); let element = a[index]; println!("The value of the element at index {index} is: {element}"); } ``` This code compiles successfully. If you run this code using `cargo run` and enter 0, 1, 2, 3, or 4, the program will print out the corresponding value at that index in the array. If you instead enter a number past the end of the array, such as 10, you’ll see output like this: ``` thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` The program resulted in a *runtime* error at the point of using an invalid value in the indexing operation. The program exited with an error message and didn’t execute the final `println!` statement. When you attempt to access an element using indexing, Rust will check that the index you’ve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler can’t possibly know what value a user will enter when they run the code later. This is an example of Rust’s memory safety principles in action. In many low-level languages, this kind of check is not done, and when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing. Chapter 9 discusses more of Rust’s error handling and how you can write readable, safe code that neither panics nor allows invalid memory access.
programming_docs
rust None Installing Binaries with `cargo install` ---------------------------------------- The `cargo install` command allows you to install and use binary crates locally. This isn’t intended to replace system packages; it’s meant to be a convenient way for Rust developers to install tools that others have shared on [crates.io](https://crates.io/). Note that you can only install packages that have binary targets. A *binary target* is the runnable program that is created if the crate has a *src/main.rs* file or another file specified as a binary, as opposed to a library target that isn’t runnable on its own but is suitable for including within other programs. Usually, crates have information in the *README* file about whether a crate is a library, has a binary target, or both. All binaries installed with `cargo install` are stored in the installation root’s *bin* folder. If you installed Rust using *rustup.rs* and don’t have any custom configurations, this directory will be *$HOME/.cargo/bin*. Ensure that directory is in your `$PATH` to be able to run programs you’ve installed with `cargo install`. For example, in Chapter 12 we mentioned that there’s a Rust implementation of the `grep` tool called `ripgrep` for searching files. To install `ripgrep`, we can run the following: ``` $ cargo install ripgrep Updating crates.io index Downloaded ripgrep v11.0.2 Downloaded 1 crate (243.3 KB) in 0.88s Installing ripgrep v11.0.2 --snip-- Compiling ripgrep v11.0.2 Finished release [optimized + debuginfo] target(s) in 3m 10s Installing ~/.cargo/bin/rg Installed package `ripgrep v11.0.2` (executable `rg`) ``` The second-to-last line of the output shows the location and the name of the installed binary, which in the case of `ripgrep` is `rg`. As long as the installation directory is in your `$PATH`, as mentioned previously, you can then run `rg --help` and start using a faster, rustier tool for searching files! rust The Rust Programming Language The Rust Programming Language ============================= *by Steve Klabnik and Carol Nichols, with contributions from the Rust Community* This version of the text assumes you’re using Rust 1.62 (released 2022-06-30) or later. See the [“Installation” section of Chapter 1](ch01-01-installation) to install or update Rust. The HTML format is available online at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/index.html) and offline with installations of Rust made with `rustup`; run `rustup docs --book` to open. Several community [translations](appendix-06-translation) are also available. This text is available in [paperback and ebook format from No Starch Press](https://nostarch.com/rust). > **🚨 Want a more interactive learning experience? Try out a different version of the Rust Book, featuring: quizzes, highlighting, visualizations, and more**: <https://rust-book.cs.brown.edu> > > rust Validating References with Lifetimes Validating References with Lifetimes ==================================== Lifetimes are another kind of generic that we’ve already been using. Rather than ensuring that a type has the behavior we want, lifetimes ensure that references are valid as long as we need them to be. One detail we didn’t discuss in the [“References and Borrowing”](ch04-02-references-and-borrowing#references-and-borrowing) section in Chapter 4 is that every reference in Rust has a *lifetime*, which is the scope for which that reference is valid. Most of the time, lifetimes are implicit and inferred, just like most of the time, types are inferred. We only must annotate types when multiple types are possible. In a similar way, we must annotate lifetimes when the lifetimes of references could be related in a few different ways. Rust requires us to annotate the relationships using generic lifetime parameters to ensure the actual references used at runtime will definitely be valid. Annotating lifetimes is not even a concept most other programming languages have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in their entirety in this chapter, we’ll discuss common ways you might encounter lifetime syntax so you can get comfortable with the concept. ### Preventing Dangling References with Lifetimes The main aim of lifetimes is to prevent *dangling references*, which cause a program to reference data other than the data it’s intended to reference. Consider the program in Listing 10-16, which has an outer scope and an inner scope. ``` fn main() { let r; { let x = 5; r = &x; } println!("r: {}", r); } ``` Listing 10-16: An attempt to use a reference whose value has gone out of scope > Note: The examples in Listings 10-16, 10-17, and 10-23 declare variables without giving them an initial value, so the variable name exists in the outer scope. At first glance, this might appear to be in conflict with Rust’s having no null values. However, if we try to use a variable before giving it a value, we’ll get a compile-time error, which shows that Rust indeed does not allow null values. > > The outer scope declares a variable named `r` with no initial value, and the inner scope declares a variable named `x` with the initial value of 5. Inside the inner scope, we attempt to set the value of `r` as a reference to `x`. Then the inner scope ends, and we attempt to print the value in `r`. This code won’t compile because the value `r` is referring to has gone out of scope before we try to use it. Here is the error message: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0597]: `x` does not live long enough --> src/main.rs:6:13 | 6 | r = &x; | ^^ borrowed value does not live long enough 7 | } | - `x` dropped here while still borrowed 8 | 9 | println!("r: {}", r); | - borrow later used here For more information about this error, try `rustc --explain E0597`. error: could not compile `chapter10` due to previous error ``` The variable `x` doesn’t “live long enough.” The reason is that `x` will be out of scope when the inner scope ends on line 7. But `r` is still valid for the outer scope; because its scope is larger, we say that it “lives longer.” If Rust allowed this code to work, `r` would be referencing memory that was deallocated when `x` went out of scope, and anything we tried to do with `r` wouldn’t work correctly. So how does Rust determine that this code is invalid? It uses a borrow checker. ### The Borrow Checker The Rust compiler has a *borrow checker* that compares scopes to determine whether all borrows are valid. Listing 10-17 shows the same code as Listing 10-16 but with annotations showing the lifetimes of the variables. ``` fn main() { let r; // ---------+-- 'a // | { // | let x = 5; // -+-- 'b | r = &x; // | | } // -+ | // | println!("r: {}", r); // | } // ---------+ ``` Listing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b`, respectively Here, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x` with `'b`. As you can see, the inner `'b` block is much smaller than the outer `'a` lifetime block. At compile time, Rust compares the size of the two lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory with a lifetime of `'b`. The program is rejected because `'b` is shorter than `'a`: the subject of the reference doesn’t live as long as the reference. Listing 10-18 fixes the code so it doesn’t have a dangling reference and compiles without any errors. ``` fn main() { let x = 5; // ----------+-- 'b // | let r = &x; // --+-- 'a | // | | println!("r: {}", r); // | | // --+ | } // ----------+ ``` Listing 10-18: A valid reference because the data has a longer lifetime than the reference Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This means `r` can reference `x` because Rust knows that the reference in `r` will always be valid while `x` is valid. Now that you know where the lifetimes of references are and how Rust analyzes lifetimes to ensure references will always be valid, let’s explore generic lifetimes of parameters and return values in the context of functions. ### Generic Lifetimes in Functions We’ll write a function that returns the longer of two string slices. This function will take two string slices and return a single string slice. After we’ve implemented the `longest` function, the code in Listing 10-19 should print `The longest string is abcd`. Filename: src/main.rs ``` fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } ``` Listing 10-19: A `main` function that calls the `longest` function to find the longer of two string slices Note that we want the function to take string slices, which are references, rather than strings, because we don’t want the `longest` function to take ownership of its parameters. Refer to the [“String Slices as Parameters”](ch04-03-slices#string-slices-as-parameters) section in Chapter 4 for more discussion about why the parameters we use in Listing 10-19 are the ones we want. If we try to implement the `longest` function as shown in Listing 10-20, it won’t compile. Filename: src/main.rs ``` fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } ``` Listing 10-20: An implementation of the `longest` function that returns the longer of two string slices but does not yet compile Instead, we get the following error that talks about lifetimes: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0106]: missing lifetime specifier --> src/main.rs:9:33 | 9 | fn longest(x: &str, y: &str) -> &str { | ---- ---- ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y` help: consider introducing a named lifetime parameter | 9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { | ++++ ++ ++ ++ For more information about this error, try `rustc --explain E0106`. error: could not compile `chapter10` due to previous error ``` The help text reveals that the return type needs a generic lifetime parameter on it because Rust can’t tell whether the reference being returned refers to `x` or `y`. Actually, we don’t know either, because the `if` block in the body of this function returns a reference to `x` and the `else` block returns a reference to `y`! When we’re defining this function, we don’t know the concrete values that will be passed into this function, so we don’t know whether the `if` case or the `else` case will execute. We also don’t know the concrete lifetimes of the references that will be passed in, so we can’t look at the scopes as we did in Listings 10-17 and 10-18 to determine whether the reference we return will always be valid. The borrow checker can’t determine this either, because it doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the return value. To fix this error, we’ll add generic lifetime parameters that define the relationship between the references so the borrow checker can perform its analysis. ### Lifetime Annotation Syntax Lifetime annotations don’t change how long any of the references live. Rather, they describe the relationships of the lifetimes of multiple references to each other without affecting the lifetimes. Just as functions can accept any type when the signature specifies a generic type parameter, functions can accept references with any lifetime by specifying a generic lifetime parameter. Lifetime annotations have a slightly unusual syntax: the names of lifetime parameters must start with an apostrophe (`'`) and are usually all lowercase and very short, like generic types. Most people use the name `'a` for the first lifetime annotation. We place lifetime parameter annotations after the `&` of a reference, using a space to separate the annotation from the reference’s type. Here are some examples: a reference to an `i32` without a lifetime parameter, a reference to an `i32` that has a lifetime parameter named `'a`, and a mutable reference to an `i32` that also has the lifetime `'a`. ``` &i32 // a reference &'a i32 // a reference with an explicit lifetime &'a mut i32 // a mutable reference with an explicit lifetime ``` One lifetime annotation by itself doesn’t have much meaning, because the annotations are meant to tell Rust how generic lifetime parameters of multiple references relate to each other. Let’s examine how the lifetime annotations relate to each other in the context of the `longest` function. ### Lifetime Annotations in Function Signatures To use lifetime annotations in function signatures, we need to declare the generic *lifetime* parameters inside angle brackets between the function name and the parameter list, just as we did with generic *type* parameters. We want the signature to express the following constraint: the returned reference will be valid as long as both the parameters are valid. This is the relationship between lifetimes of the parameters and the return value. We’ll name the lifetime `'a` and then add it to each reference, as shown in Listing 10-21. Filename: src/main.rs ``` fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } ``` Listing 10-21: The `longest` function definition specifying that all the references in the signature must have the same lifetime `'a` This code should compile and produce the result we want when we use it with the `main` function in Listing 10-19. The function signature now tells Rust that for some lifetime `'a`, the function takes two parameters, both of which are string slices that live at least as long as lifetime `'a`. The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime `'a`. In practice, it means that the lifetime of the reference returned by the `longest` function is the same as the smaller of the lifetimes of the values referred to by the function arguments. These relationships are what we want Rust to use when analyzing this code. Remember, when we specify the lifetime parameters in this function signature, we’re not changing the lifetimes of any values passed in or returned. Rather, we’re specifying that the borrow checker should reject any values that don’t adhere to these constraints. Note that the `longest` function doesn’t need to know exactly how long `x` and `y` will live, only that some scope can be substituted for `'a` that will satisfy this signature. When annotating lifetimes in functions, the annotations go in the function signature, not in the function body. The lifetime annotations become part of the contract of the function, much like the types in the signature. Having function signatures contain the lifetime contract means the analysis the Rust compiler does can be simpler. If there’s a problem with the way a function is annotated or the way it is called, the compiler errors can point to the part of our code and the constraints more precisely. If, instead, the Rust compiler made more inferences about what we intended the relationships of the lifetimes to be, the compiler might only be able to point to a use of our code many steps away from the cause of the problem. When we pass concrete references to `longest`, the concrete lifetime that is substituted for `'a` is the part of the scope of `x` that overlaps with the scope of `y`. In other words, the generic lifetime `'a` will get the concrete lifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because we’ve annotated the returned reference with the same lifetime parameter `'a`, the returned reference will also be valid for the length of the smaller of the lifetimes of `x` and `y`. Let’s look at how the lifetime annotations restrict the `longest` function by passing in references that have different concrete lifetimes. Listing 10-22 is a straightforward example. Filename: src/main.rs ``` fn main() { let string1 = String::from("long string is long"); { let string2 = String::from("xyz"); let result = longest(string1.as_str(), string2.as_str()); println!("The longest string is {}", result); } } fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } ``` Listing 10-22: Using the `longest` function with references to `String` values that have different concrete lifetimes In this example, `string1` is valid until the end of the outer scope, `string2` is valid until the end of the inner scope, and `result` references something that is valid until the end of the inner scope. Run this code, and you’ll see that the borrow checker approves; it will compile and print `The longest string is long string is long`. Next, let’s try an example that shows that the lifetime of the reference in `result` must be the smaller lifetime of the two arguments. We’ll move the declaration of the `result` variable outside the inner scope but leave the assignment of the value to the `result` variable inside the scope with `string2`. Then we’ll move the `println!` that uses `result` to outside the inner scope, after the inner scope has ended. The code in Listing 10-23 will not compile. Filename: src/main.rs ``` fn main() { let string1 = String::from("long string is long"); let result; { let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); } println!("The longest string is {}", result); } fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } ``` Listing 10-23: Attempting to use `result` after `string2` has gone out of scope When we try to compile this code, we get this error: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0597]: `string2` does not live long enough --> src/main.rs:6:44 | 6 | result = longest(string1.as_str(), string2.as_str()); | ^^^^^^^^^^^^^^^^ borrowed value does not live long enough 7 | } | - `string2` dropped here while still borrowed 8 | println!("The longest string is {}", result); | ------ borrow later used here For more information about this error, try `rustc --explain E0597`. error: could not compile `chapter10` due to previous error ``` The error shows that for `result` to be valid for the `println!` statement, `string2` would need to be valid until the end of the outer scope. Rust knows this because we annotated the lifetimes of the function parameters and return values using the same lifetime parameter `'a`. As humans, we can look at this code and see that `string1` is longer than `string2` and therefore `result` will contain a reference to `string1`. Because `string1` has not gone out of scope yet, a reference to `string1` will still be valid for the `println!` statement. However, the compiler can’t see that the reference is valid in this case. We’ve told Rust that the lifetime of the reference returned by the `longest` function is the same as the smaller of the lifetimes of the references passed in. Therefore, the borrow checker disallows the code in Listing 10-23 as possibly having an invalid reference. Try designing more experiments that vary the values and lifetimes of the references passed in to the `longest` function and how the returned reference is used. Make hypotheses about whether or not your experiments will pass the borrow checker before you compile; then check to see if you’re right! ### Thinking in Terms of Lifetimes The way in which you need to specify lifetime parameters depends on what your function is doing. For example, if we changed the implementation of the `longest` function to always return the first parameter rather than the longest string slice, we wouldn’t need to specify a lifetime on the `y` parameter. The following code will compile: Filename: src/main.rs ``` fn main() { let string1 = String::from("abcd"); let string2 = "efghijklmnopqrstuvwxyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest<'a>(x: &'a str, y: &str) -> &'a str { x } ``` We’ve specified a lifetime parameter `'a` for the parameter `x` and the return type, but not for the parameter `y`, because the lifetime of `y` does not have any relationship with the lifetime of `x` or the return value. When returning a reference from a function, the lifetime parameter for the return type needs to match the lifetime parameter for one of the parameters. If the reference returned does *not* refer to one of the parameters, it must refer to a value created within this function. However, this would be a dangling reference because the value will go out of scope at the end of the function. Consider this attempted implementation of the `longest` function that won’t compile: Filename: src/main.rs ``` fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest<'a>(x: &str, y: &str) -> &'a str { let result = String::from("really long string"); result.as_str() } ``` Here, even though we’ve specified a lifetime parameter `'a` for the return type, this implementation will fail to compile because the return value lifetime is not related to the lifetime of the parameters at all. Here is the error message we get: ``` $ cargo run Compiling chapter10 v0.1.0 (file:///projects/chapter10) error[E0515]: cannot return reference to local variable `result` --> src/main.rs:11:5 | 11 | result.as_str() | ^^^^^^^^^^^^^^^ returns a reference to data owned by the current function For more information about this error, try `rustc --explain E0515`. error: could not compile `chapter10` due to previous error ``` The problem is that `result` goes out of scope and gets cleaned up at the end of the `longest` function. We’re also trying to return a reference to `result` from the function. There is no way we can specify lifetime parameters that would change the dangling reference, and Rust won’t let us create a dangling reference. In this case, the best fix would be to return an owned data type rather than a reference so the calling function is then responsible for cleaning up the value. Ultimately, lifetime syntax is about connecting the lifetimes of various parameters and return values of functions. Once they’re connected, Rust has enough information to allow memory-safe operations and disallow operations that would create dangling pointers or otherwise violate memory safety. ### Lifetime Annotations in Struct Definitions So far, the structs we’ve defined all hold owned types. We can define structs to hold references, but in that case we would need to add a lifetime annotation on every reference in the struct’s definition. Listing 10-24 has a struct named `ImportantExcerpt` that holds a string slice. Filename: src/main.rs ``` struct ImportantExcerpt<'a> { part: &'a str, } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; } ``` Listing 10-24: A struct that holds a reference, requiring a lifetime annotation This struct has the single field `part` that holds a string slice, which is a reference. As with generic data types, we declare the name of the generic lifetime parameter inside angle brackets after the name of the struct so we can use the lifetime parameter in the body of the struct definition. This annotation means an instance of `ImportantExcerpt` can’t outlive the reference it holds in its `part` field. The `main` function here creates an instance of the `ImportantExcerpt` struct that holds a reference to the first sentence of the `String` owned by the variable `novel`. The data in `novel` exists before the `ImportantExcerpt` instance is created. In addition, `novel` doesn’t go out of scope until after the `ImportantExcerpt` goes out of scope, so the reference in the `ImportantExcerpt` instance is valid. ### Lifetime Elision You’ve learned that every reference has a lifetime and that you need to specify lifetime parameters for functions or structs that use references. However, in Chapter 4 we had a function in Listing 4-9, shown again in Listing 10-25, that compiled without lifetime annotations. Filename: src/lib.rs ``` fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // first_word works on slices of `String`s let word = first_word(&my_string[..]); let my_string_literal = "hello world"; // first_word works on slices of string literals let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); } ``` Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references The reason this function compiles without lifetime annotations is historical: in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because every reference needed an explicit lifetime. At that time, the function signature would have been written like this: ``` fn first_word<'a>(s: &'a str) -> &'a str { ``` After writing a lot of Rust code, the Rust team found that Rust programmers were entering the same lifetime annotations over and over in particular situations. These situations were predictable and followed a few deterministic patterns. The developers programmed these patterns into the compiler’s code so the borrow checker could infer the lifetimes in these situations and wouldn’t need explicit annotations. This piece of Rust history is relevant because it’s possible that more deterministic patterns will emerge and be added to the compiler. In the future, even fewer lifetime annotations might be required. The patterns programmed into Rust’s analysis of references are called the *lifetime elision rules*. These aren’t rules for programmers to follow; they’re a set of particular cases that the compiler will consider, and if your code fits these cases, you don’t need to write the lifetimes explicitly. The elision rules don’t provide full inference. If Rust deterministically applies the rules but there is still ambiguity as to what lifetimes the references have, the compiler won’t guess what the lifetime of the remaining references should be. Instead of guessing, the compiler will give you an error that you can resolve by adding the lifetime annotations. Lifetimes on function or method parameters are called *input lifetimes*, and lifetimes on return values are called *output lifetimes*. The compiler uses three rules to figure out the lifetimes of the references when there aren’t explicit annotations. The first rule applies to input lifetimes, and the second and third rules apply to output lifetimes. If the compiler gets to the end of the three rules and there are still references for which it can’t figure out lifetimes, the compiler will stop with an error. These rules apply to `fn` definitions as well as `impl` blocks. The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. In other words, a function with one parameter gets one lifetime parameter: `fn foo<'a>(x: &'a i32)`; a function with two parameters gets two separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32, y: &'b i32)`; and so on. The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32) -> &'a i32`. The third rule is that, if there are multiple input lifetime parameters, but one of them is `&self` or `&mut self` because this is a method, the lifetime of `self` is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary. Let’s pretend we’re the compiler. We’ll apply these rules to figure out the lifetimes of the references in the signature of the `first_word` function in Listing 10-25. The signature starts without any lifetimes associated with the references: ``` fn first_word(s: &str) -> &str { ``` Then the compiler applies the first rule, which specifies that each parameter gets its own lifetime. We’ll call it `'a` as usual, so now the signature is this: ``` fn first_word<'a>(s: &'a str) -> &str { ``` The second rule applies because there is exactly one input lifetime. The second rule specifies that the lifetime of the one input parameter gets assigned to the output lifetime, so the signature is now this: ``` fn first_word<'a>(s: &'a str) -> &'a str { ``` Now all the references in this function signature have lifetimes, and the compiler can continue its analysis without needing the programmer to annotate the lifetimes in this function signature. Let’s look at another example, this time using the `longest` function that had no lifetime parameters when we started working with it in Listing 10-20: ``` fn longest(x: &str, y: &str) -> &str { ``` Let’s apply the first rule: each parameter gets its own lifetime. This time we have two parameters instead of one, so we have two lifetimes: ``` fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str { ``` You can see that the second rule doesn’t apply because there is more than one input lifetime. The third rule doesn’t apply either, because `longest` is a function rather than a method, so none of the parameters are `self`. After working through all three rules, we still haven’t figured out what the return type’s lifetime is. This is why we got an error trying to compile the code in Listing 10-20: the compiler worked through the lifetime elision rules but still couldn’t figure out all the lifetimes of the references in the signature. Because the third rule really only applies in method signatures, we’ll look at lifetimes in that context next to see why the third rule means we don’t have to annotate lifetimes in method signatures very often. ### Lifetime Annotations in Method Definitions When we implement methods on a struct with lifetimes, we use the same syntax as that of generic type parameters shown in Listing 10-11. Where we declare and use the lifetime parameters depends on whether they’re related to the struct fields or the method parameters and return values. Lifetime names for struct fields always need to be declared after the `impl` keyword and then used after the struct’s name, because those lifetimes are part of the struct’s type. In method signatures inside the `impl` block, references might be tied to the lifetime of references in the struct’s fields, or they might be independent. In addition, the lifetime elision rules often make it so that lifetime annotations aren’t necessary in method signatures. Let’s look at some examples using the struct named `ImportantExcerpt` that we defined in Listing 10-24. First, we’ll use a method named `level` whose only parameter is a reference to `self` and whose return value is an `i32`, which is not a reference to anything: ``` struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 } } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; } ``` The lifetime parameter declaration after `impl` and its use after the type name are required, but we’re not required to annotate the lifetime of the reference to `self` because of the first elision rule. Here is an example where the third lifetime elision rule applies: ``` struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 } } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; } ``` There are two input lifetimes, so Rust applies the first lifetime elision rule and gives both `&self` and `announcement` their own lifetimes. Then, because one of the parameters is `&self`, the return type gets the lifetime of `&self`, and all lifetimes have been accounted for. ### The Static Lifetime One special lifetime we need to discuss is `'static`, which denotes that the affected reference *can* live for the entire duration of the program. All string literals have the `'static` lifetime, which we can annotate as follows: ``` #![allow(unused)] fn main() { let s: &'static str = "I have a static lifetime."; } ``` The text of this string is stored directly in the program’s binary, which is always available. Therefore, the lifetime of all string literals is `'static`. You might see suggestions to use the `'static` lifetime in error messages. But before specifying `'static` as the lifetime for a reference, think about whether the reference you have actually lives the entire lifetime of your program or not, and whether you want it to. Most of the time, an error message suggesting the `'static` lifetime results from attempting to create a dangling reference or a mismatch of the available lifetimes. In such cases, the solution is fixing those problems, not specifying the `'static` lifetime. Generic Type Parameters, Trait Bounds, and Lifetimes Together ------------------------------------------------------------- Let’s briefly look at the syntax of specifying generic type parameters, trait bounds, and lifetimes all in one function! ``` fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest_with_an_announcement( string1.as_str(), string2, "Today is someone's birthday!", ); println!("The longest string is {}", result); } use std::fmt::Display; fn longest_with_an_announcement<'a, T>( x: &'a str, y: &'a str, ann: T, ) -> &'a str where T: Display, { println!("Announcement! {}", ann); if x.len() > y.len() { x } else { y } } ``` This is the `longest` function from Listing 10-21 that returns the longer of two string slices. But now it has an extra parameter named `ann` of the generic type `T`, which can be filled in by any type that implements the `Display` trait as specified by the `where` clause. This extra parameter will be printed using `{}`, which is why the `Display` trait bound is necessary. Because lifetimes are a type of generic, the declarations of the lifetime parameter `'a` and the generic type parameter `T` go in the same list inside the angle brackets after the function name. Summary ------- We covered a lot in this chapter! Now that you know about generic type parameters, traits and trait bounds, and generic lifetime parameters, you’re ready to write code without repetition that works in many different situations. Generic type parameters let you apply the code to different types. Traits and trait bounds ensure that even though the types are generic, they’ll have the behavior the code needs. You learned how to use lifetime annotations to ensure that this flexible code won’t have any dangling references. And all of this analysis happens at compile time, which doesn’t affect runtime performance! Believe it or not, there is much more to learn on the topics we discussed in this chapter: Chapter 17 discusses trait objects, which are another way to use traits. There are also more complex scenarios involving lifetime annotations that you will only need in very advanced scenarios; for those, you should read the [Rust Reference](../reference/index). But next, you’ll learn how to write tests in Rust so you can make sure your code is working the way it should.
programming_docs
rust Unsafe Rust Unsafe Rust =========== All the code we’ve discussed so far has had Rust’s memory safety guarantees enforced at compile time. However, Rust has a second language hidden inside it that doesn’t enforce these memory safety guarantees: it’s called *unsafe Rust* and works just like regular Rust, but gives us extra superpowers. Unsafe Rust exists because, by nature, static analysis is conservative. When the compiler tries to determine whether or not code upholds the guarantees, it’s better for it to reject some valid programs than to accept some invalid programs. Although the code *might* be okay, if the Rust compiler doesn’t have enough information to be confident, it will reject the code. In these cases, you can use unsafe code to tell the compiler, “Trust me, I know what I’m doing.” Be warned, however, that you use unsafe Rust at your own risk: if you use unsafe code incorrectly, problems can occur due to memory unsafety, such as null pointer dereferencing. Another reason Rust has an unsafe alter ego is that the underlying computer hardware is inherently unsafe. If Rust didn’t let you do unsafe operations, you couldn’t do certain tasks. Rust needs to allow you to do low-level systems programming, such as directly interacting with the operating system or even writing your own operating system. Working with low-level systems programming is one of the goals of the language. Let’s explore what we can do with unsafe Rust and how to do it. ### Unsafe Superpowers To switch to unsafe Rust, use the `unsafe` keyword and then start a new block that holds the unsafe code. You can take five actions in unsafe Rust that you can’t in safe Rust, which we call *unsafe superpowers*. Those superpowers include the ability to: * Dereference a raw pointer * Call an unsafe function or method * Access or modify a mutable static variable * Implement an unsafe trait * Access fields of `union`s It’s important to understand that `unsafe` doesn’t turn off the borrow checker or disable any other of Rust’s safety checks: if you use a reference in unsafe code, it will still be checked. The `unsafe` keyword only gives you access to these five features that are then not checked by the compiler for memory safety. You’ll still get some degree of safety inside of an unsafe block. In addition, `unsafe` does not mean the code inside the block is necessarily dangerous or that it will definitely have memory safety problems: the intent is that as the programmer, you’ll ensure the code inside an `unsafe` block will access memory in a valid way. People are fallible, and mistakes will happen, but by requiring these five unsafe operations to be inside blocks annotated with `unsafe` you’ll know that any errors related to memory safety must be within an `unsafe` block. Keep `unsafe` blocks small; you’ll be thankful later when you investigate memory bugs. To isolate unsafe code as much as possible, it’s best to enclose unsafe code within a safe abstraction and provide a safe API, which we’ll discuss later in the chapter when we examine unsafe functions and methods. Parts of the standard library are implemented as safe abstractions over unsafe code that has been audited. Wrapping unsafe code in a safe abstraction prevents uses of `unsafe` from leaking out into all the places that you or your users might want to use the functionality implemented with `unsafe` code, because using a safe abstraction is safe. Let’s look at each of the five unsafe superpowers in turn. We’ll also look at some abstractions that provide a safe interface to unsafe code. ### Dereferencing a Raw Pointer In Chapter 4, in the [“Dangling References”](ch04-02-references-and-borrowing#dangling-references) section, we mentioned that the compiler ensures references are always valid. Unsafe Rust has two new types called *raw pointers* that are similar to references. As with references, raw pointers can be immutable or mutable and are written as `*const T` and `*mut T`, respectively. The asterisk isn’t the dereference operator; it’s part of the type name. In the context of raw pointers, *immutable* means that the pointer can’t be directly assigned to after being dereferenced. Different from references and smart pointers, raw pointers: * Are allowed to ignore the borrowing rules by having both immutable and mutable pointers or multiple mutable pointers to the same location * Aren’t guaranteed to point to valid memory * Are allowed to be null * Don’t implement any automatic cleanup By opting out of having Rust enforce these guarantees, you can give up guaranteed safety in exchange for greater performance or the ability to interface with another language or hardware where Rust’s guarantees don’t apply. Listing 19-1 shows how to create an immutable and a mutable raw pointer from references. ``` fn main() { let mut num = 5; let r1 = &num as *const i32; let r2 = &mut num as *mut i32; } ``` Listing 19-1: Creating raw pointers from references Notice that we don’t include the `unsafe` keyword in this code. We can create raw pointers in safe code; we just can’t dereference raw pointers outside an unsafe block, as you’ll see in a bit. We’ve created raw pointers by using `as` to cast an immutable and a mutable reference into their corresponding raw pointer types. Because we created them directly from references guaranteed to be valid, we know these particular raw pointers are valid, but we can’t make that assumption about just any raw pointer. To demonstrate this, next we’ll create a raw pointer whose validity we can’t be so certain of. Listing 19-2 shows how to create a raw pointer to an arbitrary location in memory. Trying to use arbitrary memory is undefined: there might be data at that address or there might not, the compiler might optimize the code so there is no memory access, or the program might error with a segmentation fault. Usually, there is no good reason to write code like this, but it is possible. ``` fn main() { let address = 0x012345usize; let r = address as *const i32; } ``` Listing 19-2: Creating a raw pointer to an arbitrary memory address Recall that we can create raw pointers in safe code, but we can’t *dereference* raw pointers and read the data being pointed to. In Listing 19-3, we use the dereference operator `*` on a raw pointer that requires an `unsafe` block. ``` fn main() { let mut num = 5; let r1 = &num as *const i32; let r2 = &mut num as *mut i32; unsafe { println!("r1 is: {}", *r1); println!("r2 is: {}", *r2); } } ``` Listing 19-3: Dereferencing raw pointers within an `unsafe` block Creating a pointer does no harm; it’s only when we try to access the value that it points at that we might end up dealing with an invalid value. Note also that in Listing 19-1 and 19-3, we created `*const i32` and `*mut i32` raw pointers that both pointed to the same memory location, where `num` is stored. If we instead tried to create an immutable and a mutable reference to `num`, the code would not have compiled because Rust’s ownership rules don’t allow a mutable reference at the same time as any immutable references. With raw pointers, we can create a mutable pointer and an immutable pointer to the same location and change data through the mutable pointer, potentially creating a data race. Be careful! With all of these dangers, why would you ever use raw pointers? One major use case is when interfacing with C code, as you’ll see in the next section, [“Calling an Unsafe Function or Method.”](#calling-an-unsafe-function-or-method) Another case is when building up safe abstractions that the borrow checker doesn’t understand. We’ll introduce unsafe functions and then look at an example of a safe abstraction that uses unsafe code. ### Calling an Unsafe Function or Method The second type of operation you can perform in an unsafe block is calling unsafe functions. Unsafe functions and methods look exactly like regular functions and methods, but they have an extra `unsafe` before the rest of the definition. The `unsafe` keyword in this context indicates the function has requirements we need to uphold when we call this function, because Rust can’t guarantee we’ve met these requirements. By calling an unsafe function within an `unsafe` block, we’re saying that we’ve read this function’s documentation and take responsibility for upholding the function’s contracts. Here is an unsafe function named `dangerous` that doesn’t do anything in its body: ``` fn main() { unsafe fn dangerous() {} unsafe { dangerous(); } } ``` We must call the `dangerous` function within a separate `unsafe` block. If we try to call `dangerous` without the `unsafe` block, we’ll get an error: ``` $ cargo run Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) error[E0133]: call to unsafe function is unsafe and requires unsafe function or block --> src/main.rs:4:5 | 4 | dangerous(); | ^^^^^^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behavior For more information about this error, try `rustc --explain E0133`. error: could not compile `unsafe-example` due to previous error ``` With the `unsafe` block, we’re asserting to Rust that we’ve read the function’s documentation, we understand how to use it properly, and we’ve verified that we’re fulfilling the contract of the function. Bodies of unsafe functions are effectively `unsafe` blocks, so to perform other unsafe operations within an unsafe function, we don’t need to add another `unsafe` block. #### Creating a Safe Abstraction over Unsafe Code Just because a function contains unsafe code doesn’t mean we need to mark the entire function as unsafe. In fact, wrapping unsafe code in a safe function is a common abstraction. As an example, let’s study the `split_at_mut` function from the standard library, which requires some unsafe code. We’ll explore how we might implement it. This safe method is defined on mutable slices: it takes one slice and makes it two by splitting the slice at the index given as an argument. Listing 19-4 shows how to use `split_at_mut`. ``` fn main() { let mut v = vec![1, 2, 3, 4, 5, 6]; let r = &mut v[..]; let (a, b) = r.split_at_mut(3); assert_eq!(a, &mut [1, 2, 3]); assert_eq!(b, &mut [4, 5, 6]); } ``` Listing 19-4: Using the safe `split_at_mut` function We can’t implement this function using only safe Rust. An attempt might look something like Listing 19-5, which won’t compile. For simplicity, we’ll implement `split_at_mut` as a function rather than a method and only for slices of `i32` values rather than for a generic type `T`. ``` fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { let len = values.len(); assert!(mid <= len); (&mut values[..mid], &mut values[mid..]) } fn main() { let mut vector = vec![1, 2, 3, 4, 5, 6]; let (left, right) = split_at_mut(&mut vector, 3); } ``` Listing 19-5: An attempted implementation of `split_at_mut` using only safe Rust This function first gets the total length of the slice. Then it asserts that the index given as a parameter is within the slice by checking whether it’s less than or equal to the length. The assertion means that if we pass an index that is greater than the length to split the slice at, the function will panic before it attempts to use that index. Then we return two mutable slices in a tuple: one from the start of the original slice to the `mid` index and another from `mid` to the end of the slice. When we try to compile the code in Listing 19-5, we’ll get an error. ``` $ cargo run Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) error[E0499]: cannot borrow `*values` as mutable more than once at a time --> src/main.rs:6:31 | 1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { | - let's call the lifetime of this reference `'1` ... 6 | (&mut values[..mid], &mut values[mid..]) | --------------------------^^^^^^-------- | | | | | | | second mutable borrow occurs here | | first mutable borrow occurs here | returning this value requires that `*values` is borrowed for `'1` For more information about this error, try `rustc --explain E0499`. error: could not compile `unsafe-example` due to previous error ``` Rust’s borrow checker can’t understand that we’re borrowing different parts of the slice; it only knows that we’re borrowing from the same slice twice. Borrowing different parts of a slice is fundamentally okay because the two slices aren’t overlapping, but Rust isn’t smart enough to know this. When we know code is okay, but Rust doesn’t, it’s time to reach for unsafe code. Listing 19-6 shows how to use an `unsafe` block, a raw pointer, and some calls to unsafe functions to make the implementation of `split_at_mut` work. ``` use std::slice; fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { let len = values.len(); let ptr = values.as_mut_ptr(); assert!(mid <= len); unsafe { ( slice::from_raw_parts_mut(ptr, mid), slice::from_raw_parts_mut(ptr.add(mid), len - mid), ) } } fn main() { let mut vector = vec![1, 2, 3, 4, 5, 6]; let (left, right) = split_at_mut(&mut vector, 3); } ``` Listing 19-6: Using unsafe code in the implementation of the `split_at_mut` function Recall from [“The Slice Type”](ch04-03-slices#the-slice-type) section in Chapter 4 that slices are a pointer to some data and the length of the slice. We use the `len` method to get the length of a slice and the `as_mut_ptr` method to access the raw pointer of a slice. In this case, because we have a mutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type `*mut i32`, which we’ve stored in the variable `ptr`. We keep the assertion that the `mid` index is within the slice. Then we get to the unsafe code: the `slice::from_raw_parts_mut` function takes a raw pointer and a length, and it creates a slice. We use this function to create a slice that starts from `ptr` and is `mid` items long. Then we call the `add` method on `ptr` with `mid` as an argument to get a raw pointer that starts at `mid`, and we create a slice using that pointer and the remaining number of items after `mid` as the length. The function `slice::from_raw_parts_mut` is unsafe because it takes a raw pointer and must trust that this pointer is valid. The `add` method on raw pointers is also unsafe, because it must trust that the offset location is also a valid pointer. Therefore, we had to put an `unsafe` block around our calls to `slice::from_raw_parts_mut` and `add` so we could call them. By looking at the code and by adding the assertion that `mid` must be less than or equal to `len`, we can tell that all the raw pointers used within the `unsafe` block will be valid pointers to data within the slice. This is an acceptable and appropriate use of `unsafe`. Note that we don’t need to mark the resulting `split_at_mut` function as `unsafe`, and we can call this function from safe Rust. We’ve created a safe abstraction to the unsafe code with an implementation of the function that uses `unsafe` code in a safe way, because it creates only valid pointers from the data this function has access to. In contrast, the use of `slice::from_raw_parts_mut` in Listing 19-7 would likely crash when the slice is used. This code takes an arbitrary memory location and creates a slice 10,000 items long. ``` fn main() { use std::slice; let address = 0x01234usize; let r = address as *mut i32; let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) }; } ``` Listing 19-7: Creating a slice from an arbitrary memory location We don’t own the memory at this arbitrary location, and there is no guarantee that the slice this code creates contains valid `i32` values. Attempting to use `values` as though it’s a valid slice results in undefined behavior. #### Using `extern` Functions to Call External Code Sometimes, your Rust code might need to interact with code written in another language. For this, Rust has the keyword `extern` that facilitates the creation and use of a *Foreign Function Interface (FFI)*. An FFI is a way for a programming language to define functions and enable a different (foreign) programming language to call those functions. Listing 19-8 demonstrates how to set up an integration with the `abs` function from the C standard library. Functions declared within `extern` blocks are always unsafe to call from Rust code. The reason is that other languages don’t enforce Rust’s rules and guarantees, and Rust can’t check them, so responsibility falls on the programmer to ensure safety. Filename: src/main.rs ``` extern "C" { fn abs(input: i32) -> i32; } fn main() { unsafe { println!("Absolute value of -3 according to C: {}", abs(-3)); } } ``` Listing 19-8: Declaring and calling an `extern` function defined in another language Within the `extern "C"` block, we list the names and signatures of external functions from another language we want to call. The `"C"` part defines which *application binary interface (ABI)* the external function uses: the ABI defines how to call the function at the assembly level. The `"C"` ABI is the most common and follows the C programming language’s ABI. > #### Calling Rust Functions from Other Languages > > We can also use `extern` to create an interface that allows other languages to call Rust functions. Instead of creating a whole `extern` block, we add the `extern` keyword and specify the ABI to use just before the `fn` keyword for the relevant function. We also need to add a `#[no_mangle]` annotation to tell the Rust compiler not to mangle the name of this function. *Mangling* is when a compiler changes the name we’ve given a function to a different name that contains more information for other parts of the compilation process to consume but is less human readable. Every programming language compiler mangles names slightly differently, so for a Rust function to be nameable by other languages, we must disable the Rust compiler’s name mangling. > > In the following example, we make the `call_from_c` function accessible from C code, after it’s compiled to a shared library and linked from C: > > > ``` > #![allow(unused)] > fn main() { > #[no_mangle] > pub extern "C" fn call_from_c() { > println!("Just called a Rust function from C!"); > } > } > > ``` > This usage of `extern` does not require `unsafe`. > > ### Accessing or Modifying a Mutable Static Variable In this book, we’ve not yet talked about *global variables*, which Rust does support but can be problematic with Rust’s ownership rules. If two threads are accessing the same mutable global variable, it can cause a data race. In Rust, global variables are called *static* variables. Listing 19-9 shows an example declaration and use of a static variable with a string slice as a value. Filename: src/main.rs ``` static HELLO_WORLD: &str = "Hello, world!"; fn main() { println!("name is: {}", HELLO_WORLD); } ``` Listing 19-9: Defining and using an immutable static variable Static variables are similar to constants, which we discussed in the [“Differences Between Variables and Constants”](ch03-01-variables-and-mutability#constants) section in Chapter 3. The names of static variables are in `SCREAMING_SNAKE_CASE` by convention. Static variables can only store references with the `'static` lifetime, which means the Rust compiler can figure out the lifetime and we aren’t required to annotate it explicitly. Accessing an immutable static variable is safe. A subtle difference between constants and immutable static variables is that values in a static variable have a fixed address in memory. Using the value will always access the same data. Constants, on the other hand, are allowed to duplicate their data whenever they’re used. Another difference is that static variables can be mutable. Accessing and modifying mutable static variables is *unsafe*. Listing 19-10 shows how to declare, access, and modify a mutable static variable named `COUNTER`. Filename: src/main.rs ``` static mut COUNTER: u32 = 0; fn add_to_count(inc: u32) { unsafe { COUNTER += inc; } } fn main() { add_to_count(3); unsafe { println!("COUNTER: {}", COUNTER); } } ``` Listing 19-10: Reading from or writing to a mutable static variable is unsafe As with regular variables, we specify mutability using the `mut` keyword. Any code that reads or writes from `COUNTER` must be within an `unsafe` block. This code compiles and prints `COUNTER: 3` as we would expect because it’s single threaded. Having multiple threads access `COUNTER` would likely result in data races. With mutable data that is globally accessible, it’s difficult to ensure there are no data races, which is why Rust considers mutable static variables to be unsafe. Where possible, it’s preferable to use the concurrency techniques and thread-safe smart pointers we discussed in Chapter 16 so the compiler checks that data accessed from different threads is done safely. ### Implementing an Unsafe Trait We can use `unsafe` to implement an unsafe trait. A trait is unsafe when at least one of its methods has some invariant that the compiler can’t verify. We declare that a trait is `unsafe` by adding the `unsafe` keyword before `trait` and marking the implementation of the trait as `unsafe` too, as shown in Listing 19-11. ``` unsafe trait Foo { // methods go here } unsafe impl Foo for i32 { // method implementations go here } fn main() {} ``` Listing 19-11: Defining and implementing an unsafe trait By using `unsafe impl`, we’re promising that we’ll uphold the invariants that the compiler can’t verify. As an example, recall the `Sync` and `Send` marker traits we discussed in the [“Extensible Concurrency with the `Sync` and `Send` Traits”](ch16-04-extensible-concurrency-sync-and-send#extensible-concurrency-with-the-sync-and-send-traits) section in Chapter 16: the compiler implements these traits automatically if our types are composed entirely of `Send` and `Sync` types. If we implement a type that contains a type that is not `Send` or `Sync`, such as raw pointers, and we want to mark that type as `Send` or `Sync`, we must use `unsafe`. Rust can’t verify that our type upholds the guarantees that it can be safely sent across threads or accessed from multiple threads; therefore, we need to do those checks manually and indicate as such with `unsafe`. ### Accessing Fields of a Union The final action that works only with `unsafe` is accessing fields of a *union*. A `union` is similar to a `struct`, but only one declared field is used in a particular instance at one time. Unions are primarily used to interface with unions in C code. Accessing union fields is unsafe because Rust can’t guarantee the type of the data currently being stored in the union instance. You can learn more about unions in [the Rust Reference](../reference/items/unions). ### When to Use Unsafe Code Using `unsafe` to take one of the five actions (superpowers) just discussed isn’t wrong or even frowned upon. But it is trickier to get `unsafe` code correct because the compiler can’t help uphold memory safety. When you have a reason to use `unsafe` code, you can do so, and having the explicit `unsafe` annotation makes it easier to track down the source of problems when they occur.
programming_docs
rust To panic! or Not to panic! To `panic!` or Not to `panic!` ============================== So how do you decide when you should call `panic!` and when you should return `Result`? When code panics, there’s no way to recover. You could call `panic!` for any error situation, whether there’s a possible way to recover or not, but then you’re making the decision that a situation is unrecoverable on behalf of the calling code. When you choose to return a `Result` value, you give the calling code options. The calling code could choose to attempt to recover in a way that’s appropriate for its situation, or it could decide that an `Err` value in this case is unrecoverable, so it can call `panic!` and turn your recoverable error into an unrecoverable one. Therefore, returning `Result` is a good default choice when you’re defining a function that might fail. In situations such as examples, prototype code, and tests, it’s more appropriate to write code that panics instead of returning a `Result`. Let’s explore why, then discuss situations in which the compiler can’t tell that failure is impossible, but you as a human can. The chapter will conclude with some general guidelines on how to decide whether to panic in library code. ### Examples, Prototype Code, and Tests When you’re writing an example to illustrate some concept, also including robust error-handling code can make the example less clear. In examples, it’s understood that a call to a method like `unwrap` that could panic is meant as a placeholder for the way you’d want your application to handle errors, which can differ based on what the rest of your code is doing. Similarly, the `unwrap` and `expect` methods are very handy when prototyping, before you’re ready to decide how to handle errors. They leave clear markers in your code for when you’re ready to make your program more robust. If a method call fails in a test, you’d want the whole test to fail, even if that method isn’t the functionality under test. Because `panic!` is how a test is marked as a failure, calling `unwrap` or `expect` is exactly what should happen. ### Cases in Which You Have More Information Than the Compiler It would also be appropriate to call `unwrap` or `expect` when you have some other logic that ensures the `Result` will have an `Ok` value, but the logic isn’t something the compiler understands. You’ll still have a `Result` value that you need to handle: whatever operation you’re calling still has the possibility of failing in general, even though it’s logically impossible in your particular situation. If you can ensure by manually inspecting the code that you’ll never have an `Err` variant, it’s perfectly acceptable to call `unwrap`, and even better to document the reason you think you’ll never have an `Err` variant in the `expect` text. Here’s an example: ``` fn main() { use std::net::IpAddr; let home: IpAddr = "127.0.0.1" .parse() .expect("Hardcoded IP address should be valid"); } ``` We’re creating an `IpAddr` instance by parsing a hardcoded string. We can see that `127.0.0.1` is a valid IP address, so it’s acceptable to use `expect` here. However, having a hardcoded, valid string doesn’t change the return type of the `parse` method: we still get a `Result` value, and the compiler will still make us handle the `Result` as if the `Err` variant is a possibility because the compiler isn’t smart enough to see that this string is always a valid IP address. If the IP address string came from a user rather than being hardcoded into the program and therefore *did* have a possibility of failure, we’d definitely want to handle the `Result` in a more robust way instead. Mentioning the assumption that this IP address is hardcoded will prompt us to change `expect` to better error handling code if in the future, we need to get the IP address from some other source instead. ### Guidelines for Error Handling It’s advisable to have your code panic when it’s possible that your code could end up in a bad state. In this context, a *bad state* is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to your code—plus one or more of the following: * The bad state is something that is unexpected, as opposed to something that will likely happen occasionally, like a user entering data in the wrong format. * Your code after this point needs to rely on not being in this bad state, rather than checking for the problem at every step. * There’s not a good way to encode this information in the types you use. We’ll work through an example of what we mean in the [“Encoding States and Behavior as Types”](ch17-03-oo-design-patterns#encoding-states-and-behavior-as-types) section of Chapter 17. If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call `panic!` and alert the person using your library to the bug in their code so they can fix it during development. Similarly, `panic!` is often appropriate if you’re calling external code that is out of your control and it returns an invalid state that you have no way of fixing. However, when failure is expected, it’s more appropriate to return a `Result` than to make a `panic!` call. Examples include a parser being given malformed data or an HTTP request returning a status that indicates you have hit a rate limit. In these cases, returning a `Result` indicates that failure is an expected possibility that the calling code must decide how to handle. When your code performs an operation that could put a user at risk if it’s called using invalid values, your code should verify the values are valid first and panic if the values aren’t valid. This is mostly for safety reasons: attempting to operate on invalid data can expose your code to vulnerabilities. This is the main reason the standard library will call `panic!` if you attempt an out-of-bounds memory access: trying to access memory that doesn’t belong to the current data structure is a common security problem. Functions often have *contracts*: their behavior is only guaranteed if the inputs meet particular requirements. Panicking when the contract is violated makes sense because a contract violation always indicates a caller-side bug and it’s not a kind of error you want the calling code to have to explicitly handle. In fact, there’s no reasonable way for calling code to recover; the calling *programmers* need to fix the code. Contracts for a function, especially when a violation will cause a panic, should be explained in the API documentation for the function. However, having lots of error checks in all of your functions would be verbose and annoying. Fortunately, you can use Rust’s type system (and thus the type checking done by the compiler) to do many of the checks for you. If your function has a particular type as a parameter, you can proceed with your code’s logic knowing that the compiler has already ensured you have a valid value. For example, if you have a type rather than an `Option`, your program expects to have *something* rather than *nothing*. Your code then doesn’t have to handle two cases for the `Some` and `None` variants: it will only have one case for definitely having a value. Code trying to pass nothing to your function won’t even compile, so your function doesn’t have to check for that case at runtime. Another example is using an unsigned integer type such as `u32`, which ensures the parameter is never negative. ### Creating Custom Types for Validation Let’s take the idea of using Rust’s type system to ensure we have a valid value one step further and look at creating a custom type for validation. Recall the guessing game in Chapter 2 in which our code asked the user to guess a number between 1 and 100. We never validated that the user’s guess was between those numbers before checking it against our secret number; we only validated that the guess was positive. In this case, the consequences were not very dire: our output of “Too high” or “Too low” would still be correct. But it would be a useful enhancement to guide the user toward valid guesses and have different behavior when a user guesses a number that’s out of range versus when a user types, for example, letters instead. One way to do this would be to parse the guess as an `i32` instead of only a `u32` to allow potentially negative numbers, and then add a check for the number being in range, like so: ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); loop { // --snip-- println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; if guess < 1 || guess > 100 { println!("The secret number will be between 1 and 100."); continue; } match guess.cmp(&secret_number) { // --snip-- Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` The `if` expression checks whether our value is out of range, tells the user about the problem, and calls `continue` to start the next iteration of the loop and ask for another guess. After the `if` expression, we can proceed with the comparisons between `guess` and the secret number knowing that `guess` is between 1 and 100. However, this is not an ideal solution: if it was absolutely critical that the program only operated on values between 1 and 100, and it had many functions with this requirement, having a check like this in every function would be tedious (and might impact performance). Instead, we can make a new type and put the validations in a function to create an instance of the type rather than repeating the validations everywhere. That way, it’s safe for functions to use the new type in their signatures and confidently use the values they receive. Listing 9-13 shows one way to define a `Guess` type that will only create an instance of `Guess` if the `new` function receives a value between 1 and 100. ``` #![allow(unused)] fn main() { pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } pub fn value(&self) -> i32 { self.value } } } ``` Listing 9-13: A `Guess` type that will only continue with values between 1 and 100 First, we define a struct named `Guess` that has a field named `value` that holds an `i32`. This is where the number will be stored. Then we implement an associated function named `new` on `Guess` that creates instances of `Guess` values. The `new` function is defined to have one parameter named `value` of type `i32` and to return a `Guess`. The code in the body of the `new` function tests `value` to make sure it’s between 1 and 100. If `value` doesn’t pass this test, we make a `panic!` call, which will alert the programmer who is writing the calling code that they have a bug they need to fix, because creating a `Guess` with a `value` outside this range would violate the contract that `Guess::new` is relying on. The conditions in which `Guess::new` might panic should be discussed in its public-facing API documentation; we’ll cover documentation conventions indicating the possibility of a `panic!` in the API documentation that you create in Chapter 14. If `value` does pass the test, we create a new `Guess` with its `value` field set to the `value` parameter and return the `Guess`. Next, we implement a method named `value` that borrows `self`, doesn’t have any other parameters, and returns an `i32`. This kind of method is sometimes called a *getter*, because its purpose is to get some data from its fields and return it. This public method is necessary because the `value` field of the `Guess` struct is private. It’s important that the `value` field be private so code using the `Guess` struct is not allowed to set `value` directly: code outside the module *must* use the `Guess::new` function to create an instance of `Guess`, thereby ensuring there’s no way for a `Guess` to have a `value` that hasn’t been checked by the conditions in the `Guess::new` function. A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a `Guess` rather than an `i32` and wouldn’t need to do any additional checks in its body. Summary ------- Rust’s error handling features are designed to help you write more robust code. The `panic!` macro signals that your program is in a state it can’t handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The `Result` enum uses Rust’s type system to indicate that operations might fail in a way that your code could recover from. You can use `Result` to tell code that calls your code that it needs to handle potential success or failure as well. Using `panic!` and `Result` in the appropriate situations will make your code more reliable in the face of inevitable problems. Now that you’ve seen useful ways that the standard library uses generics with the `Option` and `Result` enums, we’ll talk about how generics work and how you can use them in your code. rust Appendix Appendix ======== The following sections contain reference material you may find useful in your Rust journey. rust Functional Language Features: Iterators and Closures Functional Language Features: Iterators and Closures ==================================================== Rust’s design has taken inspiration from many existing languages and techniques, and one significant influence is *functional programming*. Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth. In this chapter, we won’t debate the issue of what functional programming is or isn’t but will instead discuss some features of Rust that are similar to features in many languages often referred to as functional. More specifically, we’ll cover: * *Closures*, a function-like construct you can store in a variable * *Iterators*, a way of processing a series of elements * How to use closures and iterators to improve the I/O project in Chapter 12 * The performance of closures and iterators (Spoiler alert: they’re faster than you might think!) We’ve already covered some other Rust features, such as pattern matching and enums, that are also influenced by the functional style. Because mastering closures and iterators is an important part of writing idiomatic, fast Rust code, we’ll devote this entire chapter to them. rust References and Borrowing References and Borrowing ======================== The issue with the tuple code in Listing 4-5 is that we have to return the `String` to the calling function so we can still use the `String` after the call to `calculate_length`, because the `String` was moved into `calculate_length`. Instead, we can provide a reference to the `String` value. A *reference* is like a pointer in that it’s an address we can follow to access the data stored at that address; that data is owned by some other variable. Unlike a pointer, a reference is guaranteed to point to a valid value of a particular type for the life of that reference. Here is how you would define and use a `calculate_length` function that has a reference to an object as a parameter instead of taking ownership of the value: Filename: src/main.rs ``` fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len() } ``` First, notice that all the tuple code in the variable declaration and the function return value is gone. Second, note that we pass `&s1` into `calculate_length` and, in its definition, we take `&String` rather than `String`. These ampersands represent *references*, and they allow you to refer to some value without taking ownership of it. Figure 4-5 depicts this concept. Figure 4-5: A diagram of `&String s` pointing at `String s1` > Note: The opposite of referencing by using `&` is *dereferencing*, which is accomplished with the dereference operator, `*`. We’ll see some uses of the dereference operator in Chapter 8 and discuss details of dereferencing in Chapter 15. > > Let’s take a closer look at the function call here: ``` fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len() } ``` The `&s1` syntax lets us create a reference that *refers* to the value of `s1` but does not own it. Because it does not own it, the value it points to will not be dropped when the reference stops being used. Likewise, the signature of the function uses `&` to indicate that the type of the parameter `s` is a reference. Let’s add some explanatory annotations: ``` fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { // s is a reference to a String s.len() } // Here, s goes out of scope. But because it does not have ownership of what // it refers to, it is not dropped. ``` The scope in which the variable `s` is valid is the same as any function parameter’s scope, but the value pointed to by the reference is not dropped when `s` stops being used because `s` doesn’t have ownership. When functions have references as parameters instead of the actual values, we won’t need to return the values in order to give back ownership, because we never had ownership. We call the action of creating a reference *borrowing*. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. You don’t own it. So what happens if we try to modify something we’re borrowing? Try the code in Listing 4-6. Spoiler alert: it doesn’t work! Filename: src/main.rs ``` fn main() { let s = String::from("hello"); change(&s); } fn change(some_string: &String) { some_string.push_str(", world"); } ``` Listing 4-6: Attempting to modify a borrowed value Here’s the error: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference --> src/main.rs:8:5 | 7 | fn change(some_string: &String) { | ------- help: consider changing this to be a mutable reference: `&mut String` 8 | some_string.push_str(", world"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable For more information about this error, try `rustc --explain E0596`. error: could not compile `ownership` due to previous error ``` Just as variables are immutable by default, so are references. We’re not allowed to modify something we have a reference to. ### Mutable References We can fix the code from Listing 4-6 to allow us to modify a borrowed value with just a few small tweaks that use, instead, a *mutable reference*: Filename: src/main.rs ``` fn main() { let mut s = String::from("hello"); change(&mut s); } fn change(some_string: &mut String) { some_string.push_str(", world"); } ``` First, we change `s` to be `mut`. Then we create a mutable reference with `&mut s` where we call the `change` function, and update the function signature to accept a mutable reference with `some_string: &mut String`. This makes it very clear that the `change` function will mutate the value it borrows. Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references to that value. This code that attempts to create two mutable references to `s` will fail: Filename: src/main.rs ``` fn main() { let mut s = String::from("hello"); let r1 = &mut s; let r2 = &mut s; println!("{}, {}", r1, r2); } ``` Here’s the error: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0499]: cannot borrow `s` as mutable more than once at a time --> src/main.rs:5:14 | 4 | let r1 = &mut s; | ------ first mutable borrow occurs here 5 | let r2 = &mut s; | ^^^^^^ second mutable borrow occurs here 6 | 7 | println!("{}, {}", r1, r2); | -- first borrow later used here For more information about this error, try `rustc --explain E0499`. error: could not compile `ownership` due to previous error ``` This error says that this code is invalid because we cannot borrow `s` as mutable more than once at a time. The first mutable borrow is in `r1` and must last until it’s used in the `println!`, but between the creation of that mutable reference and its usage, we tried to create another mutable reference in `r2` that borrows the same data as `r1`. The restriction preventing multiple mutable references to the same data at the same time allows for mutation but in a very controlled fashion. It’s something that new Rustaceans struggle with, because most languages let you mutate whenever you’d like. The benefit of having this restriction is that Rust can prevent data races at compile time. A *data race* is similar to a race condition and happens when these three behaviors occur: * Two or more pointers access the same data at the same time. * At least one of the pointers is being used to write to the data. * There’s no mechanism being used to synchronize access to the data. Data races cause undefined behavior and can be difficult to diagnose and fix when you’re trying to track them down at runtime; Rust prevents this problem by refusing to compile code with data races! As always, we can use curly brackets to create a new scope, allowing for multiple mutable references, just not *simultaneous* ones: ``` fn main() { let mut s = String::from("hello"); { let r1 = &mut s; } // r1 goes out of scope here, so we can make a new reference with no problems. let r2 = &mut s; } ``` Rust enforces a similar rule for combining mutable and immutable references. This code results in an error: ``` fn main() { let mut s = String::from("hello"); let r1 = &s; // no problem let r2 = &s; // no problem let r3 = &mut s; // BIG PROBLEM println!("{}, {}, and {}", r1, r2, r3); } ``` Here’s the error: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable --> src/main.rs:6:14 | 4 | let r1 = &s; // no problem | -- immutable borrow occurs here 5 | let r2 = &s; // no problem 6 | let r3 = &mut s; // BIG PROBLEM | ^^^^^^ mutable borrow occurs here 7 | 8 | println!("{}, {}, and {}", r1, r2, r3); | -- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. error: could not compile `ownership` due to previous error ``` Whew! We *also* cannot have a mutable reference while we have an immutable one to the same value. Users of an immutable reference don’t expect the value to suddenly change out from under them! However, multiple immutable references are allowed because no one who is just reading the data has the ability to affect anyone else’s reading of the data. Note that a reference’s scope starts from where it is introduced and continues through the last time that reference is used. For instance, this code will compile because the last usage of the immutable references, the `println!`, occurs before the mutable reference is introduced: ``` fn main() { let mut s = String::from("hello"); let r1 = &s; // no problem let r2 = &s; // no problem println!("{} and {}", r1, r2); // variables r1 and r2 will not be used after this point let r3 = &mut s; // no problem println!("{}", r3); } ``` The scopes of the immutable references `r1` and `r2` end after the `println!` where they are last used, which is before the mutable reference `r3` is created. These scopes don’t overlap, so this code is allowed. The ability of the compiler to tell that a reference is no longer being used at a point before the end of the scope is called *Non-Lexical Lifetimes* (NLL for short), and you can read more about it in [The Edition Guide](https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/non-lexical-lifetimes.html). Even though borrowing errors may be frustrating at times, remember that it’s the Rust compiler pointing out a potential bug early (at compile time rather than at runtime) and showing you exactly where the problem is. Then you don’t have to track down why your data isn’t what you thought it was. ### Dangling References In languages with pointers, it’s easy to erroneously create a *dangling pointer*--a pointer that references a location in memory that may have been given to someone else--by freeing some memory while preserving a pointer to that memory. In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does. Let’s try to create a dangling reference to see how Rust prevents them with a compile-time error: Filename: src/main.rs ``` fn main() { let reference_to_nothing = dangle(); } fn dangle() -> &String { let s = String::from("hello"); &s } ``` Here’s the error: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0106]: missing lifetime specifier --> src/main.rs:5:16 | 5 | fn dangle() -> &String { | ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from help: consider using the `'static` lifetime | 5 | fn dangle() -> &'static String { | ~~~~~~~~ For more information about this error, try `rustc --explain E0106`. error: could not compile `ownership` due to previous error ``` This error message refers to a feature we haven’t covered yet: lifetimes. We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard the parts about lifetimes, the message does contain the key to why this code is a problem: ``` this function's return type contains a borrowed value, but there is no value for it to be borrowed from ``` Let’s take a closer look at exactly what’s happening at each stage of our `dangle` code: Filename: src/main.rs ``` fn main() { let reference_to_nothing = dangle(); } fn dangle() -> &String { // dangle returns a reference to a String let s = String::from("hello"); // s is a new String &s // we return a reference to the String, s } // Here, s goes out of scope, and is dropped. Its memory goes away. // Danger! ``` Because `s` is created inside `dangle`, when the code of `dangle` is finished, `s` will be deallocated. But we tried to return a reference to it. That means this reference would be pointing to an invalid `String`. That’s no good! Rust won’t let us do this. The solution here is to return the `String` directly: ``` fn main() { let string = no_dangle(); } fn no_dangle() -> String { let s = String::from("hello"); s } ``` This works without any problems. Ownership is moved out, and nothing is deallocated. ### The Rules of References Let’s recap what we’ve discussed about references: * At any given time, you can have *either* one mutable reference *or* any number of immutable references. * References must always be valid. Next, we’ll look at a different kind of reference: slices.
programming_docs
rust Extensible Concurrency with the Sync and Send Traits Extensible Concurrency with the `Sync` and `Send` Traits ======================================================== Interestingly, the Rust language has *very* few concurrency features. Almost every concurrency feature we’ve talked about so far in this chapter has been part of the standard library, not the language. Your options for handling concurrency are not limited to the language or the standard library; you can write your own concurrency features or use those written by others. However, two concurrency concepts are embedded in the language: the `std::marker` traits `Sync` and `Send`. ### Allowing Transference of Ownership Between Threads with `Send` The `Send` marker trait indicates that ownership of values of the type implementing `Send` can be transferred between threads. Almost every Rust type is `Send`, but there are some exceptions, including `Rc<T>`: this cannot be `Send` because if you cloned an `Rc<T>` value and tried to transfer ownership of the clone to another thread, both threads might update the reference count at the same time. For this reason, `Rc<T>` is implemented for use in single-threaded situations where you don’t want to pay the thread-safe performance penalty. Therefore, Rust’s type system and trait bounds ensure that you can never accidentally send an `Rc<T>` value across threads unsafely. When we tried to do this in Listing 16-14, we got the error `the trait Send is not implemented for Rc<Mutex<i32>>`. When we switched to `Arc<T>`, which is `Send`, the code compiled. Any type composed entirely of `Send` types is automatically marked as `Send` as well. Almost all primitive types are `Send`, aside from raw pointers, which we’ll discuss in Chapter 19. ### Allowing Access from Multiple Threads with `Sync` The `Sync` marker trait indicates that it is safe for the type implementing `Sync` to be referenced from multiple threads. In other words, any type `T` is `Sync` if `&T` (an immutable reference to `T`) is `Send`, meaning the reference can be sent safely to another thread. Similar to `Send`, primitive types are `Sync`, and types composed entirely of types that are `Sync` are also `Sync`. The smart pointer `Rc<T>` is also not `Sync` for the same reasons that it’s not `Send`. The `RefCell<T>` type (which we talked about in Chapter 15) and the family of related `Cell<T>` types are not `Sync`. The implementation of borrow checking that `RefCell<T>` does at runtime is not thread-safe. The smart pointer `Mutex<T>` is `Sync` and can be used to share access with multiple threads as you saw in the [“Sharing a `Mutex<T>` Between Multiple Threads”](ch16-03-shared-state#sharing-a-mutext-between-multiple-threads) section. ### Implementing `Send` and `Sync` Manually Is Unsafe Because types that are made up of `Send` and `Sync` traits are automatically also `Send` and `Sync`, we don’t have to implement those traits manually. As marker traits, they don’t even have any methods to implement. They’re just useful for enforcing invariants related to concurrency. Manually implementing these traits involves implementing unsafe Rust code. We’ll talk about using unsafe Rust code in Chapter 19; for now, the important information is that building new concurrent types not made up of `Send` and `Sync` parts requires careful thought to uphold the safety guarantees. [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/index.html) has more information about these guarantees and how to uphold them. Summary ------- This isn’t the last you’ll see of concurrency in this book: the project in Chapter 20 will use the concepts in this chapter in a more realistic situation than the smaller examples discussed here. As mentioned earlier, because very little of how Rust handles concurrency is part of the language, many concurrency solutions are implemented as crates. These evolve more quickly than the standard library, so be sure to search online for the current, state-of-the-art crates to use in multithreaded situations. The Rust standard library provides channels for message passing and smart pointer types, such as `Mutex<T>` and `Arc<T>`, that are safe to use in concurrent contexts. The type system and the borrow checker ensure that the code using these solutions won’t end up with data races or invalid references. Once you get your code to compile, you can rest assured that it will happily run on multiple threads without the kinds of hard-to-track-down bugs common in other languages. Concurrent programming is no longer a concept to be afraid of: go forth and make your programs concurrent, fearlessly! Next, we’ll talk about idiomatic ways to model problems and structure solutions as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms relate to those you might be familiar with from object-oriented programming. rust Unrecoverable Errors with panic! Unrecoverable Errors with `panic!` ================================== Sometimes, bad things happen in your code, and there’s nothing you can do about it. In these cases, Rust has the `panic!` macro. There are two ways to cause a panic in practice: by taking an action that causes our code to panic (such as accessing an array past the end) or by explicitly calling the `panic!` macro. In both cases, we cause a panic in our program. By default, these panics will print a failure message, unwind, clean up the stack, and quit. Via an environment variable, you can also have Rust display the call stack when a panic occurs to make it easier to track down the source of the panic. > ### Unwinding the Stack or Aborting in Response to a Panic > > By default, when a panic occurs, the program starts *unwinding*, which means Rust walks back up the stack and cleans up the data from each function it encounters. However, this walking back and cleanup is a lot of work. Rust, therefore, allows you to choose the alternative of immediately *aborting*, which ends the program without cleaning up. > > Memory that the program was using will then need to be cleaned up by the operating system. If in your project you need to make the resulting binary as small as possible, you can switch from unwinding to aborting upon a panic by adding `panic = 'abort'` to the appropriate `[profile]` sections in your *Cargo.toml* file. For example, if you want to abort on panic in release mode, add this: > > > ``` > [profile.release] > panic = 'abort' > > ``` > Let’s try calling `panic!` in a simple program: Filename: src/main.rs ``` fn main() { panic!("crash and burn"); } ``` When you run the program, you’ll see something like this: ``` $ cargo run Compiling panic v0.1.0 (file:///projects/panic) Finished dev [unoptimized + debuginfo] target(s) in 0.25s Running `target/debug/panic` thread 'main' panicked at 'crash and burn', src/main.rs:2:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` The call to `panic!` causes the error message contained in the last two lines. The first line shows our panic message and the place in our source code where the panic occurred: *src/main.rs:2:5* indicates that it’s the second line, fifth character of our *src/main.rs* file. In this case, the line indicated is part of our code, and if we go to that line, we see the `panic!` macro call. In other cases, the `panic!` call might be in code that our code calls, and the filename and line number reported by the error message will be someone else’s code where the `panic!` macro is called, not the line of our code that eventually led to the `panic!` call. We can use the backtrace of the functions the `panic!` call came from to figure out the part of our code that is causing the problem. We’ll discuss backtraces in more detail next. ### Using a `panic!` Backtrace Let’s look at another example to see what it’s like when a `panic!` call comes from a library because of a bug in our code instead of from our code calling the macro directly. Listing 9-1 has some code that attempts to access an index in a vector beyond the range of valid indexes. Filename: src/main.rs ``` fn main() { let v = vec![1, 2, 3]; v[99]; } ``` Listing 9-1: Attempting to access an element beyond the end of a vector, which will cause a call to `panic!` Here, we’re attempting to access the 100th element of our vector (which is at index 99 because indexing starts at zero), but the vector has only 3 elements. In this situation, Rust will panic. Using `[]` is supposed to return an element, but if you pass an invalid index, there’s no element that Rust could return here that would be correct. In C, attempting to read beyond the end of a data structure is undefined behavior. You might get whatever is at the location in memory that would correspond to that element in the data structure, even though the memory doesn’t belong to that structure. This is called a *buffer overread* and can lead to security vulnerabilities if an attacker is able to manipulate the index in such a way as to read data they shouldn’t be allowed to that is stored after the data structure. To protect your program from this sort of vulnerability, if you try to read an element at an index that doesn’t exist, Rust will stop execution and refuse to continue. Let’s try it and see: ``` $ cargo run Compiling panic v0.1.0 (file:///projects/panic) Finished dev [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/panic` thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` This error points at line 4 of our `main.rs` where we attempt to access index 99. The next note line tells us that we can set the `RUST_BACKTRACE` environment variable to get a backtrace of exactly what happened to cause the error. A *backtrace* is a list of all the functions that have been called to get to this point. Backtraces in Rust work as they do in other languages: the key to reading the backtrace is to start from the top and read until you see files you wrote. That’s the spot where the problem originated. The lines above that spot are code that your code has called; the lines below are code that called your code. These before-and-after lines might include core Rust code, standard library code, or crates that you’re using. Let’s try getting a backtrace by setting the `RUST_BACKTRACE` environment variable to any value except 0. Listing 9-2 shows output similar to what you’ll see. ``` $ RUST_BACKTRACE=1 cargo run thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5 stack backtrace: 0: rust_begin_unwind at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/std/src/panicking.rs:483 1: core::panicking::panic_fmt at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:85 2: core::panicking::panic_bounds_check at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:62 3: <usize as core::slice::index::SliceIndex<[T]>>::index at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:255 4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:15 5: <alloc::vec::Vec<T> as core::ops::index::Index<I>>::index at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/alloc/src/vec.rs:1982 6: panic::main at ./src/main.rs:4 7: core::ops::function::FnOnce::call_once at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/ops/function.rs:227 note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. ``` Listing 9-2: The backtrace generated by a call to `panic!` displayed when the environment variable `RUST_BACKTRACE` is set That’s a lot of output! The exact output you see might be different depending on your operating system and Rust version. In order to get backtraces with this information, debug symbols must be enabled. Debug symbols are enabled by default when using `cargo build` or `cargo run` without the `--release` flag, as we have here. In the output in Listing 9-2, line 6 of the backtrace points to the line in our project that’s causing the problem: line 4 of *src/main.rs*. If we don’t want our program to panic, we should start our investigation at the location pointed to by the first line mentioning a file we wrote. In Listing 9-1, where we deliberately wrote code that would panic, the way to fix the panic is to not request an element beyond the range of the vector indexes. When your code panics in the future, you’ll need to figure out what action the code is taking with what values to cause the panic and what the code should do instead. We’ll come back to `panic!` and when we should and should not use `panic!` to handle error conditions in the [“To `panic!` or Not to `panic!`”](ch09-03-to-panic-or-not-to-panic#to-panic-or-not-to-panic) section later in this chapter. Next, we’ll look at how to recover from an error using `Result`. rust Comparing Performance: Loops vs. Iterators Comparing Performance: Loops vs. Iterators ========================================== To determine whether to use loops or iterators, you need to know which implementation is faster: the version of the `search` function with an explicit `for` loop or the version with iterators. We ran a benchmark by loading the entire contents of *The Adventures of Sherlock Holmes* by Sir Arthur Conan Doyle into a `String` and looking for the word *the* in the contents. Here are the results of the benchmark on the version of `search` using the `for` loop and the version using iterators: ``` test bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700) test bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200) ``` The iterator version was slightly faster! We won’t explain the benchmark code here, because the point is not to prove that the two versions are equivalent but to get a general sense of how these two implementations compare performance-wise. For a more comprehensive benchmark, you should check using various texts of various sizes as the `contents`, different words and words of different lengths as the `query`, and all kinds of other variations. The point is this: iterators, although a high-level abstraction, get compiled down to roughly the same code as if you’d written the lower-level code yourself. Iterators are one of Rust’s *zero-cost abstractions*, by which we mean using the abstraction imposes no additional runtime overhead. This is analogous to how Bjarne Stroustrup, the original designer and implementor of C++, defines *zero-overhead* in “Foundations of C++” (2012): > In general, C++ implementations obey the zero-overhead principle: What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better. > > As another example, the following code is taken from an audio decoder. The decoding algorithm uses the linear prediction mathematical operation to estimate future values based on a linear function of the previous samples. This code uses an iterator chain to do some math on three variables in scope: a `buffer` slice of data, an array of 12 `coefficients`, and an amount by which to shift data in `qlp_shift`. We’ve declared the variables within this example but not given them any values; although this code doesn’t have much meaning outside of its context, it’s still a concise, real-world example of how Rust translates high-level ideas to low-level code. ``` let buffer: &mut [i32]; let coefficients: [i64; 12]; let qlp_shift: i16; for i in 12..buffer.len() { let prediction = coefficients.iter() .zip(&buffer[i - 12..i]) .map(|(&c, &s)| c * s as i64) .sum::<i64>() >> qlp_shift; let delta = buffer[i]; buffer[i] = prediction as i32 + delta; } ``` To calculate the value of `prediction`, this code iterates through each of the 12 values in `coefficients` and uses the `zip` method to pair the coefficient values with the previous 12 values in `buffer`. Then, for each pair, we multiply the values together, sum all the results, and shift the bits in the sum `qlp_shift` bits to the right. Calculations in applications like audio decoders often prioritize performance most highly. Here, we’re creating an iterator, using two adaptors, and then consuming the value. What assembly code would this Rust code compile to? Well, as of this writing, it compiles down to the same assembly you’d write by hand. There’s no loop at all corresponding to the iteration over the values in `coefficients`: Rust knows that there are 12 iterations, so it “unrolls” the loop. *Unrolling* is an optimization that removes the overhead of the loop controlling code and instead generates repetitive code for each iteration of the loop. All of the coefficients get stored in registers, which means accessing the values is very fast. There are no bounds checks on the array access at runtime. All these optimizations that Rust is able to apply make the resulting code extremely efficient. Now that you know this, you can use iterators and closures without fear! They make code seem like it’s higher level but don’t impose a runtime performance penalty for doing so. Summary ------- Closures and iterators are Rust features inspired by functional programming language ideas. They contribute to Rust’s capability to clearly express high-level ideas at low-level performance. The implementations of closures and iterators are such that runtime performance is not affected. This is part of Rust’s goal to strive to provide zero-cost abstractions. Now that we’ve improved the expressiveness of our I/O project, let’s look at some more features of `cargo` that will help us share the project with the world. rust Storing UTF-8 Encoded Text with Strings Storing UTF-8 Encoded Text with Strings ======================================= We talked about strings in Chapter 4, but we’ll look at them in more depth now. New Rustaceans commonly get stuck on strings for a combination of three reasons: Rust’s propensity for exposing possible errors, strings being a more complicated data structure than many programmers give them credit for, and UTF-8. These factors combine in a way that can seem difficult when you’re coming from other programming languages. We discuss strings in the context of collections because strings are implemented as a collection of bytes, plus some methods to provide useful functionality when those bytes are interpreted as text. In this section, we’ll talk about the operations on `String` that every collection type has, such as creating, updating, and reading. We’ll also discuss the ways in which `String` is different from the other collections, namely how indexing into a `String` is complicated by the differences between how people and computers interpret `String` data. ### What Is a String? We’ll first define what we mean by the term *string*. Rust has only one string type in the core language, which is the string slice `str` that is usually seen in its borrowed form `&str`. In Chapter 4, we talked about *string slices*, which are references to some UTF-8 encoded string data stored elsewhere. String literals, for example, are stored in the program’s binary and are therefore string slices. The `String` type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they might be referring to either the `String` or the string slice `&str` types, not just one of those types. Although this section is largely about `String`, both types are used heavily in Rust’s standard library, and both `String` and string slices are UTF-8 encoded. ### Creating a New String Many of the same operations available with `Vec<T>` are available with `String` as well, because `String` is actually implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions, and capabilities. An example of a function that works the same way with `Vec<T>` and `String` is the `new` function to create an instance, shown in Listing 8-11. ``` fn main() { let mut s = String::new(); } ``` Listing 8-11: Creating a new, empty `String` This line creates a new empty string called `s`, which we can then load data into. Often, we’ll have some initial data that we want to start the string with. For that, we use the `to_string` method, which is available on any type that implements the `Display` trait, as string literals do. Listing 8-12 shows two examples. ``` fn main() { let data = "initial contents"; let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string(); } ``` Listing 8-12: Using the `to_string` method to create a `String` from a string literal This code creates a string containing `initial contents`. We can also use the function `String::from` to create a `String` from a string literal. The code in Listing 8-13 is equivalent to the code from Listing 8-12 that uses `to_string`. ``` fn main() { let s = String::from("initial contents"); } ``` Listing 8-13: Using the `String::from` function to create a `String` from a string literal Because strings are used for so many things, we can use many different generic APIs for strings, providing us with a lot of options. Some of them can seem redundant, but they all have their place! In this case, `String::from` and `to_string` do the same thing, so which you choose is a matter of style and readability. Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them, as shown in Listing 8-14. ``` fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); } ``` Listing 8-14: Storing greetings in different languages in strings All of these are valid `String` values. ### Updating a String A `String` can grow in size and its contents can change, just like the contents of a `Vec<T>`, if you push more data into it. In addition, you can conveniently use the `+` operator or the `format!` macro to concatenate `String` values. #### Appending to a String with `push_str` and `push` We can grow a `String` by using the `push_str` method to append a string slice, as shown in Listing 8-15. ``` fn main() { let mut s = String::from("foo"); s.push_str("bar"); } ``` Listing 8-15: Appending a string slice to a `String` using the `push_str` method After these two lines, `s` will contain `foobar`. The `push_str` method takes a string slice because we don’t necessarily want to take ownership of the parameter. For example, in the code in Listing 8-16, we want to be able to use `s2` after appending its contents to `s1`. ``` fn main() { let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); println!("s2 is {}", s2); } ``` Listing 8-16: Using a string slice after appending its contents to a `String` If the `push_str` method took ownership of `s2`, we wouldn’t be able to print its value on the last line. However, this code works as we’d expect! The `push` method takes a single character as a parameter and adds it to the `String`. Listing 8-17 adds the letter “l” to a `String` using the `push` method. ``` fn main() { let mut s = String::from("lo"); s.push('l'); } ``` Listing 8-17: Adding one character to a `String` value using `push` As a result, `s` will contain `lol`. #### Concatenation with the `+` Operator or the `format!` Macro Often, you’ll want to combine two existing strings. One way to do so is to use the `+` operator, as shown in Listing 8-18. ``` fn main() { let s1 = String::from("Hello, "); let s2 = String::from("world!"); let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used } ``` Listing 8-18: Using the `+` operator to combine two `String` values into a new `String` value The string `s3` will contain `Hello, world!`. The reason `s1` is no longer valid after the addition, and the reason we used a reference to `s2`, has to do with the signature of the method that’s called when we use the `+` operator. The `+` operator uses the `add` method, whose signature looks something like this: ``` fn add(self, s: &str) -> String { ``` In the standard library, you'll see `add` defined using generics and associated types. Here, we’ve substituted in concrete types, which is what happens when we call this method with `String` values. We’ll discuss generics in Chapter 10. This signature gives us the clues we need to understand the tricky bits of the `+` operator. First, `s2` has an `&`, meaning that we’re adding a *reference* of the second string to the first string. This is because of the `s` parameter in the `add` function: we can only add a `&str` to a `String`; we can’t add two `String` values together. But wait—the type of `&s2` is `&String`, not `&str`, as specified in the second parameter to `add`. So why does Listing 8-18 compile? The reason we’re able to use `&s2` in the call to `add` is that the compiler can *coerce* the `&String` argument into a `&str`. When we call the `add` method, Rust uses a *deref coercion*, which here turns `&s2` into `&s2[..]`. We’ll discuss deref coercion in more depth in Chapter 15. Because `add` does not take ownership of the `s` parameter, `s2` will still be a valid `String` after this operation. Second, we can see in the signature that `add` takes ownership of `self`, because `self` does *not* have an `&`. This means `s1` in Listing 8-18 will be moved into the `add` call and will no longer be valid after that. So although `let s3 = s1 + &s2;` looks like it will copy both strings and create a new one, this statement actually takes ownership of `s1`, appends a copy of the contents of `s2`, and then returns ownership of the result. In other words, it looks like it’s making a lot of copies but isn’t; the implementation is more efficient than copying. If we need to concatenate multiple strings, the behavior of the `+` operator gets unwieldy: ``` fn main() { let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = s1 + "-" + &s2 + "-" + &s3; } ``` At this point, `s` will be `tic-tac-toe`. With all of the `+` and `"` characters, it’s difficult to see what’s going on. For more complicated string combining, we can instead use the `format!` macro: ``` fn main() { let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = format!("{}-{}-{}", s1, s2, s3); } ``` This code also sets `s` to `tic-tac-toe`. The `format!` macro works like `println!`, but instead of printing the output to the screen, it returns a `String` with the contents. The version of the code using `format!` is much easier to read, and the code generated by the `format!` macro uses references so that this call doesn’t take ownership of any of its parameters. ### Indexing into Strings In many other programming languages, accessing individual characters in a string by referencing them by index is a valid and common operation. However, if you try to access parts of a `String` using indexing syntax in Rust, you’ll get an error. Consider the invalid code in Listing 8-19. ``` fn main() { let s1 = String::from("hello"); let h = s1[0]; } ``` Listing 8-19: Attempting to use indexing syntax with a String This code will result in the following error: ``` $ cargo run Compiling collections v0.1.0 (file:///projects/collections) error[E0277]: the type `String` cannot be indexed by `{integer}` --> src/main.rs:3:13 | 3 | let h = s1[0]; | ^^^^^ `String` cannot be indexed by `{integer}` | = help: the trait `Index<{integer}>` is not implemented for `String` = help: the following other types implement trait `Index<Idx>`: <String as Index<RangeFrom<usize>>> <String as Index<RangeFull>> <String as Index<RangeInclusive<usize>>> <String as Index<RangeTo<usize>>> <String as Index<RangeToInclusive<usize>>> <String as Index<std::ops::Range<usize>>> <str as Index<I>> For more information about this error, try `rustc --explain E0277`. error: could not compile `collections` due to previous error ``` The error and the note tell the story: Rust strings don’t support indexing. But why not? To answer that question, we need to discuss how Rust stores strings in memory. #### Internal Representation A `String` is a wrapper over a `Vec<u8>`. Let’s look at some of our properly encoded UTF-8 example strings from Listing 8-14. First, this one: ``` fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); } ``` In this case, `len` will be 4, which means the vector storing the string “Hola” is 4 bytes long. Each of these letters takes 1 byte when encoded in UTF-8. The following line, however, may surprise you. (Note that this string begins with the capital Cyrillic letter Ze, not the Arabic number 3.) ``` fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); } ``` Asked how long the string is, you might say 12. In fact, Rust’s answer is 24: that’s the number of bytes it takes to encode “Здравствуйте” in UTF-8, because each Unicode scalar value in that string takes 2 bytes of storage. Therefore, an index into the string’s bytes will not always correlate to a valid Unicode scalar value. To demonstrate, consider this invalid Rust code: ``` let hello = "Здравствуйте"; let answer = &hello[0]; ``` You already know that `answer` will not be `З`, the first letter. When encoded in UTF-8, the first byte of `З` is `208` and the second is `151`, so it would seem that `answer` should in fact be `208`, but `208` is not a valid character on its own. Returning `208` is likely not what a user would want if they asked for the first letter of this string; however, that’s the only data that Rust has at byte index 0. Users generally don’t want the byte value returned, even if the string contains only Latin letters: if `&"hello"[0]` were valid code that returned the byte value, it would return `104`, not `h`. The answer, then, is that to avoid returning an unexpected value and causing bugs that might not be discovered immediately, Rust doesn’t compile this code at all and prevents misunderstandings early in the development process. #### Bytes and Scalar Values and Grapheme Clusters! Oh My! Another point about UTF-8 is that there are actually three relevant ways to look at strings from Rust’s perspective: as bytes, scalar values, and grapheme clusters (the closest thing to what we would call *letters*). If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is stored as a vector of `u8` values that looks like this: ``` [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] ``` That’s 18 bytes and is how computers ultimately store this data. If we look at them as Unicode scalar values, which are what Rust’s `char` type is, those bytes look like this: ``` ['न', 'म', 'स', '्', 'त', 'े'] ``` There are six `char` values here, but the fourth and sixth are not letters: they’re diacritics that don’t make sense on their own. Finally, if we look at them as grapheme clusters, we’d get what a person would call the four letters that make up the Hindi word: ``` ["न", "म", "स्", "ते"] ``` Rust provides different ways of interpreting the raw string data that computers store so that each program can choose the interpretation it needs, no matter what human language the data is in. A final reason Rust doesn’t allow us to index into a `String` to get a character is that indexing operations are expected to always take constant time (O(1)). But it isn’t possible to guarantee that performance with a `String`, because Rust would have to walk through the contents from the beginning to the index to determine how many valid characters there were. ### Slicing Strings Indexing into a string is often a bad idea because it’s not clear what the return type of the string-indexing operation should be: a byte value, a character, a grapheme cluster, or a string slice. If you really need to use indices to create string slices, therefore, Rust asks you to be more specific. Rather than indexing using `[]` with a single number, you can use `[]` with a range to create a string slice containing particular bytes: ``` #![allow(unused)] fn main() { let hello = "Здравствуйте"; let s = &hello[0..4]; } ``` Here, `s` will be a `&str` that contains the first 4 bytes of the string. Earlier, we mentioned that each of these characters was 2 bytes, which means `s` will be `Зд`. If we were to try to slice only part of a character’s bytes with something like `&hello[0..1]`, Rust would panic at runtime in the same way as if an invalid index were accessed in a vector: ``` $ cargo run Compiling collections v0.1.0 (file:///projects/collections) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/collections` thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', library/core/src/str/mod.rs:127:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` You should use ranges to create string slices with caution, because doing so can crash your program. ### Methods for Iterating Over Strings The best way to operate on pieces of strings is to be explicit about whether you want characters or bytes. For individual Unicode scalar values, use the `chars` method. Calling `chars` on “Зд” separates out and returns two values of type `char`, and you can iterate over the result to access each element: ``` #![allow(unused)] fn main() { for c in "Зд".chars() { println!("{}", c); } } ``` This code will print the following: ``` З д ``` Alternatively, the `bytes` method returns each raw byte, which might be appropriate for your domain: ``` #![allow(unused)] fn main() { for b in "Зд".bytes() { println!("{}", b); } } ``` This code will print the four bytes that make up this string: ``` 208 151 208 180 ``` But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte. Getting grapheme clusters from strings as with the Devanagari script is complex, so this functionality is not provided by the standard library. Crates are available on [crates.io](https://crates.io/) if this is the functionality you need. ### Strings Are Not So Simple To summarize, strings are complicated. Different programming languages make different choices about how to present this complexity to the programmer. Rust has chosen to make the correct handling of `String` data the default behavior for all Rust programs, which means programmers have to put more thought into handling UTF-8 data upfront. This trade-off exposes more of the complexity of strings than is apparent in other programming languages, but it prevents you from having to handle errors involving non-ASCII characters later in your development life cycle. The good news is that the standard library offers a lot of functionality built off the `String` and `&str` types to help handle these complex situations correctly. Be sure to check out the documentation for useful methods like `contains` for searching in a string and `replace` for substituting parts of a string with another string. Let’s switch to something a bit less complex: hash maps!
programming_docs
rust Appendix C: Derivable Traits Appendix C: Derivable Traits ============================ In various places in the book, we’ve discussed the `derive` attribute, which you can apply to a struct or enum definition. The `derive` attribute generates code that will implement a trait with its own default implementation on the type you’ve annotated with the `derive` syntax. In this appendix, we provide a reference of all the traits in the standard library that you can use with `derive`. Each section covers: * What operators and methods deriving this trait will enable * What the implementation of the trait provided by `derive` does * What implementing the trait signifies about the type * The conditions in which you’re allowed or not allowed to implement the trait * Examples of operations that require the trait If you want different behavior from that provided by the `derive` attribute, consult the [standard library documentation](../std/index) for each trait for details of how to manually implement them. These traits listed here are the only ones defined by the standard library that can be implemented on your types using `derive`. Other traits defined in the standard library don’t have sensible default behavior, so it’s up to you to implement them in the way that makes sense for what you’re trying to accomplish. An example of a trait that can’t be derived is `Display`, which handles formatting for end users. You should always consider the appropriate way to display a type to an end user. What parts of the type should an end user be allowed to see? What parts would they find relevant? What format of the data would be most relevant to them? The Rust compiler doesn’t have this insight, so it can’t provide appropriate default behavior for you. The list of derivable traits provided in this appendix is not comprehensive: libraries can implement `derive` for their own traits, making the list of traits you can use `derive` with truly open-ended. Implementing `derive` involves using a procedural macro, which is covered in the [“Macros”](ch19-06-macros#macros) section of Chapter 19. ### `Debug` for Programmer Output The `Debug` trait enables debug formatting in format strings, which you indicate by adding `:?` within `{}` placeholders. The `Debug` trait allows you to print instances of a type for debugging purposes, so you and other programmers using your type can inspect an instance at a particular point in a program’s execution. The `Debug` trait is required, for example, in use of the `assert_eq!` macro. This macro prints the values of instances given as arguments if the equality assertion fails so programmers can see why the two instances weren’t equal. ### `PartialEq` and `Eq` for Equality Comparisons The `PartialEq` trait allows you to compare instances of a type to check for equality and enables use of the `==` and `!=` operators. Deriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on structs, two instances are equal only if *all* fields are equal, and the instances are not equal if any fields are not equal. When derived on enums, each variant is equal to itself and not equal to the other variants. The `PartialEq` trait is required, for example, with the use of the `assert_eq!` macro, which needs to be able to compare two instances of a type for equality. The `Eq` trait has no methods. Its purpose is to signal that for every value of the annotated type, the value is equal to itself. The `Eq` trait can only be applied to types that also implement `PartialEq`, although not all types that implement `PartialEq` can implement `Eq`. One example of this is floating point number types: the implementation of floating point numbers states that two instances of the not-a-number (`NaN`) value are not equal to each other. An example of when `Eq` is required is for keys in a `HashMap<K, V>` so the `HashMap<K, V>` can tell whether two keys are the same. ### `PartialOrd` and `Ord` for Ordering Comparisons The `PartialOrd` trait allows you to compare instances of a type for sorting purposes. A type that implements `PartialOrd` can be used with the `<`, `>`, `<=`, and `>=` operators. You can only apply the `PartialOrd` trait to types that also implement `PartialEq`. Deriving `PartialOrd` implements the `partial_cmp` method, which returns an `Option<Ordering>` that will be `None` when the values given don’t produce an ordering. An example of a value that doesn’t produce an ordering, even though most values of that type can be compared, is the not-a-number (`NaN`) floating point value. Calling `partial_cmp` with any floating point number and the `NaN` floating point value will return `None`. When derived on structs, `PartialOrd` compares two instances by comparing the value in each field in the order in which the fields appear in the struct definition. When derived on enums, variants of the enum declared earlier in the enum definition are considered less than the variants listed later. The `PartialOrd` trait is required, for example, for the `gen_range` method from the `rand` crate that generates a random value in the range specified by a range expression. The `Ord` trait allows you to know that for any two values of the annotated type, a valid ordering will exist. The `Ord` trait implements the `cmp` method, which returns an `Ordering` rather than an `Option<Ordering>` because a valid ordering will always be possible. You can only apply the `Ord` trait to types that also implement `PartialOrd` and `Eq` (and `Eq` requires `PartialEq`). When derived on structs and enums, `cmp` behaves the same way as the derived implementation for `partial_cmp` does with `PartialOrd`. An example of when `Ord` is required is when storing values in a `BTreeSet<T>`, a data structure that stores data based on the sort order of the values. ### `Clone` and `Copy` for Duplicating Values The `Clone` trait allows you to explicitly create a deep copy of a value, and the duplication process might involve running arbitrary code and copying heap data. See the [“Ways Variables and Data Interact: Clone”](ch04-01-what-is-ownership#ways-variables-and-data-interact-clone) section in Chapter 4 for more information on `Clone`. Deriving `Clone` implements the `clone` method, which when implemented for the whole type, calls `clone` on each of the parts of the type. This means all the fields or values in the type must also implement `Clone` to derive `Clone`. An example of when `Clone` is required is when calling the `to_vec` method on a slice. The slice doesn’t own the type instances it contains, but the vector returned from `to_vec` will need to own its instances, so `to_vec` calls `clone` on each item. Thus, the type stored in the slice must implement `Clone`. The `Copy` trait allows you to duplicate a value by only copying bits stored on the stack; no arbitrary code is necessary. See the [“Stack-Only Data: Copy”](ch04-01-what-is-ownership#stack-only-data-copy) section in Chapter 4 for more information on `Copy`. The `Copy` trait doesn’t define any methods to prevent programmers from overloading those methods and violating the assumption that no arbitrary code is being run. That way, all programmers can assume that copying a value will be very fast. You can derive `Copy` on any type whose parts all implement `Copy`. A type that implements `Copy` must also implement `Clone`, because a type that implements `Copy` has a trivial implementation of `Clone` that performs the same task as `Copy`. The `Copy` trait is rarely required; types that implement `Copy` have optimizations available, meaning you don’t have to call `clone`, which makes the code more concise. Everything possible with `Copy` you can also accomplish with `Clone`, but the code might be slower or have to use `clone` in places. ### `Hash` for Mapping a Value to a Value of Fixed Size The `Hash` trait allows you to take an instance of a type of arbitrary size and map that instance to a value of fixed size using a hash function. Deriving `Hash` implements the `hash` method. The derived implementation of the `hash` method combines the result of calling `hash` on each of the parts of the type, meaning all fields or values must also implement `Hash` to derive `Hash`. An example of when `Hash` is required is in storing keys in a `HashMap<K, V>` to store data efficiently. ### `Default` for Default Values The `Default` trait allows you to create a default value for a type. Deriving `Default` implements the `default` function. The derived implementation of the `default` function calls the `default` function on each part of the type, meaning all fields or values in the type must also implement `Default` to derive `Default`. The `Default::default` function is commonly used in combination with the struct update syntax discussed in the [“Creating Instances From Other Instances With Struct Update Syntax”](ch05-01-defining-structs#creating-instances-from-other-instances-with-struct-update-syntax) section in Chapter 5. You can customize a few fields of a struct and then set and use a default value for the rest of the fields by using `..Default::default()`. The `Default` trait is required when you use the method `unwrap_or_default` on `Option<T>` instances, for example. If the `Option<T>` is `None`, the method `unwrap_or_default` will return the result of `Default::default` for the type `T` stored in the `Option<T>`. rust Writing Error Messages to Standard Error Instead of Standard Output Writing Error Messages to Standard Error Instead of Standard Output =================================================================== At the moment, we’re writing all of our output to the terminal using the `println!` macro. In most terminals, there are two kinds of output: *standard output* (`stdout`) for general information and *standard error* (`stderr`) for error messages. This distinction enables users to choose to direct the successful output of a program to a file but still print error messages to the screen. The `println!` macro is only capable of printing to standard output, so we have to use something else to print to standard error. ### Checking Where Errors Are Written First, let’s observe how the content printed by `minigrep` is currently being written to standard output, including any error messages we want to write to standard error instead. We’ll do that by redirecting the standard output stream to a file while intentionally causing an error. We won’t redirect the standard error stream, so any content sent to standard error will continue to display on the screen. Command line programs are expected to send error messages to the standard error stream so we can still see error messages on the screen even if we redirect the standard output stream to a file. Our program is not currently well-behaved: we’re about to see that it saves the error message output to a file instead! To demonstrate this behavior, we’ll run the program with `>` and the file path, *output.txt*, that we want to redirect the standard output stream to. We won’t pass any arguments, which should cause an error: ``` $ cargo run > output.txt ``` The `>` syntax tells the shell to write the contents of standard output to *output.txt* instead of the screen. We didn’t see the error message we were expecting printed to the screen, so that means it must have ended up in the file. This is what *output.txt* contains: ``` Problem parsing arguments: not enough arguments ``` Yup, our error message is being printed to standard output. It’s much more useful for error messages like this to be printed to standard error so only data from a successful run ends up in the file. We’ll change that. ### Printing Errors to Standard Error We’ll use the code in Listing 12-24 to change how error messages are printed. Because of the refactoring we did earlier in this chapter, all the code that prints error messages is in one function, `main`. The standard library provides the `eprintln!` macro that prints to the standard error stream, so let’s change the two places we were calling `println!` to print errors to use `eprintln!` instead. Filename: src/main.rs ``` use std::env; use std::process; use minigrep::Config; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = minigrep::run(config) { eprintln!("Application error: {e}"); process::exit(1); } } ``` Listing 12-24: Writing error messages to standard error instead of standard output using `eprintln!` Let’s now run the program again in the same way, without any arguments and redirecting standard output with `>`: ``` $ cargo run > output.txt Problem parsing arguments: not enough arguments ``` Now we see the error onscreen and *output.txt* contains nothing, which is the behavior we expect of command line programs. Let’s run the program again with arguments that don’t cause an error but still redirect standard output to a file, like so: ``` $ cargo run -- to poem.txt > output.txt ``` We won’t see any output to the terminal, and *output.txt* will contain our results: Filename: output.txt ``` Are you nobody, too? How dreary to be somebody! ``` This demonstrates that we’re now using standard output for successful output and standard error for error output as appropriate. Summary ------- This chapter recapped some of the major concepts you’ve learned so far and covered how to perform common I/O operations in Rust. By using command line arguments, files, environment variables, and the `eprintln!` macro for printing errors, you’re now prepared to write command line applications. Combined with the concepts in previous chapters, your code will be well organized, store data effectively in the appropriate data structures, handle errors nicely, and be well tested. Next, we’ll explore some Rust features that were influenced by functional languages: closures and iterators. rust Statements and expressions Statements and expressions ========================== Rust is *primarily* an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax category of *expressions*. Each kind of expression can typically *nest* within each other kind of expression, and rules for evaluation of expressions involve specifying both the value produced by the expression and the order in which its sub-expressions are themselves evaluated. In contrast, statements serve *mostly* to contain and explicitly sequence expression evaluation. rust Identifiers Identifiers =========== > **Lexer:** > IDENTIFIER\_OR\_KEYWORD : > XID\_Start XID\_Continue\* > | `_` XID\_Continue+ > > RAW\_IDENTIFIER : `r#` IDENTIFIER\_OR\_KEYWORD *Except `crate`, `self`, `super`, `Self`* > > NON\_KEYWORD\_IDENTIFIER : IDENTIFIER\_OR\_KEYWORD *Except a [strict](keywords#strict-keywords) or [reserved](keywords#reserved-keywords) keyword* > > IDENTIFIER : > NON\_KEYWORD\_IDENTIFIER | RAW\_IDENTIFIER > > Identifiers follow the specification in [Unicode Standard Annex #31](https://www.unicode.org/reports/tr31/tr31-33.html) for Unicode version 13.0, with the additions described below. Some examples of identifiers: * `foo` * `_identifier` * `r#true` * `Москва` * `東京` The profile used from UAX #31 is: * Start := [`XID_Start`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=), plus the underscore character (U+005F) * Continue := [`XID_Continue`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=) * Medial := empty with the additional constraint that a single underscore character is not an identifier. > **Note**: Identifiers starting with an underscore are typically used to indicate an identifier that is intentionally unused, and will silence the unused warning in `rustc`. > > Identifiers may not be a [strict](keywords#strict-keywords) or [reserved](keywords#reserved-keywords) keyword without the `r#` prefix described below in [raw identifiers](#raw-identifiers). Zero width non-joiner (ZWNJ U+200C) and zero width joiner (ZWJ U+200D) characters are not allowed in identifiers. Identifiers are restricted to the ASCII subset of [`XID_Start`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=) and [`XID_Continue`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=) in the following situations: * [`extern crate`](items/extern-crates) declarations * External crate names referenced in a [path](paths) * [Module](items/modules) names loaded from the filesystem without a [`path` attribute](items/modules#the-path-attribute) * [`no_mangle`](abi#the-no_mangle-attribute) attributed items * Item names in [external blocks](items/external-blocks) Normalization ------------- Identifiers are normalized using Normalization Form C (NFC) as defined in [Unicode Standard Annex #15](https://www.unicode.org/reports/tr15/tr15-50.html). Two identifiers are equal if their NFC forms are equal. [Procedural](procedural-macros) and [declarative](macros-by-example) macros receive normalized identifiers in their input. Raw identifiers --------------- A raw identifier is like a normal identifier, but prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual identifier.) Unlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for `RAW_IDENTIFIER`. rust Keywords Keywords ======== Rust divides keywords into three categories: * [strict](#strict-keywords) * [reserved](#reserved-keywords) * [weak](#weak-keywords) Strict keywords --------------- These keywords can only be used in their correct contexts. They cannot be used as the names of: * [Items](items) * [Variables](variables) and function parameters * Fields and [variants](items/enumerations) * [Type parameters](types/parameters) * Lifetime parameters or [loop labels](expressions/loop-expr#loop-labels) * [Macros](macros) or <attributes> * [Macro placeholders](macros-by-example) * [Crates](crates-and-source-files) > **Lexer:** > KW\_AS : `as` > KW\_BREAK : `break` > KW\_CONST : `const` > KW\_CONTINUE : `continue` > KW\_CRATE : `crate` > KW\_ELSE : `else` > KW\_ENUM : `enum` > KW\_EXTERN : `extern` > KW\_FALSE : `false` > KW\_FN : `fn` > KW\_FOR : `for` > KW\_IF : `if` > KW\_IMPL : `impl` > KW\_IN : `in` > KW\_LET : `let` > KW\_LOOP : `loop` > KW\_MATCH : `match` > KW\_MOD : `mod` > KW\_MOVE : `move` > KW\_MUT : `mut` > KW\_PUB : `pub` > KW\_REF : `ref` > KW\_RETURN : `return` > KW\_SELFVALUE : `self` > KW\_SELFTYPE : `Self` > KW\_STATIC : `static` > KW\_STRUCT : `struct` > KW\_SUPER : `super` > KW\_TRAIT : `trait` > KW\_TRUE : `true` > KW\_TYPE : `type` > KW\_UNSAFE : `unsafe` > KW\_USE : `use` > KW\_WHERE : `where` > KW\_WHILE : `while` > > The following keywords were added beginning in the 2018 edition. > **Lexer 2018+** > KW\_ASYNC : `async` > KW\_AWAIT : `await` > KW\_DYN : `dyn` > > Reserved keywords ----------------- These keywords aren't used yet, but they are reserved for future use. They have the same restrictions as strict keywords. The reasoning behind this is to make current programs forward compatible with future versions of Rust by forbidding them to use these keywords. > **Lexer** > KW\_ABSTRACT : `abstract` > KW\_BECOME : `become` > KW\_BOX : `box` > KW\_DO : `do` > KW\_FINAL : `final` > KW\_MACRO : `macro` > KW\_OVERRIDE : `override` > KW\_PRIV : `priv` > KW\_TYPEOF : `typeof` > KW\_UNSIZED : `unsized` > KW\_VIRTUAL : `virtual` > KW\_YIELD : `yield` > > The following keywords are reserved beginning in the 2018 edition. > **Lexer 2018+** > KW\_TRY : `try` > > Weak keywords ------------- These keywords have special meaning only in certain contexts. For example, it is possible to declare a variable or method with the name `union`. * `macro_rules` is used to create custom <macros>. * `union` is used to declare a [union](items/unions) and is only a keyword when used in a union declaration. * `'static` is used for the static lifetime and cannot be used as a [generic lifetime parameter](items/generics) or [loop label](expressions/loop-expr#loop-labels) ``` // error[E0262]: invalid lifetime parameter name: `'static` fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s } ``` * In the 2015 edition, [`dyn`](types/trait-object) is a keyword when used in a type position followed by a path that does not start with `::`. Beginning in the 2018 edition, `dyn` has been promoted to a strict keyword. > **Lexer** > KW\_UNION : `union` > KW\_STATICLIFETIME : `'static` > > **Lexer 2015** > KW\_DYN : `dyn` > >
programming_docs
rust Attributes Attributes ========== > **Syntax** > *InnerAttribute* : > `#` `!` `[` *Attr* `]` > > *OuterAttribute* : > `#` `[` *Attr* `]` > > *Attr* : > [*SimplePath*](paths#simple-paths) *AttrInput*? > > *AttrInput* : > [*DelimTokenTree*](macros) > | `=` [*Expression*](expressions) > > An *attribute* is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in [ECMA-335](https://www.ecma-international.org/publications/standards/Ecma-335.htm), with the syntax coming from [ECMA-334](https://www.ecma-international.org/publications/standards/Ecma-334.htm) (C#). *Inner attributes*, written with a bang (`!`) after the hash (`#`), apply to the item that the attribute is declared within. *Outer attributes*, written without the bang after the hash, apply to the thing that follows the attribute. The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign (`=`) followed by an expression. See the [meta item syntax](#meta-item-attribute-syntax) below for more details. Attributes can be classified into the following kinds: * [Built-in attributes](#built-in-attributes-index) * [Macro attributes](procedural-macros#attribute-macros) * [Derive macro helper attributes](procedural-macros#derive-macro-helper-attributes) * [Tool attributes](#tool-attributes) Attributes may be applied to many things in the language: * All [item declarations](items) accept outer attributes while [external blocks](items/external-blocks), [functions](items/functions), [implementations](items/implementations), and [modules](items/modules) accept inner attributes. * Most <statements> accept outer attributes (see [Expression Attributes](expressions#expression-attributes) for limitations on expression statements). * [Block expressions](expressions/block-expr) accept outer and inner attributes, but only when they are the outer expression of an [expression statement](statements#expression-statements) or the final expression of another block expression. * [Enum](items/enumerations) variants and [struct](items/structs) and [union](items/unions) fields accept outer attributes. * [Match expression arms](expressions/match-expr) accept outer attributes. * [Generic lifetime or type parameter](items/generics) accept outer attributes. * Expressions accept outer attributes in limited situations, see [Expression Attributes](expressions#expression-attributes) for details. * [Function](items/functions), [closure](expressions/closure-expr) and [function pointer](types/function-pointer) parameters accept outer attributes. This includes attributes on variadic parameters denoted with `...` in function pointers and [external blocks](items/external-blocks#variadic-functions). Some examples of attributes: ``` #![allow(unused)] fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; // Inner attribute applies to the entire function. fn some_unused_variables() { #![allow(unused_variables)] let x = (); let y = (); let z = (); } } ``` Meta Item Attribute Syntax -------------------------- A "meta item" is the syntax used for the *Attr* rule by most [built-in attributes](#built-in-attributes-index). It has the following grammar: > **Syntax** > *MetaItem* : > [*SimplePath*](paths#simple-paths) > | [*SimplePath*](paths#simple-paths) `=` [*Expression*](expressions) > | [*SimplePath*](paths#simple-paths) `(` *MetaSeq*? `)` > > *MetaSeq* : > *MetaItemInner* ( `,` MetaItemInner )\* `,`? > > *MetaItemInner* : > *MetaItem* > | [*Expression*](expressions) > > Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing. Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the `Serialize` proc-macro first, which must preserve the `include_str!` call in order for it to be expanded: ``` #[derive(Serialize)] struct Foo { #[doc = include_str!("x.md")] x: u32 } ``` Additionally, macros in attributes will be expanded only after all other attributes applied to the item: ``` #[macro_attr1] // expanded first #[doc = mac!()] // `mac!` is expanded fourth. #[macro_attr2] // expanded second #[derive(MacroDerive1, MacroDerive2)] // expanded third fn foo() {} ``` Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms: > **Syntax** > *MetaWord*: > [IDENTIFIER](identifiers) > > *MetaNameValueStr*: > [IDENTIFIER](identifiers) `=` ([STRING\_LITERAL](tokens#string-literals) | [RAW\_STRING\_LITERAL](tokens#raw-string-literals)) > > *MetaListPaths*: > [IDENTIFIER](identifiers) `(` ( [*SimplePath*](paths#simple-paths) (`,` [*SimplePath*](paths#simple-paths))\* `,`? )? `)` > > *MetaListIdents*: > [IDENTIFIER](identifiers) `(` ( [IDENTIFIER](identifiers) (`,` [IDENTIFIER](identifiers))\* `,`? )? `)` > > *MetaListNameValueStr*: > [IDENTIFIER](identifiers) `(` ( *MetaNameValueStr* (`,` *MetaNameValueStr*)\* `,`? )? `)` > > Some examples of meta items are: | Style | Example | | --- | --- | | *MetaWord* | `no_std` | | *MetaNameValueStr* | `doc = "example"` | | *MetaListPaths* | `allow(unused, clippy::inline_always)` | | *MetaListIdents* | `macro_use(foo, bar)` | | *MetaListNameValueStr* | `link(name = "CoreFoundation", kind = "framework")` | Active and inert attributes --------------------------- An attribute is either active or inert. During attribute processing, *active attributes* remove themselves from the thing they are on while *inert attributes* stay on. The [`cfg`](conditional-compilation#the-cfg-attribute) and [`cfg_attr`](conditional-compilation#the-cfg_attr-attribute) attributes are active. The [`test`](attributes/testing#the-test-attribute) attribute is inert when compiling for tests and active otherwise. [Attribute macros](procedural-macros#attribute-macros) are active. All other attributes are inert. Tool attributes --------------- The compiler may allow attributes for external tools where each tool resides in its own namespace in the [tool prelude](names/preludes#tool-prelude). The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool. When a tool is not in use, the tool's attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes. Tool attributes are not available if the [`no_implicit_prelude`](names/preludes#the-no_implicit_prelude-attribute) attribute is used. ``` #![allow(unused)] fn main() { // Tells the rustfmt tool to not format the following element. #[rustfmt::skip] struct S { } // Controls the "cyclomatic complexity" threshold for the clippy tool. #[clippy::cyclomatic_complexity = "100"] pub fn f() {} } ``` > Note: `rustc` currently recognizes the tools "clippy" and "rustfmt". > > Built-in attributes index ------------------------- The following is an index of all built-in attributes. * Conditional compilation + [`cfg`](conditional-compilation#the-cfg-attribute) — Controls conditional compilation. + [`cfg_attr`](conditional-compilation#the-cfg_attr-attribute) — Conditionally includes attributes. * Testing + [`test`](attributes/testing#the-test-attribute) — Marks a function as a test. + [`ignore`](attributes/testing#the-ignore-attribute) — Disables a test function. + [`should_panic`](attributes/testing#the-should_panic-attribute) — Indicates a test should generate a panic. * Derive + [`derive`](attributes/derive) — Automatic trait implementations. + [`automatically_derived`](attributes/derive#the-automatically_derived-attribute) — Marker for implementations created by `derive`. * Macros + [`macro_export`](macros-by-example#path-based-scope) — Exports a `macro_rules` macro for cross-crate usage. + [`macro_use`](macros-by-example#the-macro_use-attribute) — Expands macro visibility, or imports macros from other crates. + [`proc_macro`](procedural-macros#function-like-procedural-macros) — Defines a function-like macro. + [`proc_macro_derive`](procedural-macros#derive-macros) — Defines a derive macro. + [`proc_macro_attribute`](procedural-macros#attribute-macros) — Defines an attribute macro. * Diagnostics + [`allow`](attributes/diagnostics#lint-check-attributes), [`warn`](attributes/diagnostics#lint-check-attributes), [`deny`](attributes/diagnostics#lint-check-attributes), [`forbid`](attributes/diagnostics#lint-check-attributes) — Alters the default lint level. + [`deprecated`](attributes/diagnostics#the-deprecated-attribute) — Generates deprecation notices. + [`must_use`](attributes/diagnostics#the-must_use-attribute) — Generates a lint for unused values. * ABI, linking, symbols, and FFI + [`link`](items/external-blocks#the-link-attribute) — Specifies a native library to link with an `extern` block. + [`link_name`](items/external-blocks#the-link_name-attribute) — Specifies the name of the symbol for functions or statics in an `extern` block. + [`no_link`](items/extern-crates#the-no_link-attribute) — Prevents linking an extern crate. + [`repr`](type-layout#representations) — Controls type layout. + [`crate_type`](linkage) — Specifies the type of crate (library, executable, etc.). + [`no_main`](crates-and-source-files#the-no_main-attribute) — Disables emitting the `main` symbol. + [`export_name`](abi#the-export_name-attribute) — Specifies the exported symbol name for a function or static. + [`link_section`](abi#the-link_section-attribute) — Specifies the section of an object file to use for a function or static. + [`no_mangle`](abi#the-no_mangle-attribute) — Disables symbol name encoding. + [`used`](abi#the-used-attribute) — Forces the compiler to keep a static item in the output object file. + [`crate_name`](crates-and-source-files#the-crate_name-attribute) — Specifies the crate name. * Code generation + [`inline`](attributes/codegen#the-inline-attribute) — Hint to inline code. + [`cold`](attributes/codegen#the-cold-attribute) — Hint that a function is unlikely to be called. + [`no_builtins`](attributes/codegen#the-no_builtins-attribute) — Disables use of certain built-in functions. + [`target_feature`](attributes/codegen#the-target_feature-attribute) — Configure platform-specific code generation. + [`track_caller`](attributes/codegen#the-track_caller-attribute) - Pass the parent call location to `std::panic::Location::caller()`. * Documentation + `doc` — Specifies documentation. See [The Rustdoc Book](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html) for more information. [Doc comments](comments#doc-comments) are transformed into `doc` attributes. * Preludes + [`no_std`](names/preludes#the-no_std-attribute) — Removes std from the prelude. + [`no_implicit_prelude`](names/preludes#the-no_implicit_prelude-attribute) — Disables prelude lookups within a module. * Modules + [`path`](items/modules#the-path-attribute) — Specifies the filename for a module. * Limits + [`recursion_limit`](attributes/limits#the-recursion_limit-attribute) — Sets the maximum recursion limit for certain compile-time operations. + [`type_length_limit`](attributes/limits#the-type_length_limit-attribute) — Sets the maximum size of a polymorphic type. * Runtime + [`panic_handler`](runtime#the-panic_handler-attribute) — Sets the function to handle panics. + [`global_allocator`](runtime#the-global_allocator-attribute) — Sets the global memory allocator. + [`windows_subsystem`](runtime#the-windows_subsystem-attribute) — Specifies the windows subsystem to link with. * Features + `feature` — Used to enable unstable or experimental compiler features. See [The Unstable Book](https://doc.rust-lang.org/unstable-book/index.html) for features implemented in `rustc`. * Type System + [`non_exhaustive`](attributes/type_system#the-non_exhaustive-attribute) — Indicate that a type will have more fields/variants added in future. rust Constant evaluation Constant evaluation =================== Constant evaluation is the process of computing the result of <expressions> during compilation. Only a subset of all expressions can be evaluated at compile-time. Constant expressions -------------------- Certain forms of expressions, called constant expressions, can be evaluated at compile time. In [const contexts](#const-context), these are the only allowed expressions, and are always evaluated at compile time. In other places, such as [let statements](statements#let-statements), constant expressions *may* be, but are not guaranteed to be, evaluated at compile time. Behaviors such as out of bounds [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) or [overflow](expressions/operator-expr#overflow) are compiler errors if the value must be evaluated at compile time (i.e. in const contexts). Otherwise, these behaviors are warnings, but will likely panic at run-time. The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any [`Drop::drop`](destructors) calls to be run. * [Literals](expressions/literal-expr). * [Const parameters](items/generics). * [Paths](expressions/path-expr) to [functions](items/functions) and [constants](items/constant-items). Recursively defining constants is not allowed. * Paths to [statics](items/static-items). These are only allowed within the initializer of a static. * [Tuple expressions](expressions/tuple-expr). * [Array expressions](expressions/array-expr). * [Struct](expressions/struct-expr) expressions. * [Block expressions](expressions/block-expr), including `unsafe` blocks. + [let statements](statements#let-statements) and thus irrefutable <patterns>, including mutable bindings + [assignment expressions](expressions/operator-expr#assignment-expressions) + [compound assignment expressions](expressions/operator-expr#compound-assignment-expressions) + [expression statements](statements#expression-statements) * [Field](expressions/field-expr) expressions. * Index expressions, [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) or [slice](types/slice) with a `usize`. * [Range expressions](expressions/range-expr). * [Closure expressions](expressions/closure-expr) which don't capture variables from the environment. * Built-in [negation](expressions/operator-expr#negation-operators), [arithmetic](expressions/operator-expr#arithmetic-and-logical-binary-operators), [logical](expressions/operator-expr#arithmetic-and-logical-binary-operators), [comparison](expressions/operator-expr#comparison-operators) or [lazy boolean](expressions/operator-expr#lazy-boolean-operators) operators used on integer and floating point types, `bool`, and `char`. * Shared [borrow](expressions/operator-expr#borrow-operators)s, except if applied to a type with [interior mutability](interior-mutability). * The [dereference operator](expressions/operator-expr#the-dereference-operator) except for raw pointers. * [Grouped](expressions/grouped-expr) expressions. * [Cast](expressions/operator-expr#type-cast-expressions) expressions, except + pointer to address casts and + function pointer to address casts. * Calls of [const functions](items/functions#const-functions) and const methods. * [loop](expressions/loop-expr#infinite-loops), [while](expressions/loop-expr#predicate-loops) and [`while let`](expressions/loop-expr#predicate-pattern-loops) expressions. * [if](expressions/if-expr#if-expressions), [`if let`](expressions/if-expr#if-let-expressions) and [match](expressions/match-expr) expressions. Const context ------------- A *const context* is one of the following: * [Array type length expressions](types/array) * [Array repeat length expressions](expressions/array-expr) * The initializer of + [constants](items/constant-items) + [statics](items/static-items) + [enum discriminants](items/enumerations#custom-discriminant-values-for-fieldless-enumerations) * A [const generic argument](items/generics#const-generics) Const Functions --------------- A *const fn* is a function that one is permitted to call from a const context. Declaring a function `const` has no effect on any existing uses, it only restricts the types that arguments and the return type may use, as well as prevent various expressions from being used within it. You can freely do anything with a const function that you can do with a regular function. When called from a const context, the function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So `usize` is `32` bits if you are compiling against a `32` bit system, irrelevant of whether you are building on a `64` bit or a `32` bit system. Const functions have various restrictions to make sure that they can be evaluated at compile-time. It is, for example, not possible to write a random number generator as a const function. Calling a const function at compile-time will always yield the same result as calling it at runtime, even when called multiple times. There's one exception to this rule: if you are doing complex floating point operations in extreme situations, then you might get (very slightly) different results. It is advisable to not make array lengths and enum discriminants depend on floating point computations. Notable features that are allowed in const contexts but not in const functions include: * floating point operations + floating point values are treated just like generic parameters without trait bounds beyond `Copy`. So you cannot do anything with them but copy/move them around. Conversely, the following are possible in a const function, but not in a const context: * Use of generic type and lifetime parameters. + Const contexts do allow limited use of [const generic parameters](items/generics#const-generics). rust Statements Statements ========== > **Syntax** > *Statement* : > `;` > | [*Item*](items) > | [*LetStatement*](#let-statements) > | [*ExpressionStatement*](#expression-statements) > | [*MacroInvocationSemi*](macros#macro-invocation) > > A *statement* is a component of a [block](expressions/block-expr), which is in turn a component of an outer [expression](expressions) or [function](items/functions). Rust has two kinds of statement: [declaration statements](#declaration-statements) and [expression statements](#expression-statements). Declaration statements ---------------------- A *declaration statement* is one that introduces one or more *names* into the enclosing statement block. The declared names may denote new variables or new <items>. The two kinds of declaration statements are item declarations and `let` statements. ### Item declarations An *item declaration statement* has a syntactic form identical to an [item declaration](items) within a [module](items/modules). Declaring an item within a statement block restricts its scope to the block containing the statement. The item is not given a [canonical path](paths#canonical-paths) nor are any sub-items it may declare. The exception to this is that associated items defined by [implementations](items/implementations) are still accessible in outer scopes as long as the item and, if applicable, trait are accessible. It is otherwise identical in meaning to declaring the item inside a module. There is no implicit capture of the containing function's generic parameters, parameters, and local variables. For example, `inner` may not access `outer_var`. ``` #![allow(unused)] fn main() { fn outer() { let outer_var = true; fn inner() { /* outer_var is not in scope here */ } inner(); } } ``` ### `let` statements > **Syntax** > *LetStatement* : > [*OuterAttribute*](attributes)\* `let` [*PatternNoTopAlt*](patterns) ( `:` [*Type*](types) )? (`=` [*Expression*](expressions) )? `;` > > A *`let` statement* introduces a new set of <variables>, given by an irrefutable [pattern](patterns). The pattern is followed optionally by a type annotation and then optionally by an initializer expression. When no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference. Any variables introduced by a variable declaration are visible from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration. Expression statements --------------------- > **Syntax** > *ExpressionStatement* : > [*ExpressionWithoutBlock*](expressions) `;` > | [*ExpressionWithBlock*](expressions) `;`? > > An *expression statement* is one that evaluates an [expression](expressions) and ignores its result. As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression. An expression that consists of only a [block expression](expressions/block-expr) or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement. The type of [*ExpressionWithBlock*](expressions) expressions when used as statements must be the unit type. ``` #![allow(unused)] fn main() { let mut v = vec![1, 2, 3]; v.pop(); // Ignore the element returned from pop if v.is_empty() { v.push(5); } else { v.remove(0); } // Semicolon can be omitted. [1]; // Separate expression statement, not an indexing expression. } ``` When the trailing semicolon is omitted, the result must be type `()`. ``` #![allow(unused)] fn main() { // bad: the block's type is i32, not () // Error: expected `()` because of default return type // if true { // 1 // } // good: the block's type is i32 if true { 1 } else { 2 }; } ``` Attributes on Statements ------------------------ Statements accept [outer attributes](attributes). The attributes that have meaning on a statement are [`cfg`](conditional-compilation), and [the lint check attributes](attributes/diagnostics#lint-check-attributes).
programming_docs
rust Type coercions Type coercions ============== **Type coercions** are implicit operations that change the type of a value. They happen automatically at specific locations and are highly restricted in what types actually coerce. Any conversions allowed by coercion can also be explicitly performed by the [type cast operator](expressions/operator-expr#type-cast-expressions), `as`. Coercions are originally defined in [RFC 401](https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md) and expanded upon in [RFC 1558](https://github.com/rust-lang/rfcs/blob/master/text/1558-closure-to-fn-coercion.md). Coercion sites -------------- A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference). Possible coercion sites are: * `let` statements where an explicit type is given. For example, `&mut 42` is coerced to have type `&i8` in the following: ``` #![allow(unused)] fn main() { let _: &i8 = &mut 42; } ``` * `static` and `const` item declarations (similar to `let` statements). * Arguments for function calls The value being coerced is the actual parameter, and it is coerced to the type of the formal parameter. For example, `&mut 42` is coerced to have type `&i8` in the following: ``` fn bar(_: &i8) { } fn main() { bar(&mut 42); } ``` For method calls, the receiver (`self` parameter) can only take advantage of [unsized coercions](#unsized-coercions). * Instantiations of struct, union, or enum variant fields For example, `&mut 42` is coerced to have type `&i8` in the following: ``` struct Foo<'a> { x: &'a i8 } fn main() { Foo { x: &mut 42 }; } ``` * Function results—either the final line of a block if it is not semicolon-terminated or any expression in a `return` statement For example, `x` is coerced to have type `&dyn Display` in the following: ``` #![allow(unused)] fn main() { use std::fmt::Display; fn foo(x: &u32) -> &dyn Display { x } } ``` If the expression in one of these coercion sites is a coercion-propagating expression, then the relevant sub-expressions in that expression are also coercion sites. Propagation recurses from these new coercion sites. Propagating expressions and their relevant sub-expressions are: * Array literals, where the array has type `[U; n]`. Each sub-expression in the array literal is a coercion site for coercion to type `U`. * Array literals with repeating syntax, where the array has type `[U; n]`. The repeated sub-expression is a coercion site for coercion to type `U`. * Tuples, where a tuple is a coercion site to type `(U_0, U_1, ..., U_n)`. Each sub-expression is a coercion site to the respective type, e.g. the zeroth sub-expression is a coercion site to type `U_0`. * Parenthesized sub-expressions (`(e)`): if the expression has type `U`, then the sub-expression is a coercion site to `U`. * Blocks: if a block has type `U`, then the last expression in the block (if it is not semicolon-terminated) is a coercion site to `U`. This includes blocks which are part of control flow statements, such as `if`/`else`, if the block has a known type. Coercion types -------------- Coercion is allowed between the following types: * `T` to `U` if `T` is a [subtype](subtyping) of `U` (*reflexive case*) * `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to `T_3` (*transitive case*) Note that this is not fully supported yet. * `&mut T` to `&T` * `*mut T` to `*const T` * `&T` to `*const T` * `&mut T` to `*mut T` * `&T` or `&mut T` to `&U` if `T` implements `Deref<Target = U>`. For example: ``` use std::ops::Deref; struct CharContainer { value: char, } impl Deref for CharContainer { type Target = char; fn deref<'a>(&'a self) -> &'a char { &self.value } } fn foo(arg: &char) {} fn main() { let x = &mut CharContainer { value: 'y' }; foo(x); //&mut CharContainer is coerced to &char. } ``` * `&mut T` to `&mut U` if `T` implements `DerefMut<Target = U>`. * TyCtor(`T`) to TyCtor(`U`), where TyCtor(`T`) is one of + `&T` + `&mut T` + `*const T` + `*mut T` + `Box<T>`and where `U` can be obtained from `T` by [unsized coercion](#unsized-coercions). * Function item types to `fn` pointers * Non capturing closures to `fn` pointers * `!` to any `T` ### Unsized Coercions The following coercions are called `unsized coercions`, since they relate to converting sized types to unsized types, and are permitted in a few cases where other coercions are not, as described above. They can still happen anywhere else a coercion can occur. Two traits, [`Unsize`](../std/marker/trait.unsize) and [`CoerceUnsized`](../std/ops/trait.coerceunsized), are used to assist in this process and expose it for library use. The following coercions are built-ins and, if `T` can be coerced to `U` with one of them, then an implementation of `Unsize<U>` for `T` will be provided: * `[T; n]` to `[T]`. * `T` to `dyn U`, when `T` implements `U + Sized`, and `U` is [object safe](items/traits#object-safety). * `Foo<..., T, ...>` to `Foo<..., U, ...>`, when: + `Foo` is a struct. + `T` implements `Unsize<U>`. + The last field of `Foo` has a type involving `T`. + If that field has type `Bar<T>`, then `Bar<T>` implements `Unsized<Bar<U>>`. + T is not part of the type of any other fields. Additionally, a type `Foo<T>` can implement `CoerceUnsized<Foo<U>>` when `T` implements `Unsize<U>` or `CoerceUnsized<Foo<U>>`. This allows it to provide a unsized coercion to `Foo<U>`. > Note: While the definition of the unsized coercions and their implementation has been stabilized, the traits themselves are not yet stable and therefore can't be used directly in stable Rust. > > Least upper bound coercions --------------------------- In some contexts, the compiler must coerce together multiple types to try and find the most general type. This is called a "Least Upper Bound" coercion. LUB coercion is used and only used in the following situations: * To find the common type for a series of if branches. * To find the common type for a series of match arms. * To find the common type for array elements. * To find the type for the return type of a closure with multiple return statements. * To check the type for the return type of a function with multiple return statements. In each such case, there are a set of types `T0..Tn` to be mutually coerced to some target type `T_t`, which is unknown to start. Computing the LUB coercion is done iteratively. The target type `T_t` begins as the type `T0`. For each new type `Ti`, we consider whether * If `Ti` can be coerced to the current target type `T_t`, then no change is made. * Otherwise, check whether `T_t` can be coerced to `Ti`; if so, the `T_t` is changed to `Ti`. (This check is also conditioned on whether all of the source expressions considered thus far have implicit coercions.) * If not, try to compute a mutual supertype of `T_t` and `Ti`, which will become the new target type. ### Examples: ``` #![allow(unused)] fn main() { let (a, b, c) = (0, 1, 2); // For if branches let bar = if true { a } else if false { b } else { c }; // For match arms let baw = match 42 { 0 => a, 1 => b, _ => c, }; // For array elements let bax = [a, b, c]; // For closure with multiple return statements let clo = || { if true { a } else if false { b } else { c } }; let baz = clo(); // For type checking of function with multiple return statements fn foo() -> i32 { let (a, b, c) = (0, 1, 2); match 42 { 0 => a, 1 => b, _ => c, } } } ``` In these examples, types of the `ba*` are found by LUB coercion. And the compiler checks whether LUB coercion result of `a`, `b`, `c` is `i32` in the processing of the function `foo`. ### Caveat This description is obviously informal. Making it more precise is expected to proceed as part of a general effort to specify the Rust type checker more precisely. rust Introduction Introduction ============ This book is the primary reference for the Rust programming language. It provides three kinds of material: * Chapters that informally describe each language construct and their use. * Chapters that informally describe the memory model, concurrency model, runtime services, linkage model, and debugging facilities. * Appendix chapters providing rationale and references to languages that influenced the design. Warning: This book is incomplete. Documenting everything takes a while. See the [GitHub issues](https://github.com/rust-lang/reference/issues) for what is not documented in this book. Rust releases ------------- Rust has a new language release every six weeks. The first stable release of the language was Rust 1.0.0, followed by Rust 1.1.0 and so on. Tools (`rustc`, `cargo`, etc.) and documentation ([Standard library](../std/index), this book, etc.) are released with the language release. The latest release of this book, matching the latest Rust version, can always be found at [https://doc.rust-lang.org/reference/](index). Prior versions can be found by adding the Rust version before the "reference" directory. For example, the Reference for Rust 1.49.0 is located at [https://doc.rust-lang.org/1.49.0/reference/](https://doc.rust-lang.org/1.49.0/reference/index.html). What *The Reference* is not --------------------------- This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate [book](../index) is available to help acquire such background familiarity. This book also does not serve as a reference to the [standard library](../std/index) included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you're looking for may be there, not here. Similarly, this book does not usually document the specifics of `rustc` as a tool or of Cargo. `rustc` has its own [book](https://doc.rust-lang.org/rustc/index.html). Cargo has a [book](https://doc.rust-lang.org/cargo/index.html) that contains a [reference](https://doc.rust-lang.org/cargo/reference/index.html). There are a few pages such as <linkage> that still describe how `rustc` works. This book also only serves as a reference to what is available in stable Rust. For unstable features being worked on, see the [Unstable Book](https://doc.rust-lang.org/unstable-book/index.html). Rust compilers, including `rustc`, will perform optimizations. The reference does not specify what optimizations are allowed or disallowed. Instead, think of the compiled program as a black box. You can only probe by running it, feeding it input and observing its output. Everything that happens that way must conform to what the reference says. Finally, this book is not normative. It may include details that are specific to `rustc` itself, and should not be taken as a specification for the Rust language. We intend to produce such a book someday, and until then, the reference is the closest thing we have to one. How to use this book -------------------- This book does not assume you are reading this book sequentially. Each chapter generally can be read standalone, but will cross-link to other chapters for facets of the language they refer to, but do not discuss. There are two main ways to read this document. The first is to answer a specific question. If you know which chapter answers that question, you can jump to that chapter in the table of contents. Otherwise, you can press `s` or click the magnifying glass on the top bar to search for keywords related to your question. For example, say you wanted to know when a temporary value created in a let statement is dropped. If you didn't already know that the [lifetime of temporaries](expressions#temporaries) is defined in the [expressions chapter](expressions), you could search "temporary let" and the first search result will take you to that section. The second is to generally improve your knowledge of a facet of the language. In that case, just browse the table of contents until you see something you want to know more about, and just start reading. If a link looks interesting, click it, and read about that section. That said, there is no wrong way to read this book. Read it however you feel helps you best. ### Conventions Like all technical books, this book has certain conventions in how it displays information. These conventions are documented here. * Statements that define a term contain that term in *italics*. Whenever that term is used outside of that chapter, it is usually a link to the section that has this definition. An *example term* is an example of a term being defined. * Differences in the language by which edition the crate is compiled under are in a blockquote that start with the words "Edition Differences:" in **bold**. > **Edition Differences**: In the 2015 edition, this syntax is valid that is disallowed as of the 2018 edition. > > * Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in blockquotes that start with the word "Note:" in **bold**. > **Note**: This is an example note. > > * Warnings that show unsound behavior in the language or possibly confusing interactions of language features are in a special warning box. Warning: This is an example warning. * Code snippets inline in the text are inside `<code>` tags. Longer code examples are in a syntax highlighted box that has controls for copying, executing, and showing hidden lines in the top right corner. ``` // This is a hidden line. fn main() { println!("This is a code example"); } ``` All examples are written for the latest edition unless otherwise stated. * The grammar and lexical structure is in blockquotes with either "Lexer" or "Syntax" in **bold superscript** as the first line. > **Syntax** > *ExampleGrammar*: > `~` [*Expression*](expressions) > | `box` [*Expression*](expressions) > > See [Notation](notation) for more detail. Contributing ------------ We welcome contributions of all kinds. You can contribute to this book by opening an issue or sending a pull request to [the Rust Reference repository](https://github.com/rust-lang/reference/). If this book does not answer your question, and you think its answer is in scope of it, please do not hesitate to [file an issue](https://github.com/rust-lang/reference/issues) or ask about it in the `t-lang/doc` stream on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/237824-t-lang.2Fdoc). Knowing what people use this book for the most helps direct our attention to making those sections the best that they can be. We also want the reference to be as normative as possible, so if you see anything that is wrong or is non-normative but not specifically called out, please also [file an issue](https://github.com/rust-lang/reference/issues). rust Patterns Patterns ======== > **Syntax** > *Pattern* : > `|`? *PatternNoTopAlt* ( `|` *PatternNoTopAlt* )\* > > *PatternNoTopAlt* : > *PatternWithoutRange* > | [*RangePattern*](#range-patterns) > > *PatternWithoutRange* : > [*LiteralPattern*](#literal-patterns) > | [*IdentifierPattern*](#identifier-patterns) > | [*WildcardPattern*](#wildcard-pattern) > | [*RestPattern*](#rest-patterns) > | [*ReferencePattern*](#reference-patterns) > | [*StructPattern*](#struct-patterns) > | [*TupleStructPattern*](#tuple-struct-patterns) > | [*TuplePattern*](#tuple-patterns) > | [*GroupedPattern*](#grouped-patterns) > | [*SlicePattern*](#slice-patterns) > | [*PathPattern*](#path-patterns) > | [*MacroInvocation*](macros#macro-invocation) > > Patterns are used to match values against structures and to, optionally, bind variables to values inside these structures. They are also used in variable declarations and parameters for functions and closures. The pattern in the following example does four things: * Tests if `person` has the `car` field filled with something. * Tests if the person's `age` field is between 13 and 19, and binds its value to the `person_age` variable. * Binds a reference to the `name` field to the variable `person_name`. * Ignores the rest of the fields of `person`. The remaining fields can have any value and are not bound to any variables. ``` #![allow(unused)] fn main() { struct Car; struct Computer; struct Person { name: String, car: Option<Car>, computer: Option<Computer>, age: u8, } let person = Person { name: String::from("John"), car: Some(Car), computer: None, age: 15, }; if let Person { car: Some(_), age: person_age @ 13..=19, name: ref person_name, .. } = person { println!("{} has a car and is {} years old.", person_name, person_age); } } ``` Patterns are used in: * [`let` declarations](statements#let-statements) * [Function](items/functions) and [closure](expressions/closure-expr) parameters * [`match` expressions](expressions/match-expr) * [`if let` expressions](expressions/if-expr) * [`while let` expressions](expressions/loop-expr#predicate-pattern-loops) * [`for` expressions](expressions/loop-expr#iterator-loops) Destructuring ------------- Patterns can be used to *destructure* [structs](items/structs), [enums](items/enumerations), and [tuples](types/tuple). Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values. In a pattern whose [scrutinee](glossary#scrutinee) expression has a `struct`, `enum` or `tuple` type, a placeholder (`_`) stands in for a *single* data field, whereas a wildcard `..` stands in for *all* the remaining fields of a particular variant. When destructuring a data structure with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`. ``` #![allow(unused)] fn main() { enum Message { Quit, WriteString(String), Move { x: i32, y: i32 }, ChangeColor(u8, u8, u8), } let message = Message::Quit; match message { Message::Quit => println!("Quit"), Message::WriteString(write) => println!("{}", &write), Message::Move{ x, y: 0 } => println!("move {} horizontally", x), Message::Move{ .. } => println!("other move"), Message::ChangeColor { 0: red, 1: green, 2: _ } => { println!("color change, red: {}, green: {}", red, green); } }; } ``` Refutability ------------ A pattern is said to be *refutable* when it has the possibility of not being matched by the value it is being matched against. *Irrefutable* patterns, on the other hand, always match the value they are being matched against. Examples: ``` #![allow(unused)] fn main() { let (x, y) = (1, 2); // "(x, y)" is an irrefutable pattern if let (a, 3) = (1, 2) { // "(a, 3)" is refutable, and will not match panic!("Shouldn't reach here"); } else if let (a, 4) = (3, 4) { // "(a, 4)" is refutable, and will match println!("Matched ({}, 4)", a); } } ``` Literal patterns ---------------- > **Syntax** > *LiteralPattern* : > `true` | `false` > | [CHAR\_LITERAL](tokens#character-literals) > | [BYTE\_LITERAL](tokens#byte-literals) > | [STRING\_LITERAL](tokens#string-literals) > | [RAW\_STRING\_LITERAL](tokens#raw-string-literals) > | [BYTE\_STRING\_LITERAL](tokens#byte-string-literals) > | [RAW\_BYTE\_STRING\_LITERAL](tokens#raw-byte-string-literals) > | `-`? [INTEGER\_LITERAL](tokens#integer-literals) > | `-`? [FLOAT\_LITERAL](tokens#floating-point-literals) > > *Literal patterns* match exactly the same value as what is created by the literal. Since negative numbers are not [literals](expressions/literal-expr), literal patterns also accept an optional minus sign before the literal, which acts like the negation operator. Floating-point literals are currently accepted, but due to the complexity of comparing them, they are going to be forbidden on literal patterns in a future version of Rust (see [issue #41620](https://github.com/rust-lang/rust/issues/41620)). Literal patterns are always refutable. Examples: ``` #![allow(unused)] fn main() { for i in -2..5 { match i { -1 => println!("It's minus one"), 1 => println!("It's a one"), 2|4 => println!("It's either a two or a four"), _ => println!("Matched none of the arms"), } } } ``` Identifier patterns ------------------- > **Syntax** > *IdentifierPattern* : > `ref`? `mut`? [IDENTIFIER](identifiers) (`@` [*PatternNoTopAlt*](#patterns) ) ? > > Identifier patterns bind the value they match to a variable. The identifier must be unique within the pattern. The variable will shadow any variables of the same name in scope. The scope of the new binding depends on the context of where the pattern is used (such as a `let` binding or a `match` arm). Patterns that consist of only an identifier, possibly with a `mut`, match any value and bind it to that identifier. This is the most commonly used pattern in variable declarations and parameters for functions and closures. ``` #![allow(unused)] fn main() { let mut variable = 10; fn sum(x: i32, y: i32) -> i32 { x + y } } ``` To bind the matched value of a pattern to a variable, use the syntax `variable @ subpattern`. For example, the following binds the value 2 to `e` (not the entire range: the range here is a range subpattern). ``` #![allow(unused)] fn main() { let x = 2; match x { e @ 1 ..= 5 => println!("got a range element {}", e), _ => println!("anything"), } } ``` By default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements [`Copy`](special-types-and-traits#copy). This can be changed to bind to a reference by using the `ref` keyword, or to a mutable reference using `ref mut`. For example: ``` #![allow(unused)] fn main() { let a = Some(10); match a { None => (), Some(value) => (), } match a { None => (), Some(ref value) => (), } } ``` In the first match expression, the value is copied (or moved). In the second match, a reference to the same memory location is bound to the variable value. This syntax is needed because in destructuring subpatterns the `&` operator can't be applied to the value's fields. For example, the following is not valid: ``` #![allow(unused)] fn main() { struct Person { name: String, age: u8, } let value = Person { name: String::from("John"), age: 23 }; if let Person { name: &person_name, age: 18..=150 } = value { } } ``` To make it valid, write the following: ``` #![allow(unused)] fn main() { struct Person { name: String, age: u8, } let value = Person { name: String::from("John"), age: 23 }; if let Person {name: ref person_name, age: 18..=150 } = value { } } ``` Thus, `ref` is not something that is being matched against. Its objective is exclusively to make the matched binding a reference, instead of potentially copying or moving what was matched. [Path patterns](#path-patterns) take precedence over identifier patterns. It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant. Identifier patterns are irrefutable if the `@` subpattern is irrefutable or the subpattern is not specified. ### Binding modes To service better ergonomics, patterns operate in different *binding modes* in order to make it easier to bind references to values. When a reference value is matched by a non-reference pattern, it will be automatically treated as a `ref` or `ref mut` binding. Example: ``` #![allow(unused)] fn main() { let x: &Option<i32> = &Some(3); if let Some(y) = x { // y was converted to `ref y` and its type is &i32 } } ``` *Non-reference patterns* include all patterns except bindings, [wildcard patterns](#wildcard-pattern) (`_`), [`const` patterns](#path-patterns) of reference types, and [reference patterns](#reference-patterns). If a binding pattern does not explicitly have `ref`, `ref mut`, or `mut`, then it uses the *default binding mode* to determine how the variable is bound. The default binding mode starts in "move" mode which uses move semantics. When matching a pattern, the compiler starts from the outside of the pattern and works inwards. Each time a reference is matched using a non-reference pattern, it will automatically dereference the value and update the default binding mode. References will set the default binding mode to `ref`. Mutable references will set the mode to `ref mut` unless the mode is already `ref` in which case it remains `ref`. If the automatically dereferenced value is still a reference, it is dereferenced and this process repeats. Move bindings and reference bindings can be mixed together in the same pattern, doing so will result in partial move of the object bound to and the object cannot be used afterwards. This applies only if the type cannot be copied. In the example below, `name` is moved out of `person`, trying to use `person` as a whole or `person.name` would result in an error because of *partial move*. Example: ``` #![allow(unused)] fn main() { struct Person { name: String, age: u8, } let person = Person{ name: String::from("John"), age: 23 }; // `name` is moved from person and `age` referenced let Person { name, ref age } = person; } ``` Wildcard pattern ---------------- > **Syntax** > *WildcardPattern* : > `_` > > The *wildcard pattern* (an underscore symbol) matches any value. It is used to ignore values when they don't matter. Inside other patterns it matches a single data field (as opposed to the `..` which matches the remaining fields). Unlike identifier patterns, it does not copy, move or borrow the value it matches. Examples: ``` #![allow(unused)] fn main() { let x = 20; let (a, _) = (10, x); // the x is always matched by _ assert_eq!(a, 10); // ignore a function/closure param let real_part = |a: f64, _: f64| { a }; // ignore a field from a struct struct RGBA { r: f32, g: f32, b: f32, a: f32, } let color = RGBA{r: 0.4, g: 0.1, b: 0.9, a: 0.5}; let RGBA{r: red, g: green, b: blue, a: _} = color; assert_eq!(color.r, red); assert_eq!(color.g, green); assert_eq!(color.b, blue); // accept any Some, with any value let x = Some(10); if let Some(_) = x {} } ``` The wildcard pattern is always irrefutable. Rest patterns ------------- > **Syntax** > *RestPattern* : > `..` > > The *rest pattern* (the `..` token) acts as a variable-length pattern which matches zero or more elements that haven't been matched already before and after. It may only be used in [tuple](#tuple-patterns), [tuple struct](#tuple-struct-patterns), and [slice](#slice-patterns) patterns, and may only appear once as one of the elements in those patterns. It is also allowed in an [identifier pattern](#identifier-patterns) for [slice patterns](#slice-patterns) only. The rest pattern is always irrefutable. Examples: ``` #![allow(unused)] fn main() { let words = vec!["a", "b", "c"]; let slice = &words[..]; match slice { [] => println!("slice is empty"), [one] => println!("single element {}", one), [head, tail @ ..] => println!("head={} tail={:?}", head, tail), } match slice { // Ignore everything but the last element, which must be "!". [.., "!"] => println!("!!!"), // `start` is a slice of everything except the last element, which must be "z". [start @ .., "z"] => println!("starts with: {:?}", start), // `end` is a slice of everything but the first element, which must be "a". ["a", end @ ..] => println!("ends with: {:?}", end), // 'whole' is the entire slice and `last` is the final element whole @ [.., last] => println!("the last element of {:?} is {}", whole, last), rest => println!("{:?}", rest), } if let [.., penultimate, _] = slice { println!("next to last is {}", penultimate); } let tuple = (1, 2, 3, 4, 5); // Rest patterns may also be used in tuple and tuple struct patterns. match tuple { (1, .., y, z) => println!("y={} z={}", y, z), (.., 5) => println!("tail must be 5"), (..) => println!("matches everything else"), } } ``` Range patterns -------------- > **Syntax** > *RangePattern* : > *InclusiveRangePattern* > | *HalfOpenRangePattern* > | *ObsoleteRangePattern* > > *InclusiveRangePattern* : > *RangePatternBound* `..=` *RangePatternBound* > > *HalfOpenRangePattern* : > | *RangePatternBound* `..` > > *ObsoleteRangePattern* : > *RangePatternBound* `...` *RangePatternBound* > > *RangePatternBound* : > [CHAR\_LITERAL](tokens#character-literals) > | [BYTE\_LITERAL](tokens#byte-literals) > | `-`? [INTEGER\_LITERAL](tokens#integer-literals) > | `-`? [FLOAT\_LITERAL](tokens#floating-point-literals) > | [*PathExpression*](expressions/path-expr) > > Range patterns match values within the range defined by their bounds. A range pattern may be closed or half-open. A range pattern is closed if it has both a lower and an upper bound, and it matches all the values between and including both of its bounds. A range pattern that is half-open is written with a lower bound but not an upper bound, and matches any value equal to or greater than the specified lower bound. For example, a pattern `'m'..='p'` will match only the values `'m'`, `'n'`, `'o'`, and `'p'`. For an integer the pattern `1..` will match 9, or 9001, or 9007199254740991 (if it is of an appropriate size), but not 0, and not negative numbers for signed integers. The bounds can be literals or paths that point to constant values. A half-open range pattern in the style `a..` cannot be used to match within the context of a slice. A pattern `a..=b` must always have a ≤ b. It is an error to have a range pattern `10..=0`, for example. Range patterns only work on scalar types. The accepted types are: * Integer types (u8, i8, u16, i16, usize, isize, etc.). * Character types (char). * Floating point types (f32 and f64). This is being deprecated and will not be available in a future version of Rust (see [issue #41620](https://github.com/rust-lang/rust/issues/41620)). Examples: ``` #![allow(unused)] fn main() { let c = 'f'; let valid_variable = match c { 'a'..='z' => true, 'A'..='Z' => true, 'α'..='ω' => true, _ => false, }; let ph = 10; println!("{}", match ph { 0..=6 => "acid", 7 => "neutral", 8..=14 => "base", _ => unreachable!(), }); let uint: u32 = 5; match uint { 0 => "zero!", 1.. => "positive number!", }; // using paths to constants: const TROPOSPHERE_MIN : u8 = 6; const TROPOSPHERE_MAX : u8 = 20; const STRATOSPHERE_MIN : u8 = TROPOSPHERE_MAX + 1; const STRATOSPHERE_MAX : u8 = 50; const MESOSPHERE_MIN : u8 = STRATOSPHERE_MAX + 1; const MESOSPHERE_MAX : u8 = 85; let altitude = 70; println!("{}", match altitude { TROPOSPHERE_MIN..=TROPOSPHERE_MAX => "troposphere", STRATOSPHERE_MIN..=STRATOSPHERE_MAX => "stratosphere", MESOSPHERE_MIN..=MESOSPHERE_MAX => "mesosphere", _ => "outer space, maybe", }); pub mod binary { pub const MEGA : u64 = 1024*1024; pub const GIGA : u64 = 1024*1024*1024; } let n_items = 20_832_425; let bytes_per_item = 12; if let size @ binary::MEGA..=binary::GIGA = n_items * bytes_per_item { println!("It fits and occupies {} bytes", size); } trait MaxValue { const MAX: u64; } impl MaxValue for u8 { const MAX: u64 = (1 << 8) - 1; } impl MaxValue for u16 { const MAX: u64 = (1 << 16) - 1; } impl MaxValue for u32 { const MAX: u64 = (1 << 32) - 1; } // using qualified paths: println!("{}", match 0xfacade { 0 ..= <u8 as MaxValue>::MAX => "fits in a u8", 0 ..= <u16 as MaxValue>::MAX => "fits in a u16", 0 ..= <u32 as MaxValue>::MAX => "fits in a u32", _ => "too big", }); } ``` Range patterns for (non-`usize` and -`isize`) integer and `char` types are irrefutable when they span the entire set of possible values of a type. For example, `0u8..=255u8` is irrefutable. The range of values for an integer type is the closed range from its minimum to maximum value. The range of values for a `char` type are precisely those ranges containing all Unicode Scalar Values: `'\u{0000}'..='\u{D7FF}'` and `'\u{E000}'..='\u{10FFFF}'`. > **Edition Differences**: Before the 2021 edition, closed range patterns may also be written using `...` as an alternative to `..=`, with the same meaning. > > Reference patterns ------------------ > **Syntax** > *ReferencePattern* : > (`&`|`&&`) `mut`? [*PatternWithoutRange*](#patterns) > > Reference patterns dereference the pointers that are being matched and, thus, borrow them. For example, these two matches on `x: &i32` are equivalent: ``` #![allow(unused)] fn main() { let int_reference = &3; let a = match *int_reference { 0 => "zero", _ => "some" }; let b = match int_reference { &0 => "zero", _ => "some" }; assert_eq!(a, b); } ``` The grammar production for reference patterns has to match the token `&&` to match a reference to a reference because it is a token by itself, not two `&` tokens. Adding the `mut` keyword dereferences a mutable reference. The mutability must match the mutability of the reference. Reference patterns are always irrefutable. Struct patterns --------------- > **Syntax** > *StructPattern* : > [*PathInExpression*](paths#paths-in-expressions) `{` > *StructPatternElements* ? > `}` > > *StructPatternElements* : > *StructPatternFields* (`,` | `,` *StructPatternEtCetera*)? > | *StructPatternEtCetera* > > *StructPatternFields* : > *StructPatternField* (`,` *StructPatternField*) \* > > *StructPatternField* : > [*OuterAttribute*](attributes) \* > ( > [TUPLE\_INDEX](tokens#tuple-index) `:` [*Pattern*](#patterns) > | [IDENTIFIER](identifiers) `:` [*Pattern*](#patterns) > | `ref`? `mut`? [IDENTIFIER](identifiers) > ) > > *StructPatternEtCetera* : > [*OuterAttribute*](attributes) \* > `..` > > Struct patterns match struct values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a struct. On a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of `..`: ``` #![allow(unused)] fn main() { struct Point { x: u32, y: u32, } let s = Point {x: 1, y: 1}; match s { Point {x: 10, y: 20} => (), Point {y: 10, x: 20} => (), // order doesn't matter Point {x: 10, ..} => (), Point {..} => (), } struct PointTuple ( u32, u32, ); let t = PointTuple(1, 2); match t { PointTuple {0: 10, 1: 20} => (), PointTuple {1: 10, 0: 20} => (), // order doesn't matter PointTuple {0: 10, ..} => (), PointTuple {..} => (), } } ``` If `..` is not used, it is required to match all fields: ``` #![allow(unused)] fn main() { struct Struct { a: i32, b: char, c: bool, } let mut struct_value = Struct{a: 10, b: 'X', c: false}; match struct_value { Struct{a: 10, b: 'X', c: false} => (), Struct{a: 10, b: 'X', ref c} => (), Struct{a: 10, b: 'X', ref mut c} => (), Struct{a: 10, b: 'X', c: _} => (), Struct{a: _, b: _, c: _} => (), } } ``` The `ref` and/or `mut` *IDENTIFIER* syntax matches any value and binds it to a variable with the same name as the given field. ``` #![allow(unused)] fn main() { struct Struct { a: i32, b: char, c: bool, } let struct_value = Struct{a: 10, b: 'X', c: false}; let Struct{a: x, b: y, c: z} = struct_value; // destructure all fields } ``` A struct pattern is refutable when one of its subpatterns is refutable. Tuple struct patterns --------------------- > **Syntax** > *TupleStructPattern* : > [*PathInExpression*](paths#paths-in-expressions) `(` *TupleStructItems*? `)` > > *TupleStructItems* : > [*Pattern*](#patterns) ( `,` [*Pattern*](#patterns) )\* `,`? > > Tuple struct patterns match tuple struct and enum values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a tuple struct or enum value. A tuple struct pattern is refutable when one of its subpatterns is refutable. Tuple patterns -------------- > **Syntax** > *TuplePattern* : > `(` *TuplePatternItems*? `)` > > *TuplePatternItems* : > [*Pattern*](#patterns) `,` > | [*RestPattern*](#rest-patterns) > | [*Pattern*](#patterns) (`,` [*Pattern*](#patterns))+ `,`? > > Tuple patterns match tuple values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a tuple. The form `(..)` with a single [*RestPattern*](#rest-patterns) is a special form that does not require a comma, and matches a tuple of any size. The tuple pattern is refutable when one of its subpatterns is refutable. An example of using tuple patterns: ``` #![allow(unused)] fn main() { let pair = (10, "ten"); let (a, b) = pair; assert_eq!(a, 10); assert_eq!(b, "ten"); } ``` Grouped patterns ---------------- > **Syntax** > *GroupedPattern* : > `(` [*Pattern*](#patterns) `)` > > Enclosing a pattern in parentheses can be used to explicitly control the precedence of compound patterns. For example, a reference pattern next to a range pattern such as `&0..=5` is ambiguous and is not allowed, but can be expressed with parentheses. ``` #![allow(unused)] fn main() { let int_reference = &3; match int_reference { &(0..=5) => (), _ => (), } } ``` Slice patterns -------------- > **Syntax** > *SlicePattern* : > `[` *SlicePatternItems*? `]` > > *SlicePatternItems* : > [*Pattern*](#patterns) (`,` [*Pattern*](#patterns))\* `,`? > > Slice patterns can match both arrays of fixed size and slices of dynamic size. ``` #![allow(unused)] fn main() { // Fixed size let arr = [1, 2, 3]; match arr { [1, _, _] => "starts with one", [a, b, c] => "starts with something else", }; } ``` ``` #![allow(unused)] fn main() { // Dynamic size let v = vec![1, 2, 3]; match v[..] { [a, b] => { /* this arm will not apply because the length doesn't match */ } [a, b, c] => { /* this arm will apply */ } _ => { /* this wildcard is required, since the length is not known statically */ } }; } ``` Slice patterns are irrefutable when matching an array as long as each element is irrefutable. When matching a slice, it is irrefutable only in the form with a single `..` [rest pattern](#rest-patterns) or [identifier pattern](#identifier-patterns) with the `..` rest pattern as a subpattern. Within a slice, a half-open range pattern like `a..` must be enclosed in parentheses, as in `(a..)`, to clarify it is intended to match a single value. A future version of Rust may give the non-parenthesized version an alternate meaning. Path patterns ------------- > **Syntax** > *PathPattern* : > [*PathExpression*](expressions/path-expr) > > *Path patterns* are patterns that refer either to constant values or to structs or enum variants that have no fields. Unqualified path patterns can refer to: * enum variants * structs * constants * associated constants Qualified path patterns can only refer to associated constants. Constants cannot be a union type. Struct and enum constants must have `#[derive(PartialEq, Eq)]` (not merely implemented). Path patterns are irrefutable when they refer to structs or an enum variant when the enum has only one variant or a constant whose type is irrefutable. They are refutable when they refer to refutable constants or enum variants for enums with multiple variants. Or-patterns ----------- *Or-patterns* are patterns that match on one of two or more sub-patterns (e.g. `A | B | C`). They can nest arbitrarily. Syntactically, or-patterns are allowed in any of the places where other patterns are allowed (represented by the *Pattern* production), with the exceptions of `let`-bindings and function and closure arguments (represented by the *PatternNoTopAlt* production). ### Static semantics 1. Given a pattern `p | q` at some depth for some arbitrary patterns `p` and `q`, the pattern is considered ill-formed if: * the type inferred for `p` does not unify with the type inferred for `q`, or * the same set of bindings are not introduced in `p` and `q`, or * the type of any two bindings with the same name in `p` and `q` do not unify with respect to types or binding modes.Unification of types is in all instances aforementioned exact and implicit [type coercions](type-coercions) do not apply. 2. When type checking an expression `match e_s { a_1 => e_1, ... a_n => e_n }`, for each match arm `a_i` which contains a pattern of form `p_i | q_i`, the pattern `p_i | q_i` is considered ill formed if, at the depth `d` where it exists the fragment of `e_s` at depth `d`, the type of the expression fragment does not unify with `p_i | q_i`. 3. With respect to exhaustiveness checking, a pattern `p | q` is considered to cover `p` as well as `q`. For some constructor `c(x, ..)` the distributive law applies such that `c(p | q, ..rest)` covers the same set of value as `c(p, ..rest) | c(q, ..rest)` does. This can be applied recursively until there are no more nested patterns of form `p | q` other than those that exist at the top level. Note that by *"constructor"* we do not refer to tuple struct patterns, but rather we refer to a pattern for any product type. This includes enum variants, tuple structs, structs with named fields, arrays, tuples, and slices. ### Dynamic semantics 1. The dynamic semantics of pattern matching a scrutinee expression `e_s` against a pattern `c(p | q, ..rest)` at depth `d` where `c` is some constructor, `p` and `q` are arbitrary patterns, and `rest` is optionally any remaining potential factors in `c`, is defined as being the same as that of `c(p, ..rest) | c(q, ..rest)`. ### Precedence with other undelimited patterns As shown elsewhere in this chapter, there are several types of patterns that are syntactically undelimited, including identifier patterns, reference patterns, and or-patterns. Or-patterns always have the lowest-precedence. This allows us to reserve syntactic space for a possible future type ascription feature and also to reduce ambiguity. For example, `x @ A(..) | B(..)` will result in an error that `x` is not bound in all patterns, `&A(x) | B(x)` will result in a type mismatch between `x` in the different subpatterns.
programming_docs
rust Tokens Tokens ====== Tokens are primitive productions in the grammar defined by regular (non-recursive) languages. Rust source input can be broken down into the following kinds of tokens: * [Keywords](keywords) * [Identifiers](identifiers) * [Literals](#literals) * [Lifetimes](#lifetimes-and-loop-labels) * [Punctuation](#punctuation) * [Delimiters](#delimiters) Within this documentation's grammar, "simple" tokens are given in [string table production](notation#string-table-productions) form, and appear in `monospace` font. Literals -------- Literals are tokens used in [literal expressions](expressions/literal-expr). ### Examples #### Characters and strings | | Example | `#` sets\* | Characters | Escapes | | --- | --- | --- | --- | --- | | [Character](#character-literals) | `'H'` | 0 | All Unicode | [Quote](#quote-escapes) & [ASCII](#ascii-escapes) & [Unicode](#unicode-escapes) | | [String](#string-literals) | `"hello"` | 0 | All Unicode | [Quote](#quote-escapes) & [ASCII](#ascii-escapes) & [Unicode](#unicode-escapes) | | [Raw string](#raw-string-literals) | `r#"hello"#` | <256 | All Unicode | `N/A` | | [Byte](#byte-literals) | `b'H'` | 0 | All ASCII | [Quote](#quote-escapes) & [Byte](#byte-escapes) | | [Byte string](#byte-string-literals) | `b"hello"` | 0 | All ASCII | [Quote](#quote-escapes) & [Byte](#byte-escapes) | | [Raw byte string](#raw-byte-string-literals) | `br#"hello"#` | <256 | All ASCII | `N/A` | \* The number of `#`s on each side of the same literal must be equivalent. #### ASCII escapes | | Name | | --- | --- | | `\x41` | 7-bit character code (exactly 2 digits, up to 0x7F) | | `\n` | Newline | | `\r` | Carriage return | | `\t` | Tab | | `\\` | Backslash | | `\0` | Null | #### Byte escapes | | Name | | --- | --- | | `\x7F` | 8-bit character code (exactly 2 digits) | | `\n` | Newline | | `\r` | Carriage return | | `\t` | Tab | | `\\` | Backslash | | `\0` | Null | #### Unicode escapes | | Name | | --- | --- | | `\u{7FFF}` | 24-bit Unicode character code (up to 6 digits) | #### Quote escapes | | Name | | --- | --- | | `\'` | Single quote | | `\"` | Double quote | #### Numbers | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes | | --- | --- | --- | --- | | Decimal integer | `98_222` | `N/A` | Integer suffixes | | Hex integer | `0xff` | `N/A` | Integer suffixes | | Octal integer | `0o77` | `N/A` | Integer suffixes | | Binary integer | `0b1111_0000` | `N/A` | Integer suffixes | | Floating-point | `123.0E+77` | `Optional` | Floating-point suffixes | `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64` #### Suffixes A suffix is a sequence of characters following the primary part of a literal (without intervening whitespace), of the same form as a non-raw identifier or keyword. Any kind of literal (string, integer, etc) with any suffix is valid as a token, and can be passed to a macro without producing an error. The macro itself will decide how to interpret such a token and whether to produce an error or not. ``` #![allow(unused)] fn main() { macro_rules! blackhole { ($tt:tt) => () } blackhole!("string"suffix); // OK } ``` However, suffixes on literal tokens parsed as Rust code are restricted. Any suffixes are rejected on non-numeric literal tokens, and numeric literal tokens are accepted only with suffixes from the list below. | Integer | Floating-point | | --- | --- | | `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, `isize` | `f32`, `f64` | ### Character and string literals #### Character literals > **Lexer** > CHAR\_LITERAL : > `'` ( ~[`'` `\` \n \r \t] | QUOTE\_ESCAPE | ASCII\_ESCAPE | UNICODE\_ESCAPE ) `'` > > QUOTE\_ESCAPE : > `\'` | `\"` > > ASCII\_ESCAPE : > `\x` OCT\_DIGIT HEX\_DIGIT > | `\n` | `\r` | `\t` | `\\` | `\0` > > UNICODE\_ESCAPE : > `\u{` ( HEX\_DIGIT `_`\* )1..6 `}` > > A *character literal* is a single Unicode character enclosed within two `U+0027` (single-quote) characters, with the exception of `U+0027` itself, which must be *escaped* by a preceding `U+005C` character (`\`). #### String literals > **Lexer** > STRING\_LITERAL : > `"` ( > ~[`"` `\` *IsolatedCR*] > | QUOTE\_ESCAPE > | ASCII\_ESCAPE > | UNICODE\_ESCAPE > | STRING\_CONTINUE > )\* `"` > > STRING\_CONTINUE : > `\` *followed by* \n > > A *string literal* is a sequence of any Unicode characters enclosed within two `U+0022` (double-quote) characters, with the exception of `U+0022` itself, which must be *escaped* by a preceding `U+005C` character (`\`). Line-breaks are allowed in string literals. A line-break is either a newline (`U+000A`) or a pair of carriage return and newline (`U+000D`, `U+000A`). Both byte sequences are normally translated to `U+000A`, but as a special exception, when an unescaped `U+005C` character (`\`) occurs immediately before a line break, then the line break character(s), and all immediately following (`U+0020`), `\t` (`U+0009`), `\n` (`U+000A`) and `\r` (`U+0000D`) characters are ignored. Thus `a`, `b` and `c` are equal: ``` #![allow(unused)] fn main() { let a = "foobar"; let b = "foo\ bar"; let c = "foo\ bar"; assert_eq!(a, b); assert_eq!(b, c); } ``` > Note: Rust skipping additional newlines (like in example `c`) is potentially confusing and unexpected. This behavior may be adjusted in the future. Until a decision is made, it is recommended to avoid relying on this, i.e. skipping multiple newlines with line continuations. See [this issue](https://github.com/rust-lang/reference/pull/1042) for more information. > > #### Character escapes Some additional *escapes* are available in either character or non-raw string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms: * A *7-bit code point escape* starts with `U+0078` (`x`) and is followed by exactly two *hex digits* with value up to `0x7F`. It denotes the ASCII character with value equal to the provided hex value. Higher values are not permitted because it is ambiguous whether they mean Unicode code points or byte values. * A *24-bit code point escape* starts with `U+0075` (`u`) and is followed by up to six *hex digits* surrounded by braces `U+007B` (`{`) and `U+007D` (`}`). It denotes the Unicode code point equal to the provided hex value. * A *whitespace escape* is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the Unicode values `U+000A` (LF), `U+000D` (CR) or `U+0009` (HT) respectively. * The *null escape* is the character `U+0030` (`0`) and denotes the Unicode value `U+0000` (NUL). * The *backslash escape* is the character `U+005C` (`\`) which must be escaped in order to denote itself. #### Raw string literals > **Lexer** > RAW\_STRING\_LITERAL : > `r` RAW\_STRING\_CONTENT > > RAW\_STRING\_CONTENT : > `"` ( ~ *IsolatedCR* )\* (non-greedy) `"` > | `#` RAW\_STRING\_CONTENT `#` > > Raw string literals do not process any escapes. They start with the character `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`) and a `U+0022` (double-quote) character. The *raw string body* can contain any sequence of Unicode characters and is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character. All Unicode characters contained in the raw string body represent themselves, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning. Examples for string literals: ``` #![allow(unused)] fn main() { "foo"; r"foo"; // foo "\"foo\""; r#""foo""#; // "foo" "foo #\"# bar"; r##"foo #"# bar"##; // foo #"# bar "\x52"; "R"; r"R"; // R "\\x52"; r"\x52"; // \x52 } ``` ### Byte and byte string literals #### Byte literals > **Lexer** > BYTE\_LITERAL : > `b'` ( ASCII\_FOR\_CHAR | BYTE\_ESCAPE ) `'` > > ASCII\_FOR\_CHAR : > *any ASCII (i.e. 0x00 to 0x7F), except* `'`, `\`, \n, \r or \t > > BYTE\_ESCAPE : > `\x` HEX\_DIGIT HEX\_DIGIT > | `\n` | `\r` | `\t` | `\\` | `\0` | `\'` | `\"` > > A *byte literal* is a single ASCII character (in the `U+0000` to `U+007F` range) or a single *escape* preceded by the characters `U+0062` (`b`) and `U+0027` (single-quote), and followed by the character `U+0027`. If the character `U+0027` is present within the literal, it must be *escaped* by a preceding `U+005C` (`\`) character. It is equivalent to a `u8` unsigned 8-bit integer *number literal*. #### Byte string literals > **Lexer** > BYTE\_STRING\_LITERAL : > `b"` ( ASCII\_FOR\_STRING | BYTE\_ESCAPE | STRING\_CONTINUE )\* `"` > > ASCII\_FOR\_STRING : > *any ASCII (i.e 0x00 to 0x7F), except* `"`, `\` *and IsolatedCR* > > A non-raw *byte string literal* is a sequence of ASCII characters and *escapes*, preceded by the characters `U+0062` (`b`) and `U+0022` (double-quote), and followed by the character `U+0022`. If the character `U+0022` is present within the literal, it must be *escaped* by a preceding `U+005C` (`\`) character. Alternatively, a byte string literal can be a *raw byte string literal*, defined below. The type of a byte string literal of length `n` is `&'static [u8; n]`. Some additional *escapes* are available in either byte or non-raw byte string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms: * A *byte escape* escape starts with `U+0078` (`x`) and is followed by exactly two *hex digits*. It denotes the byte equal to the provided hex value. * A *whitespace escape* is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF), `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively. * The *null escape* is the character `U+0030` (`0`) and denotes the byte value `0x00` (ASCII NUL). * The *backslash escape* is the character `U+005C` (`\`) which must be escaped in order to denote its ASCII encoding `0x5C`. #### Raw byte string literals > **Lexer** > RAW\_BYTE\_STRING\_LITERAL : > `br` RAW\_BYTE\_STRING\_CONTENT > > RAW\_BYTE\_STRING\_CONTENT : > `"` ASCII\* (non-greedy) `"` > | `#` RAW\_BYTE\_STRING\_CONTENT `#` > > ASCII : > *any ASCII (i.e. 0x00 to 0x7F)* > > Raw byte string literals do not process any escapes. They start with the character `U+0062` (`b`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The *raw string body* can contain any sequence of ASCII characters and is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character. A raw byte string literal can not contain any non-ASCII byte. All characters contained in the raw string body represent their ASCII encoding, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning. Examples for byte string literals: ``` #![allow(unused)] fn main() { b"foo"; br"foo"; // foo b"\"foo\""; br#""foo""#; // "foo" b"foo #\"# bar"; br##"foo #"# bar"##; // foo #"# bar b"\x52"; b"R"; br"R"; // R b"\\x52"; br"\x52"; // \x52 } ``` ### Number literals A *number literal* is either an *integer literal* or a *floating-point literal*. The grammar for recognizing the two kinds of literals is mixed. #### Integer literals > **Lexer** > INTEGER\_LITERAL : > ( DEC\_LITERAL | BIN\_LITERAL | OCT\_LITERAL | HEX\_LITERAL ) INTEGER\_SUFFIX? > > DEC\_LITERAL : > DEC\_DIGIT (DEC\_DIGIT|`_`)\* > > BIN\_LITERAL : > `0b` (BIN\_DIGIT|`_`)\* BIN\_DIGIT (BIN\_DIGIT|`_`)\* > > OCT\_LITERAL : > `0o` (OCT\_DIGIT|`_`)\* OCT\_DIGIT (OCT\_DIGIT|`_`)\* > > HEX\_LITERAL : > `0x` (HEX\_DIGIT|`_`)\* HEX\_DIGIT (HEX\_DIGIT|`_`)\* > > BIN\_DIGIT : [`0`-`1`] > > OCT\_DIGIT : [`0`-`7`] > > DEC\_DIGIT : [`0`-`9`] > > HEX\_DIGIT : [`0`-`9` `a`-`f` `A`-`F`] > > INTEGER\_SUFFIX : > `u8` | `u16` | `u32` | `u64` | `u128` | `usize` > | `i8` | `i16` | `i32` | `i64` | `i128` | `isize` > > An *integer literal* has one of four forms: * A *decimal literal* starts with a *decimal digit* and continues with any mixture of *decimal digits* and *underscores*. * A *hex literal* starts with the character sequence `U+0030` `U+0078` (`0x`) and continues as any mixture (with at least one digit) of hex digits and underscores. * An *octal literal* starts with the character sequence `U+0030` `U+006F` (`0o`) and continues as any mixture (with at least one digit) of octal digits and underscores. * A *binary literal* starts with the character sequence `U+0030` `U+0062` (`0b`) and continues as any mixture (with at least one digit) of binary digits and underscores. Like any literal, an integer literal may be followed (immediately, without any spaces) by an *integer suffix*, which must be the name of one of the [primitive integer types](types/numeric): `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`. See [literal expressions](expressions/literal-expr) for the effect of these suffixes. Examples of integer literals of various forms: ``` #![allow(unused)] fn main() { #![allow(overflowing_literals)] 123; 123i32; 123u32; 123_u32; 0xff; 0xff_u8; 0x01_f32; // integer 7986, not floating-point 1.0 0x01_e3; // integer 483, not floating-point 1000.0 0o70; 0o70_i16; 0b1111_1111_1001_0000; 0b1111_1111_1001_0000i64; 0b________1; 0usize; // These are too big for their type, but are still valid tokens 128_i8; 256_u8; } ``` Note that `-1i8`, for example, is analyzed as two tokens: `-` followed by `1i8`. Examples of invalid integer literals: ``` #![allow(unused)] fn main() { // uses numbers of the wrong base 0b0102; 0o0581; // bin, hex, and octal literals must have at least one digit 0b_; 0b____; } ``` #### Tuple index > **Lexer** > TUPLE\_INDEX: > INTEGER\_LITERAL > > A tuple index is used to refer to the fields of [tuples](types/tuple), [tuple structs](items/structs), and [tuple variants](items/enumerations). Tuple indices are compared with the literal token directly. Tuple indices start with `0` and each successive index increments the value by `1` as a decimal value. Thus, only decimal values will match, and the value must not have any extra `0` prefix characters. ``` #![allow(unused)] fn main() { let example = ("dog", "cat", "horse"); let dog = example.0; let cat = example.1; // The following examples are invalid. let cat = example.01; // ERROR no field named `01` let horse = example.0b10; // ERROR no field named `0b10` } ``` > **Note**: The tuple index may include an `INTEGER_SUFFIX`, but this is not intended to be valid, and may be removed in a future version. See <https://github.com/rust-lang/rust/issues/60210> for more information. > > #### Floating-point literals > **Lexer** > FLOAT\_LITERAL : > DEC\_LITERAL `.` *(not immediately followed by `.`, `_` or an XID\_Start character)* > | DEC\_LITERAL FLOAT\_EXPONENT > | DEC\_LITERAL `.` DEC\_LITERAL FLOAT\_EXPONENT? > | DEC\_LITERAL (`.` DEC\_LITERAL)? FLOAT\_EXPONENT? FLOAT\_SUFFIX > > FLOAT\_EXPONENT : > (`e`|`E`) (`+`|`-`)? (DEC\_DIGIT|`_`)\* DEC\_DIGIT (DEC\_DIGIT|`_`)\* > > FLOAT\_SUFFIX : > `f32` | `f64` > > A *floating-point literal* has one of three forms: * A *decimal literal* followed by a period character `U+002E` (`.`). This is optionally followed by another decimal literal, with an optional *exponent*. * A single *decimal literal* followed by an *exponent*. * A single *decimal literal* (in which case a suffix is required). Like integer literals, a floating-point literal may be followed by a suffix, so long as the pre-suffix part does not end with `U+002E` (`.`). There are two valid *floating-point suffixes*: `f32` and `f64` (the names of the 32-bit and 64-bit [primitive floating-point types](types/numeric#floating-point-types)). See [literal expressions](expressions/literal-expr) for the effect of these suffixes. Examples of floating-point literals of various forms: ``` #![allow(unused)] fn main() { 123.0f64; 0.1f64; 0.1f32; 12E+99_f64; 5f32; let x: f64 = 2.; } ``` This last example is different because it is not possible to use the suffix syntax with a floating point literal ending in a period. `2.f64` would attempt to call a method named `f64` on `2`. Note that `-1.0`, for example, is analyzed as two tokens: `-` followed by `1.0`. #### Number pseudoliterals > **Lexer** > NUMBER\_PSEUDOLITERAL : > DEC\_LITERAL ( . DEC\_LITERAL )? FLOAT\_EXPONENT > ( NUMBER\_PSEUDOLITERAL\_SUFFIX | INTEGER\_SUFFIX ) > | DEC\_LITERAL . DEC\_LITERAL > ( NUMBER\_PSEUDOLITERAL\_SUFFIX\_NO\_E | INTEGER SUFFIX ) > | DEC\_LITERAL NUMBER\_PSEUDOLITERAL\_SUFFIX\_NO\_E > | ( BIN\_LITERAL | OCT\_LITERAL | HEX\_LITERAL ) > ( NUMBER\_PSEUDOLITERAL\_SUFFIX\_NO\_E | FLOAT\_SUFFIX ) > > NUMBER\_PSEUDOLITERAL\_SUFFIX : > IDENTIFIER\_OR\_KEYWORD *not matching INTEGER\_SUFFIX or FLOAT\_SUFFIX* > > NUMBER\_PSEUDOLITERAL\_SUFFIX\_NO\_E : > NUMBER\_PSEUDOLITERAL\_SUFFIX *not beginning with `e` or `E`* > > Tokenization of numeric literals allows arbitrary suffixes as described in the grammar above. These values generate valid tokens, but are not valid [literal expressions](expressions/literal-expr), so are usually an error except as macro arguments. Examples of such tokens: ``` #![allow(unused)] fn main() { 0invalidSuffix; 123AFB43; 0b010a; 0xAB_CD_EF_GH; 2.0f80; 2e5f80; 2e5e6; 2.0e5e6; 1.3e10u64; 0b1111_f32; } ``` #### Reserved forms similar to number literals > **Lexer** > RESERVED\_NUMBER : > BIN\_LITERAL [`2`-`9`​] > | OCT\_LITERAL [`8`-`9`​] > | ( BIN\_LITERAL | OCT\_LITERAL | HEX\_LITERAL ) `.` > *(not immediately followed by `.`, `_` or an XID\_Start character)* > | ( BIN\_LITERAL | OCT\_LITERAL ) `e` > | `0b` `_`\* *end of input or not BIN\_DIGIT* > | `0o` `_`\* *end of input or not OCT\_DIGIT* > | `0x` `_`\* *end of input or not HEX\_DIGIT* > | DEC\_LITERAL ( . DEC\_LITERAL)? (`e`|`E`) (`+`|`-`)? *end of input or not DEC\_DIGIT* > > The following lexical forms similar to number literals are *reserved forms*. Due to the possible ambiguity these raise, they are rejected by the tokenizer instead of being interpreted as separate tokens. * An unsuffixed binary or octal literal followed, without intervening whitespace, by a decimal digit out of the range for its radix. * An unsuffixed binary, octal, or hexadecimal literal followed, without intervening whitespace, by a period character (with the same restrictions on what follows the period as for floating-point literals). * An unsuffixed binary or octal literal followed, without intervening whitespace, by the character `e`. * Input which begins with one of the radix prefixes but is not a valid binary, octal, or hexadecimal literal (because it contains no digits). * Input which has the form of a floating-point literal with no digits in the exponent. Examples of reserved forms: ``` #![allow(unused)] fn main() { 0b0102; // this is not `0b010` followed by `2` 0o1279; // this is not `0o127` followed by `9` 0x80.0; // this is not `0x80` followed by `.` and `0` 0b101e; // this is not a pseudoliteral, or `0b101` followed by `e` 0b; // this is not a pseudoliteral, or `0` followed by `b` 0b_; // this is not a pseudoliteral, or `0` followed by `b_` 2e; // this is not a pseudoliteral, or `2` followed by `e` 2.0e; // this is not a pseudoliteral, or `2.0` followed by `e` 2em; // this is not a pseudoliteral, or `2` followed by `em` 2.0em; // this is not a pseudoliteral, or `2.0` followed by `em` } ``` Lifetimes and loop labels ------------------------- > **Lexer** > LIFETIME\_TOKEN : > `'` [IDENTIFIER\_OR\_KEYWORD](identifiers) > | `'_` > > LIFETIME\_OR\_LABEL : > `'` [NON\_KEYWORD\_IDENTIFIER](identifiers) > > Lifetime parameters and [loop labels](expressions/loop-expr) use LIFETIME\_OR\_LABEL tokens. Any LIFETIME\_TOKEN will be accepted by the lexer, and for example, can be used in macros. Punctuation ----------- Punctuation symbol tokens are listed here for completeness. Their individual usages and meanings are defined in the linked pages. | Symbol | Name | Usage | | --- | --- | --- | | `+` | Plus | [Addition](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Trait Bounds](trait-bounds), [Macro Kleene Matcher](macros-by-example) | | `-` | Minus | [Subtraction](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Negation](expressions/operator-expr#negation-operators) | | `*` | Star | [Multiplication](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Dereference](expressions/operator-expr#the-dereference-operator), [Raw Pointers](types/pointer#raw-pointers-const-and-mut), [Macro Kleene Matcher](macros-by-example), [Use wildcards](items/use-declarations) | | `/` | Slash | [Division](expressions/operator-expr#arithmetic-and-logical-binary-operators) | | `%` | Percent | [Remainder](expressions/operator-expr#arithmetic-and-logical-binary-operators) | | `^` | Caret | [Bitwise and Logical XOR](expressions/operator-expr#arithmetic-and-logical-binary-operators) | | `!` | Not | [Bitwise and Logical NOT](expressions/operator-expr#negation-operators), [Macro Calls](macros-by-example), [Inner Attributes](attributes), [Never Type](types/never), [Negative impls](items/implementations) | | `&` | And | [Bitwise and Logical AND](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Borrow](expressions/operator-expr#borrow-operators), [References](types/pointer), [Reference patterns](patterns#reference-patterns) | | `|` | Or | [Bitwise and Logical OR](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Closures](expressions/closure-expr), Patterns in [match](expressions/match-expr), [if let](expressions/if-expr#if-let-expressions), and [while let](expressions/loop-expr#predicate-pattern-loops) | | `&&` | AndAnd | [Lazy AND](expressions/operator-expr#lazy-boolean-operators), [Borrow](expressions/operator-expr#borrow-operators), [References](types/pointer), [Reference patterns](patterns#reference-patterns) | | `||` | OrOr | [Lazy OR](expressions/operator-expr#lazy-boolean-operators), [Closures](expressions/closure-expr) | | `<<` | Shl | [Shift Left](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Nested Generics](items/generics) | | `>>` | Shr | [Shift Right](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Nested Generics](items/generics) | | `+=` | PlusEq | [Addition assignment](expressions/operator-expr#compound-assignment-expressions) | | `-=` | MinusEq | [Subtraction assignment](expressions/operator-expr#compound-assignment-expressions) | | `*=` | StarEq | [Multiplication assignment](expressions/operator-expr#compound-assignment-expressions) | | `/=` | SlashEq | [Division assignment](expressions/operator-expr#compound-assignment-expressions) | | `%=` | PercentEq | [Remainder assignment](expressions/operator-expr#compound-assignment-expressions) | | `^=` | CaretEq | [Bitwise XOR assignment](expressions/operator-expr#compound-assignment-expressions) | | `&=` | AndEq | [Bitwise And assignment](expressions/operator-expr#compound-assignment-expressions) | | `|=` | OrEq | [Bitwise Or assignment](expressions/operator-expr#compound-assignment-expressions) | | `<<=` | ShlEq | [Shift Left assignment](expressions/operator-expr#compound-assignment-expressions) | | `>>=` | ShrEq | [Shift Right assignment](expressions/operator-expr#compound-assignment-expressions), [Nested Generics](items/generics) | | `=` | Eq | [Assignment](expressions/operator-expr#assignment-expressions), [Attributes](attributes), Various type definitions | | `==` | EqEq | [Equal](expressions/operator-expr#comparison-operators) | | `!=` | Ne | [Not Equal](expressions/operator-expr#comparison-operators) | | `>` | Gt | [Greater than](expressions/operator-expr#comparison-operators), [Generics](items/generics), [Paths](paths) | | `<` | Lt | [Less than](expressions/operator-expr#comparison-operators), [Generics](items/generics), [Paths](paths) | | `>=` | Ge | [Greater than or equal to](expressions/operator-expr#comparison-operators), [Generics](items/generics) | | `<=` | Le | [Less than or equal to](expressions/operator-expr#comparison-operators) | | `@` | At | [Subpattern binding](patterns#identifier-patterns) | | `_` | Underscore | [Wildcard patterns](patterns#wildcard-pattern), [Inferred types](types/inferred), Unnamed items in [constants](items/constant-items), [extern crates](items/extern-crates), [use declarations](items/use-declarations), and [destructuring assignment](expressions/underscore-expr) | | `.` | Dot | [Field access](expressions/field-expr), [Tuple index](expressions/tuple-expr#tuple-indexing-expressions) | | `..` | DotDot | [Range](expressions/range-expr), [Struct expressions](expressions/struct-expr), [Patterns](patterns), [Range Patterns](patterns#range-patterns) | | `...` | DotDotDot | [Variadic functions](items/external-blocks), [Range patterns](patterns#range-patterns) | | `..=` | DotDotEq | [Inclusive Range](expressions/range-expr), [Range patterns](patterns#range-patterns) | | `,` | Comma | Various separators | | `;` | Semi | Terminator for various items and statements, [Array types](types/array) | | `:` | Colon | Various separators | | `::` | PathSep | [Path separator](paths) | | `->` | RArrow | [Function return type](items/functions), [Closure return type](expressions/closure-expr), [Function pointer type](types/function-pointer) | | `=>` | FatArrow | [Match arms](expressions/match-expr), [Macros](macros-by-example) | | `#` | Pound | [Attributes](attributes) | | `$` | Dollar | [Macros](macros-by-example) | | `?` | Question | [Question mark operator](expressions/operator-expr#the-question-mark-operator), [Questionably sized](trait-bounds#sized), [Macro Kleene Matcher](macros-by-example) | | `~` | Tilde | The tilde operator has been unused since before Rust 1.0, but its token may still be used | Delimiters ---------- Bracket punctuation is used in various parts of the grammar. An open bracket must always be paired with a close bracket. Brackets and the tokens within them are referred to as "token trees" in [macros](macros-by-example). The three types of brackets are: | Bracket | Type | | --- | --- | | `{` `}` | Curly braces | | `[` `]` | Square brackets | | `(` `)` | Parentheses | Reserved prefixes ----------------- > **Lexer 2021+** > RESERVED\_TOKEN\_DOUBLE\_QUOTE : ( IDENTIFIER\_OR\_KEYWORD *Except `b` or `r` or `br`* | `_` ) `"` > RESERVED\_TOKEN\_SINGLE\_QUOTE : ( IDENTIFIER\_OR\_KEYWORD *Except `b`* | `_` ) `'` > RESERVED\_TOKEN\_POUND : ( IDENTIFIER\_OR\_KEYWORD *Except `r` or `br`* | `_` ) `#` > > Some lexical forms known as *reserved prefixes* are reserved for future use. Source input which would otherwise be lexically interpreted as a non-raw identifier (or a keyword or `_`) which is immediately followed by a `#`, `'`, or `"` character (without intervening whitespace) is identified as a reserved prefix. Note that raw identifiers, raw string literals, and raw byte string literals may contain a `#` character but are not interpreted as containing a reserved prefix. Similarly the `r`, `b`, and `br` prefixes used in raw string literals, byte literals, byte string literals, and raw byte string literals are not interpreted as reserved prefixes. > **Edition Differences**: Starting with the 2021 edition, reserved prefixes are reported as an error by the lexer (in particular, they cannot be passed to macros). > > Before the 2021 edition, a reserved prefixes are accepted by the lexer and interpreted as multiple tokens (for example, one token for the identifier or keyword, followed by a `#` token). > > Examples accepted in all editions: > > > ``` > #![allow(unused)] > fn main() { > macro_rules! lexes {($($_:tt)*) => {}} > lexes!{a #foo} > lexes!{continue 'foo} > lexes!{match "..." {}} > lexes!{r#let#foo} // three tokens: r#let # foo > } > > ``` > Examples accepted before the 2021 edition but rejected later: > > > ``` > #![allow(unused)] > fn main() { > macro_rules! lexes {($($_:tt)*) => {}} > lexes!{a#foo} > lexes!{continue'foo} > lexes!{match"..." {}} > } > > ``` >
programming_docs
rust Unsafe blocks Unsafe blocks ============= A block of code can be prefixed with the `unsafe` keyword, to permit calling `unsafe` functions or dereferencing raw pointers within a safe function. When a programmer has sufficient conviction that a sequence of potentially unsafe operations is actually safe, they can encapsulate that sequence (taken as a whole) within an `unsafe` block. The compiler will consider uses of such code safe, in the surrounding context. Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features not directly present in the language. For example, Rust provides the language features necessary to implement memory-safe concurrency in the language but the implementation of threads and message passing is in the standard library. Rust's type system is a conservative approximation of the dynamic safety requirements, so in some cases there is a performance cost to using safe code. For example, a doubly-linked list is not a tree structure and can only be represented with reference-counted pointers in safe code. By using `unsafe` blocks to represent the reverse links as raw pointers, it can be implemented with only boxes. rust Lifetime elision Lifetime elision ================ Rust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice. Lifetime elision in functions ----------------------------- In order to make common patterns more ergonomic, lifetime arguments can be *elided* in [function item](types/function-item), [function pointer](types/function-pointer), and [closure trait](types/closure) signatures. The following rules are used to infer lifetime parameters for elided lifetimes. It is an error to elide lifetime parameters that cannot be inferred. The placeholder lifetime, `'_`, can also be used to have a lifetime inferred in the same way. For lifetimes in paths, using `'_` is preferred. Trait object lifetimes follow different rules discussed [below](#default-trait-object-lifetimes). * Each elided lifetime in the parameters becomes a distinct lifetime parameter. * If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to *all* elided output lifetimes. In method signatures there is another rule * If the receiver has type `&Self` or `&mut Self`, then the lifetime of that reference to `Self` is assigned to all elided output lifetime parameters. Examples: ``` #![allow(unused)] fn main() { trait T {} trait ToCStr {} struct Thing<'a> {f: &'a i32} struct Command; trait Example { fn print1(s: &str); // elided fn print2(s: &'_ str); // also elided fn print3<'a>(s: &'a str); // expanded fn debug1(lvl: usize, s: &str); // elided fn debug2<'a>(lvl: usize, s: &'a str); // expanded fn substr1(s: &str, until: usize) -> &str; // elided fn substr2<'a>(s: &'a str, until: usize) -> &'a str; // expanded fn get_mut1(&mut self) -> &mut dyn T; // elided fn get_mut2<'a>(&'a mut self) -> &'a mut dyn T; // expanded fn args1<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided fn args2<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded fn new1(buf: &mut [u8]) -> Thing<'_>; // elided - preferred fn new2(buf: &mut [u8]) -> Thing; // elided fn new3<'a>(buf: &'a mut [u8]) -> Thing<'a>; // expanded } type FunPtr1 = fn(&str) -> &str; // elided type FunPtr2 = for<'a> fn(&'a str) -> &'a str; // expanded type FunTrait1 = dyn Fn(&str) -> &str; // elided type FunTrait2 = dyn for<'a> Fn(&'a str) -> &'a str; // expanded } ``` ``` #![allow(unused)] fn main() { // The following examples show situations where it is not allowed to elide the // lifetime parameter. trait Example { // Cannot infer, because there are no parameters to infer from. fn get_str() -> &str; // ILLEGAL // Cannot infer, ambiguous if it is borrowed from the first or second parameter. fn frob(s: &str, t: &str) -> &str; // ILLEGAL } } ``` Default trait object lifetimes ------------------------------ The assumed lifetime of references held by a [trait object](types/trait-object) is called its *default object lifetime bound*. These were defined in [RFC 599](https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md) and amended in [RFC 1156](https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md). These default object lifetime bounds are used instead of the lifetime parameter elision rules defined above when the lifetime bound is omitted entirely. If `'_` is used as the lifetime bound then the bound follows the usual elision rules. If the trait object is used as a type argument of a generic type then the containing type is first used to try to infer a bound. * If there is a unique bound from the containing type then that is the default * If there is more than one bound from the containing type then an explicit bound must be specified If neither of those rules apply, then the bounds on the trait are used: * If the trait is defined with a single lifetime *bound* then that bound is used. * If `'static` is used for any lifetime bound then `'static` is used. * If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is `'static` outside of expressions. ``` #![allow(unused)] fn main() { // For the following trait... trait Foo { } // These two are the same because Box<T> has no lifetime bound on T type T1 = Box<dyn Foo>; type T2 = Box<dyn Foo + 'static>; // ...and so are these: impl dyn Foo {} impl dyn Foo + 'static {} // ...so are these, because &'a T requires T: 'a type T3<'a> = &'a dyn Foo; type T4<'a> = &'a (dyn Foo + 'a); // std::cell::Ref<'a, T> also requires T: 'a, so these are the same type T5<'a> = std::cell::Ref<'a, dyn Foo>; type T6<'a> = std::cell::Ref<'a, dyn Foo + 'a>; } ``` ``` #![allow(unused)] fn main() { // This is an example of an error. trait Foo { } struct TwoBounds<'a, 'b, T: ?Sized + 'a + 'b> { f1: &'a i32, f2: &'b i32, f3: T, } type T7<'a, 'b> = TwoBounds<'a, 'b, dyn Foo>; // ^^^^^^^ // Error: the lifetime bound for this object type cannot be deduced from context } ``` Note that the innermost object sets the bound, so `&'a Box<dyn Foo>` is still `&'a Box<dyn Foo + 'static>`. ``` #![allow(unused)] fn main() { // For the following trait... trait Bar<'a>: 'a { } // ...these two are the same: type T1<'a> = Box<dyn Bar<'a>>; type T2<'a> = Box<dyn Bar<'a> + 'a>; // ...and so are these: impl<'a> dyn Bar<'a> {} impl<'a> dyn Bar<'a> + 'a {} } ``` `'static` lifetime elision --------------------------- Both [constant](items/constant-items) and [static](items/static-items) declarations of reference types have *implicit* `'static` lifetimes unless an explicit lifetime is specified. As such, the constant declarations involving `'static` above may be written without the lifetimes. ``` #![allow(unused)] fn main() { // STRING: &'static str const STRING: &str = "bitstring"; struct BitsNStrings<'a> { mybits: [u32; 2], mystring: &'a str, } // BITS_N_STRINGS: BitsNStrings<'static> const BITS_N_STRINGS: BitsNStrings<'_> = BitsNStrings { mybits: [1, 2], mystring: STRING, }; } ``` Note that if the `static` or `const` items include function or closure references, which themselves include references, the compiler will first try the standard elision rules. If it is unable to resolve the lifetimes by its usual rules, then it will error. By way of example: ``` #![allow(unused)] fn main() { struct Foo; struct Bar; struct Baz; fn somefunc(a: &Foo, b: &Bar, c: &Baz) -> usize {42} // Resolved as `fn<'a>(&'a str) -> &'a str`. const RESOLVED_SINGLE: fn(&str) -> &str = |x| x; // Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`. const RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc; } ``` ``` #![allow(unused)] fn main() { struct Foo; struct Bar; struct Baz; fn somefunc<'a,'b>(a: &'a Foo, b: &'b Bar) -> &'a Baz {unimplemented!()} // There is insufficient information to bound the return reference lifetime // relative to the argument lifetimes, so this is an error. const RESOLVED_STATIC: &dyn Fn(&Foo, &Bar) -> &Baz = &somefunc; // ^ // this function's return type contains a borrowed value, but the signature // does not say whether it is borrowed from argument 1 or argument 2 } ``` rust Special types and traits Special types and traits ======================== Certain types and traits that exist in [the standard library](../std/index) are known to the Rust compiler. This chapter documents the special features of these types and traits. `Box<T>` -------- [`Box<T>`](../std/boxed/struct.box) has a few special features that Rust doesn't currently allow for user defined types. * The [dereference operator](expressions/operator-expr#the-dereference-operator) for `Box<T>` produces a place which can be moved from. This means that the `*` operator and the destructor of `Box<T>` are built-in to the language. * [Methods](items/associated-items#associated-functions-and-methods) can take `Box<Self>` as a receiver. * A trait may be implemented for `Box<T>` in the same crate as `T`, which the [orphan rules](items/implementations#trait-implementation-coherence) prevent for other generic types. `Rc<T>` ------- [Methods](items/associated-items#associated-functions-and-methods) can take [`Rc<Self>`](../std/rc/struct.rc) as a receiver. `Arc<T>` -------- [Methods](items/associated-items#associated-functions-and-methods) can take [`Arc<Self>`](../std/sync/struct.arc) as a receiver. `Pin<P>` -------- [Methods](items/associated-items#associated-functions-and-methods) can take [`Pin<P>`](../std/pin/struct.pin) as a receiver. `UnsafeCell<T>` --------------- [`std::cell::UnsafeCell<T>`](../std/cell/struct.unsafecell) is used for [interior mutability](interior-mutability). It ensures that the compiler doesn't perform optimisations that are incorrect for such types. It also ensures that [`static` items](items/static-items) which have a type with interior mutability aren't placed in memory marked as read only. `PhantomData<T>` ---------------- [`std::marker::PhantomData<T>`](../std/marker/struct.phantomdata) is a zero-sized, minimum alignment, type that is considered to own a `T` for the purposes of [variance](subtyping#variance), [drop check](https://doc.rust-lang.org/nomicon/dropck.html), and [auto traits](#auto-traits). Operator Traits --------------- The traits in [`std::ops`](../std/ops/index) and [`std::cmp`](../std/cmp/index) are used to overload [operators](expressions/operator-expr), [indexing expressions](expressions/array-expr#array-and-slice-indexing-expressions), and [call expressions](expressions/call-expr). `Deref` and `DerefMut` ----------------------- As well as overloading the unary `*` operator, [`Deref`](../std/ops/trait.deref) and [`DerefMut`](../std/ops/trait.derefmut) are also used in [method resolution](expressions/method-call-expr) and [deref coercions](type-coercions#coercion-types). `Drop` ------ The [`Drop`](../std/ops/trait.drop) trait provides a [destructor](destructors), to be run whenever a value of this type is to be destroyed. `Copy` ------ The [`Copy`](../std/marker/trait.copy) trait changes the semantics of a type implementing it. Values whose type implements `Copy` are copied rather than moved upon assignment. `Copy` can only be implemented for types which do not implement `Drop`, and whose fields are all `Copy`. For enums, this means all fields of all variants have to be `Copy`. For unions, this means all variants have to be `Copy`. `Copy` is implemented by the compiler for * [Tuples](types/tuple) of `Copy` types * [Function pointers](types/function-pointer) * [Function items](types/function-item) * [Closures](types/closure) that capture no values or that only capture values of `Copy` types `Clone` ------- The [`Clone`](../std/clone/trait.clone) trait is a supertrait of `Copy`, so it also needs compiler generated implementations. It is implemented by the compiler for the following types: * Types with a built-in `Copy` implementation (see above) * [Tuples](types/tuple) of `Clone` types `Send` ------ The [`Send`](../std/marker/trait.send) trait indicates that a value of this type is safe to send from one thread to another. `Sync` ------ The [`Sync`](../std/marker/trait.sync) trait indicates that a value of this type is safe to share between multiple threads. This trait must be implemented for all types used in immutable [`static` items](items/static-items). `Termination` ------------- The [`Termination`](../std/process/trait.termination) trait indicates the acceptable return types for the [main function](crates-and-source-files#main-functions) and [test functions](attributes/testing#the-test-attribute). Auto traits ----------- The [`Send`](../std/marker/trait.send), [`Sync`](../std/marker/trait.sync), [`Unpin`](../std/marker/trait.unpin), [`UnwindSafe`](../std/panic/trait.unwindsafe), and [`RefUnwindSafe`](../std/panic/trait.refunwindsafe) traits are *auto traits*. Auto traits have special properties. If no explicit implementation or negative implementation is written out for an auto trait for a given type, then the compiler implements it automatically according to the following rules: * `&T`, `&mut T`, `*const T`, `*mut T`, `[T; n]`, and `[T]` implement the trait if `T` does. * Function item types and function pointers automatically implement the trait. * Structs, enums, unions, and tuples implement the trait if all of their fields do. * Closures implement the trait if the types of all of their captures do. A closure that captures a `T` by shared reference and a `U` by value implements any auto traits that both `&T` and `U` do. For generic types (counting the built-in types above as generic over `T`), if a generic implementation is available, then the compiler does not automatically implement it for types that could use the implementation except that they do not meet the requisite trait bounds. For instance, the standard library implements `Send` for all `&T` where `T` is `Sync`; this means that the compiler will not implement `Send` for `&T` if `T` is `Send` but not `Sync`. Auto traits can also have negative implementations, shown as `impl !AutoTrait for T` in the standard library documentation, that override the automatic implementations. For example `*mut T` has a negative implementation of `Send`, and so `*mut T` is not `Send`, even if `T` is. There is currently no stable way to specify additional negative implementations; they exist only in the standard library. Auto traits may be added as an additional bound to any [trait object](types/trait-object), even though normally only one trait is allowed. For instance, `Box<dyn Debug + Send + UnwindSafe>` is a valid type. `Sized` ------- The [`Sized`](../std/marker/trait.sized) trait indicates that the size of this type is known at compile-time; that is, it's not a [dynamically sized type](dynamically-sized-types). [Type parameters](types/parameters) are `Sized` by default, as are [associated types](items/associated-items#associated-types). `Sized` is always implemented automatically by the compiler, not by [implementation items](items/implementations). These implicit `Sized` bounds may be relaxed by using the special `?Sized` bound. rust Influences Influences ========== Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed): * SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation * C++: references, RAII, smart pointers, move semantics, monomorphization, memory model * ML Kit, Cyclone: region based memory management * Haskell (GHC): typeclasses, type families * Newsqueak, Alef, Limbo: channels, concurrency * Erlang: message passing, thread failure, linked thread failure, lightweight concurrency * Swift: optional bindings * Scheme: hygienic macros * C#: attributes * Ruby: closure syntax, block syntax * NIL, Hermes: typestate * [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and pattern syntax rust Memory model Memory model ============ Rust does not yet have a defined memory model. Various academics and industry professionals are working on various proposals, but for now, this is an under-defined place in the language. rust Variables Variables ========= A *variable* is a component of a stack frame, either a named function parameter, an anonymous [temporary](expressions#temporaries), or a named local variable. A *local variable* (or *stack-local* allocation) holds a value directly, allocated within the stack's memory. The value is a part of the stack frame. Local variables are immutable unless declared otherwise. For example: `let mut x = ...`. Function parameters are immutable unless declared with `mut`. The `mut` keyword applies only to the following parameter. For example: `|mut x, y|` and `fn f(mut x: Box<i32>, y: Box<i32>)` declare one mutable variable `x` and one immutable variable `y`. Local variables are not initialized when allocated. Instead, the entire frame worth of local variables are allocated, on frame-entry, in an uninitialized state. Subsequent statements within a function may or may not initialize the local variables. Local variables can be used only after they have been initialized through all reachable control flow paths. In this next example, `init_after_if` is initialized after the [`if` expression](expressions/if-expr#if-expressions) while `uninit_after_if` is not because it is not initialized in the `else` case. ``` #![allow(unused)] fn main() { fn random_bool() -> bool { true } fn initialization_example() { let init_after_if: (); let uninit_after_if: (); if random_bool() { init_after_if = (); uninit_after_if = (); } else { init_after_if = (); } init_after_if; // ok // uninit_after_if; // err: use of possibly uninitialized `uninit_after_if` } } ``` rust Behavior not considered unsafe Behavior not considered `unsafe` ================================ The Rust compiler does not consider the following behaviors *unsafe*, though a programmer may (should) find them undesirable, unexpected, or erroneous. ##### Deadlocks ##### Leaks of memory and other resources ##### Exiting without calling destructors ##### Exposing randomized base addresses through pointer leaks ##### Integer overflow If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional. When the programmer has enabled `debug_assert!` assertions (for example, by enabling a non-optimized build), implementations must insert dynamic checks that `panic` on overflow. Other kinds of builds may result in `panics` or silently wrapped values on overflow, at the implementation's discretion. In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions. The integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, `i32::wrapping_add` provides two's complement, wrapping addition. The standard library also provides a `Wrapping<T>` newtype which ensures all standard arithmetic operations for `T` have wrapping semantics. See [RFC 560](https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md) for error conditions, rationale, and more details about integer overflow. ##### Logic errors Safe code may impose extra logical constraints that can be checked at neither compile-time nor runtime. If a program breaks such a constraint, the behavior may be unspecified but will not result in undefined behavior. This could include panics, incorrect results, aborts, and non-termination. The behavior may also differ between runs, builds, or kinds of build. For example, implementing both `Hash` and `Eq` requires that values considered equal have equal hashes. Another example are data structures like `BinaryHeap`, `BTreeMap`, `BTreeSet`, `HashMap` and `HashSet` which describe constraints on the modification of their keys while they are in the data structure. Violating such constraints is not considered unsafe, yet the program is considered erroneous and its behavior unpredictable.
programming_docs
rust Application Binary Interface (ABI) Application Binary Interface (ABI) ================================== This section documents features that affect the ABI of the compiled output of a crate. See *[extern functions](items/functions#extern-function-qualifier)* for information on specifying the ABI for exporting functions. See *[external blocks](items/external-blocks)* for information on specifying the ABI for linking external libraries. The `used` attribute -------------------- The *`used` attribute* can only be applied to [`static` items](items/static-items). This [attribute](attributes) forces the compiler to keep the variable in the output object file (.o, .rlib, etc. excluding final binaries) even if the variable is not used, or referenced, by any other item in the crate. However, the linker is still free to remove such an item. Below is an example that shows under what conditions the compiler keeps a `static` item in the output object file. ``` #![allow(unused)] fn main() { // foo.rs // This is kept because of `#[used]`: #[used] static FOO: u32 = 0; // This is removable because it is unused: #[allow(dead_code)] static BAR: u32 = 0; // This is kept because it is publicly reachable: pub static BAZ: u32 = 0; // This is kept because it is referenced by a public, reachable function: static QUUX: u32 = 0; pub fn quux() -> &'static u32 { &QUUX } // This is removable because it is referenced by a private, unused (dead) function: static CORGE: u32 = 0; #[allow(dead_code)] fn corge() -> &'static u32 { &CORGE } } ``` ``` $ rustc -O --emit=obj --crate-type=rlib foo.rs $ nm -C foo.o 0000000000000000 R foo::BAZ 0000000000000000 r foo::FOO 0000000000000000 R foo::QUUX 0000000000000000 T foo::quux ``` The `no_mangle` attribute ------------------------- The *`no_mangle` attribute* may be used on any [item](items) to disable standard symbol name mangling. The symbol for the item will be the identifier of the item's name. Additionally, the item will be publicly exported from the produced library or object file, similar to the [`used` attribute](#the-used-attribute). The `link_section` attribute ---------------------------- The *`link_section` attribute* specifies the section of the object file that a [function](items/functions) or [static](items/static-items)'s content will be placed into. It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the section name. ``` #![allow(unused)] fn main() { #[no_mangle] #[link_section = ".example_section"] pub static VAR1: u32 = 1; } ``` The `export_name` attribute --------------------------- The *`export_name` attribute* specifies the name of the symbol that will be exported on a [function](items/functions) or [static](items/static-items). It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the symbol name. ``` #![allow(unused)] fn main() { #[export_name = "exported_symbol_name"] pub fn name_in_rust() { } } ``` rust Memory allocation and lifetime Memory allocation and lifetime ============================== The *items* of a program are those functions, modules, and types that have their value calculated at compile-time and stored uniquely in the memory image of the rust process. Items are neither dynamically allocated nor freed. The *heap* is a general term that describes boxes. The lifetime of an allocation in the heap depends on the lifetime of the box values pointing to it. Since box values may themselves be passed in and out of frames, or stored in the heap, heap allocations may outlive the frame they are allocated within. An allocation in the heap is guaranteed to reside at a single location in the heap for the whole lifetime of the allocation - it will never be relocated as a result of moving a box value. rust Interior Mutability Interior Mutability =================== Sometimes a type needs to be mutated while having multiple aliases. In Rust this is achieved using a pattern called *interior mutability*. A type has interior mutability if its internal state can be changed through a [shared reference](types/pointer#shared-references-) to it. This goes against the usual [requirement](behavior-considered-undefined) that the value pointed to by a shared reference is not mutated. [`std::cell::UnsafeCell<T>`](../std/cell/struct.unsafecell) type is the only allowed way to disable this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to mutate, or obtain a mutable reference to, the `T` it contains. As with all other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>` aliases. Other types with interior mutability can be created by using `UnsafeCell<T>` as a field. The standard library provides a variety of types that provide safe interior mutability APIs. For example, [`std::cell::RefCell<T>`](../std/cell/struct.refcell) uses run-time borrow checks to ensure the usual rules around multiple references. The [`std::sync::atomic`](../std/sync/atomic/index) module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads. rust Dynamically Sized Types Dynamically Sized Types ======================= Most types have a fixed size that is known at compile time and implement the trait [`Sized`](special-types-and-traits#sized). A type with a size that is known only at run-time is called a *dynamically sized type* (*DST*) or, informally, an unsized type. [Slices](types/slice) and [trait objects](types/trait-object) are two examples of DSTs. Such types can only be used in certain cases: * [Pointer types](types/pointer) to DSTs are sized but have twice the size of pointers to sized types + Pointers to slices also store the number of elements of the slice. + Pointers to trait objects also store a pointer to a vtable. * DSTs can be provided as type arguments to generic type parameters having the special `?Sized` bound. They can also be used for associated type definitions when the corresponding associated type declaration has a `?Sized` bound. By default, any type parameter or associated type has a `Sized` bound, unless it is relaxed using `?Sized`. * Traits may be implemented for DSTs. Unlike with generic type parameters, `Self: ?Sized` is the default in trait definitions. * Structs may contain a DST as the last field; this makes the struct itself a DST. > **Note**: <variables>, function parameters, [const](items/constant-items) items, and [static](items/static-items) items must be `Sized`. > > rust Macros Macros ====== The functionality and syntax of Rust can be extended with custom definitions called macros. They are given names, and invoked through a consistent syntax: `some_extension!(...)`. There are two ways to define new macros: * [Macros by Example](macros-by-example) define new syntax in a higher-level, declarative way. * [Procedural Macros](procedural-macros) define function-like macros, custom derives, and custom attributes using functions that operate on input tokens. Macro Invocation ---------------- > **Syntax** > *MacroInvocation* : > [*SimplePath*](paths#simple-paths) `!` *DelimTokenTree* > > *DelimTokenTree* : > `(` *TokenTree*\* `)` > | `[` *TokenTree*\* `]` > | `{` *TokenTree*\* `}` > > *TokenTree* : > [*Token*](tokens)*except [delimiters](tokens#delimiters)* | *DelimTokenTree* > > *MacroInvocationSemi* : > [*SimplePath*](paths#simple-paths) `!` `(` *TokenTree*\* `)` `;` > | [*SimplePath*](paths#simple-paths) `!` `[` *TokenTree*\* `]` `;` > | [*SimplePath*](paths#simple-paths) `!` `{` *TokenTree*\* `}` > > A macro invocation expands a macro at compile time and replaces the invocation with the result of the macro. Macros may be invoked in the following situations: * [Expressions](expressions) and <statements> * [Patterns](patterns) * [Types](types) * [Items](items) including [associated items](items/associated-items) * [`macro_rules`](macros-by-example) transcribers * [External blocks](items/external-blocks) When used as an item or a statement, the *MacroInvocationSemi* form is used where a semicolon is required at the end when not using curly braces. [Visibility qualifiers](visibility-and-privacy) are never allowed before a macro invocation or [`macro_rules`](macros-by-example) definition. ``` #![allow(unused)] fn main() { // Used as an expression. let x = vec![1,2,3]; // Used as a statement. println!("Hello!"); // Used in a pattern. macro_rules! pat { ($i:ident) => (Some($i)) } if let pat!(x) = Some(1) { assert_eq!(x, 1); } // Used in a type. macro_rules! Tuple { { $A:ty, $B:ty } => { ($A, $B) }; } type N2 = Tuple!(i32, i32); // Used as an item. use std::cell::RefCell; thread_local!(static FOO: RefCell<u32> = RefCell::new(1)); // Used as an associated item. macro_rules! const_maker { ($t:ty, $v:tt) => { const CONST: $t = $v; }; } trait T { const_maker!{i32, 7} } // Macro calls within macros. macro_rules! example { () => { println!("Macro call in a macro!") }; } // Outer macro `example` is expanded, then inner macro `println` is expanded. example!(); } ``` rust Unsafe functions Unsafe functions ================ Unsafe functions are functions that are not safe in all contexts and/or for all possible inputs. Such a function must be prefixed with the keyword `unsafe` and can only be called from an `unsafe` block or another `unsafe` function. rust Names Names ===== An *entity* is a language construct that can be referred to in some way within the source program, usually via a [path](paths). Entities include <types>, <items>, [generic parameters](items/generics), [variable bindings](patterns), [loop labels](expressions/loop-expr#loop-labels), [lifetimes](tokens#lifetimes-and-loop-labels), [fields](expressions/field-expr), <attributes>, and [lints](attributes/diagnostics#lint-check-attributes). A *declaration* is a syntactical construct that can introduce a *name* to refer to an entity. Entity names are valid within a [*scope*](names/scopes) — a region of source text where that name may be referenced. Some entities are [explicitly declared](#explicitly-declared-entities) in the source code, and some are [implicitly declared](#implicitly-declared-entities) as part of the language or compiler extensions. [*Paths*](paths) are used to refer to an entity, possibly in another scope. Lifetimes and loop labels use a [dedicated syntax](tokens#lifetimes-and-loop-labels) using a leading quote. Names are segregated into different [*namespaces*](names/namespaces), allowing entities in different namespaces to share the same name without conflict. [*Name resolution*](names/name-resolution) is the compile-time process of tying paths, identifiers, and labels to entity declarations. Access to certain names may be restricted based on their [*visibility*](visibility-and-privacy). Explicitly declared entities ---------------------------- Entities that explicitly introduce a name in the source code are: * [Items](items): + [Module declarations](items/modules) + [External crate declarations](items/extern-crates) + [Use declarations](items/use-declarations) + [Function declarations](items/functions) and [function parameters](items/functions#function-parameters) + [Type aliases](items/type-aliases) + [struct](items/structs), [union](items/unions), [enum](items/enumerations), enum variant declarations, and their named fields + [Constant item declarations](items/constant-items) + [Static item declarations](items/static-items) + [Trait item declarations](items/traits) and their [associated items](items/associated-items) + [External block items](items/external-blocks) + [`macro_rules` declarations](macros-by-example) and [matcher metavariables](macros-by-example#metavariables) + [Implementation](items/implementations) associated items * [Expressions](expressions): + [Closure](expressions/closure-expr) parameters + [`while let`](expressions/loop-expr#predicate-pattern-loops) pattern bindings + [`for`](expressions/loop-expr#iterator-loops) pattern bindings + [`if let`](expressions/if-expr#if-let-expressions) pattern bindings + [`match`](expressions/match-expr) pattern bindings + [Loop labels](expressions/loop-expr#loop-labels) * [Generic parameters](items/generics) * [Higher ranked trait bounds](trait-bounds#higher-ranked-trait-bounds) * [`let` statement](statements#let-statements) pattern bindings * The [`macro_use` attribute](macros-by-example#the-macro_use-attribute) can introduce macro names from another crate * The [`macro_export` attribute](macros-by-example#path-based-scope) can introduce an alias for the macro into the crate root Additionally, [macro invocations](macros#macro-invocation) and <attributes> can introduce names by expanding to one of the above items. Implicitly declared entities ---------------------------- The following entities are implicitly defined by the language, or are introduced by compiler options and extensions: * [Language prelude](names/preludes#language-prelude): + [Boolean type](types/boolean) — `bool` + [Textual types](types/textual) — `char` and `str` + [Integer types](types/numeric#integer-types) — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128` + [Machine-dependent integer types](types/numeric#machine-dependent-integer-types) — `usize` and `isize` + [floating-point types](types/numeric#floating-point-types) — `f32` and `f64` * [Built-in attributes](attributes#built-in-attributes-index) * [Standard library prelude](names/preludes#standard-library-prelude) items, attributes, and macros * [Standard library](names/preludes#extern-prelude) crates in the root module * [External crates](names/preludes#extern-prelude) linked by the compiler * [Tool attributes](attributes#tool-attributes) * [Lints](attributes/diagnostics#lint-check-attributes) and [tool lint attributes](attributes/diagnostics#tool-lint-attributes) * [Derive helper attributes](procedural-macros#derive-macro-helper-attributes) are valid within an item without being explicitly imported * The [`'static`](keywords#weak-keywords) lifetime Additionally, the crate root module does not have a name, but can be referred to with certain [path qualifiers](paths#path-qualifiers) or aliases. rust Paths Paths ===== A *path* is a sequence of one or more path segments *logically* separated by a namespace qualifier (`::`). If a path consists of only one segment, it refers to either an [item](items) or a [variable](variables) in a local control scope. If a path has multiple segments, it always refers to an item. Two examples of simple paths consisting of only identifier segments: ``` x; x::y::z; ``` Types of paths -------------- ### Simple Paths > **Syntax** > *SimplePath* : > `::`? *SimplePathSegment* (`::` *SimplePathSegment*)\* > > *SimplePathSegment* : > [IDENTIFIER](identifiers) | `super` | `self` | `crate` | `$crate` > > Simple paths are used in [visibility](visibility-and-privacy) markers, <attributes>, [macros](macros-by-example), and [`use`](items/use-declarations) items. Examples: ``` #![allow(unused)] fn main() { use std::io::{self, Write}; mod m { #[clippy::cyclomatic_complexity = "0"] pub (in super) fn f1() {} } } ``` ### Paths in expressions > **Syntax** > *PathInExpression* : > `::`? *PathExprSegment* (`::` *PathExprSegment*)\* > > *PathExprSegment* : > *PathIdentSegment* (`::` *GenericArgs*)? > > *PathIdentSegment* : > [IDENTIFIER](identifiers) | `super` | `self` | `Self` | `crate` | `$crate` > > *GenericArgs* : > `<` `>` > | `<` ( *GenericArg* `,` )\* *GenericArg* `,`? `>` > > *GenericArg* : > [*Lifetime*](trait-bounds) | [*Type*](types#type-expressions) | *GenericArgsConst* | *GenericArgsBinding* > > *GenericArgsConst* : > [*BlockExpression*](expressions/block-expr) > | [*LiteralExpression*](expressions/literal-expr) > | `-` [*LiteralExpression*](expressions/literal-expr) > | [*SimplePathSegment*](#simple-paths) > > *GenericArgsBinding* : > [IDENTIFIER](identifiers) `=` [*Type*](types#type-expressions) > > Paths in expressions allow for paths with generic arguments to be specified. They are used in various places in <expressions> and <patterns>. The `::` token is required before the opening `<` for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as "turbofish" syntax. ``` #![allow(unused)] fn main() { (0..10).collect::<Vec<_>>(); Vec::<u8>::with_capacity(1024); } ``` The order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints. Const arguments must be surrounded by braces unless they are a [literal](expressions/literal-expr) or a single segment path. The synthetic type parameters corresponding to `impl Trait` types are implicit, and these cannot be explicitly specified. Qualified paths --------------- > **Syntax** > *QualifiedPathInExpression* : > *QualifiedPathType* (`::` *PathExprSegment*)+ > > *QualifiedPathType* : > `<` [*Type*](types#type-expressions) (`as` *TypePath*)? `>` > > *QualifiedPathInType* : > *QualifiedPathType* (`::` *TypePathSegment*)+ > > Fully qualified paths allow for disambiguating the path for [trait implementations](items/implementations#trait-implementations) and for specifying [canonical paths](#canonical-paths). When used in a type specification, it supports using the type syntax specified below. ``` #![allow(unused)] fn main() { struct S; impl S { fn f() { println!("S"); } } trait T1 { fn f() { println!("T1 f"); } } impl T1 for S {} trait T2 { fn f() { println!("T2 f"); } } impl T2 for S {} S::f(); // Calls the inherent impl. <S as T1>::f(); // Calls the T1 trait function. <S as T2>::f(); // Calls the T2 trait function. } ``` ### Paths in types > **Syntax** > *TypePath* : > `::`? *TypePathSegment* (`::` *TypePathSegment*)\* > > *TypePathSegment* : > *PathIdentSegment* `::`? ([*GenericArgs*](#paths-in-expressions) | *TypePathFn*)? > > *TypePathFn* : > `(` *TypePathFnInputs*? `)` (`->` [*Type*](types#type-expressions))? > > *TypePathFnInputs* : > [*Type*](types#type-expressions) (`,` [*Type*](types#type-expressions))\* `,`? > > Type paths are used within type definitions, trait bounds, type parameter bounds, and qualified paths. Although the `::` token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in *PathInExpression*. ``` #![allow(unused)] fn main() { mod ops { pub struct Range<T> {f1: T} pub trait Index<T> {} pub struct Example<'a> {f1: &'a i32} } struct S; impl ops::Index<ops::Range<usize>> for S { /*...*/ } fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> { // ... const EXAMPLE: Vec<ops::Example<'static>> = Vec::new(); EXAMPLE.into_iter() } type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>; } ``` Path qualifiers --------------- Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved. ### `::` Paths starting with `::` are considered to be *global paths* where the segments of the path start being resolved from a place which differs based on edition. Each identifier in the path must resolve to an item. > **Edition Differences**: In the 2015 Edition, identifiers resolve from the "crate root" (`crate::` in the 2018 edition), which contains a variety of different items, including external crates, default crates such as `std` or `core`, and items in the top level of the crate (including `use` imports). > > Beginning with the 2018 Edition, paths starting with `::` resolve from crates in the [extern prelude](names/preludes#extern-prelude). That is, they must be followed by the name of a crate. > > ``` #![allow(unused)] fn main() { pub fn foo() { // In the 2018 edition, this accesses `std` via the extern prelude. // In the 2015 edition, this accesses `std` via the crate root. let now = ::std::time::Instant::now(); println!("{:?}", now); } } ``` ``` // 2015 Edition mod a { pub fn foo() {} } mod b { pub fn foo() { ::a::foo(); // call `a`'s foo function // In Rust 2018, `::a` would be interpreted as the crate `a`. } } fn main() {} ``` ### `self` `self` resolves the path relative to the current module. `self` can only be used as the first segment, without a preceding `::`. ``` fn foo() {} fn bar() { self::foo(); } fn main() {} ``` ### `Self` `Self`, with a capital "S", is used to refer to the implementing type within [traits](items/traits) and [implementations](items/implementations). `Self` can only be used as the first segment, without a preceding `::`. ``` #![allow(unused)] fn main() { trait T { type Item; const C: i32; // `Self` will be whatever type that implements `T`. fn new() -> Self; // `Self::Item` will be the type alias in the implementation. fn f(&self) -> Self::Item; } struct S; impl T for S { type Item = i32; const C: i32 = 9; fn new() -> Self { // `Self` is the type `S`. S } fn f(&self) -> Self::Item { // `Self::Item` is the type `i32`. Self::C // `Self::C` is the constant value `9`. } } } ``` ### `super` `super` in a path resolves to the parent module. It may only be used in leading segments of the path, possibly after an initial `self` segment. ``` mod a { pub fn foo() {} } mod b { pub fn foo() { super::a::foo(); // call a's foo function } } fn main() {} ``` `super` may be repeated several times after the first `super` or `self` to refer to ancestor modules. ``` mod a { fn foo() {} mod b { mod c { fn foo() { super::super::foo(); // call a's foo function self::super::super::foo(); // call a's foo function } } } } fn main() {} ``` ### `crate` `crate` resolves the path relative to the current crate. `crate` can only be used as the first segment, without a preceding `::`. ``` fn foo() {} mod a { fn bar() { crate::foo(); } } fn main() {} ``` ### `$crate` `$crate` is only used within [macro transcribers](macros-by-example), and can only be used as the first segment, without a preceding `::`. `$crate` will expand to a path to access items from the top level of the crate where the macro is defined, regardless of which crate the macro is invoked. ``` pub fn increment(x: u32) -> u32 { x + 1 } #[macro_export] macro_rules! inc { ($x:expr) => ( $crate::increment($x) ) } fn main() { } ``` Canonical paths --------------- Items defined in a module or implementation have a *canonical path* that corresponds to where within its crate it is defined. All other paths to these items are aliases. The canonical path is defined as a *path prefix* appended by the path segment the item itself defines. [Implementations](items/implementations) and [use declarations](items/use-declarations) do not have canonical paths, although the items that implementations define do have them. Items defined in block expressions do not have canonical paths. Items defined in a module that does not have a canonical path do not have a canonical path. Associated items defined in an implementation that refers to an item without a canonical path, e.g. as the implementing type, the trait being implemented, a type parameter or bound on a type parameter, do not have canonical paths. The path prefix for modules is the canonical path to that module. For bare implementations, it is the canonical path of the item being implemented surrounded by angle (`<>`) brackets. For [trait implementations](items/implementations#trait-implementations), it is the canonical path of the item being implemented followed by `as` followed by the canonical path to the trait all surrounded in angle (`<>`) brackets. The canonical path is only meaningful within a given crate. There is no global namespace across crates; an item's canonical path merely identifies it within the crate. ``` // Comments show the canonical path of the item. mod a { // crate::a pub struct Struct; // crate::a::Struct pub trait Trait { // crate::a::Trait fn f(&self); // crate::a::Trait::f } impl Trait for Struct { fn f(&self) {} // <crate::a::Struct as crate::a::Trait>::f } impl Struct { fn g(&self) {} // <crate::a::Struct>::g } } mod without { // crate::without fn canonicals() { // crate::without::canonicals struct OtherStruct; // None trait OtherTrait { // None fn g(&self); // None } impl OtherTrait for OtherStruct { fn g(&self) {} // None } impl OtherTrait for crate::a::Struct { fn g(&self) {} // None } impl crate::a::Trait for OtherStruct { fn f(&self) {} // None } } } fn main() {} ```
programming_docs
rust Input format Input format ============ Rust input is interpreted as a sequence of Unicode code points encoded in UTF-8. rust Crates and source files Crates and source files ======================= > **Syntax** > *Crate* : > UTF8BOM? > SHEBANG? > [*InnerAttribute*](attributes)\* > [*Item*](items)\* > > > **Lexer** > UTF8BOM : `\uFEFF` > SHEBANG : `#!` ~`\n`+[†](#shebang) > > > Note: Although Rust, like any other language, can be implemented by an interpreter as well as a compiler, the only existing implementation is a compiler, and the language has always been designed to be compiled. For these reasons, this section assumes a compiler. > > Rust's semantics obey a *phase distinction* between compile-time and run-time.[1](#phase-distinction) Semantic rules that have a *static interpretation* govern the success or failure of compilation, while semantic rules that have a *dynamic interpretation* govern the behavior of the program at run-time. The compilation model centers on artifacts called *crates*. Each compilation processes a single crate in source form, and if successful, produces a single crate in binary form: either an executable or some sort of library.[2](#cratesourcefile) A *crate* is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. A crate contains a *tree* of nested [module](items/modules) scopes. The top level of this tree is a module that is anonymous (from the point of view of paths within the module) and any item within a crate has a canonical [module path](paths) denoting its location within the crate's module tree. The Rust compiler is always invoked with a single source file as input, and always produces a single output crate. The processing of that source file may result in other source files being loaded as modules. Source files have the extension `.rs`. A Rust source file describes a module, the name and location of which — in the module tree of the current crate — are defined from outside the source file: either by an explicit [*Module*](items/modules) item in a referencing source file, or by the name of the crate itself. Every source file is a module, but not every module needs its own source file: [module definitions](items/modules) can be nested within one file. Each source file contains a sequence of zero or more [*Item*](items) definitions, and may optionally begin with any number of <attributes> that apply to the containing module, most of which influence the behavior of the compiler. The anonymous crate module can have additional attributes that apply to the crate as a whole. ``` #![allow(unused)] fn main() { // Specify the crate name. #![crate_name = "projx"] // Specify the type of output artifact. #![crate_type = "lib"] // Turn on a warning. // This can be done in any module, not just the anonymous crate module. #![warn(non_camel_case_types)] } ``` Byte order mark --------------- The optional [*UTF8 byte order mark*](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) (UTF8BOM production) indicates that the file is encoded in UTF8. It can only occur at the beginning of the file and is ignored by the compiler. Shebang ------- A source file can have a [*shebang*](https://en.wikipedia.org/wiki/Shebang_(Unix)) (SHEBANG production), which indicates to the operating system what program to use to execute this file. It serves essentially to treat the source file as an executable script. The shebang can only occur at the beginning of the file (but after the optional *UTF8BOM*). It is ignored by the compiler. For example: ``` #!/usr/bin/env rustx fn main() { println!("Hello!"); } ``` A restriction is imposed on the shebang syntax to avoid confusion with an [attribute](attributes). The `#!` characters must not be followed by a `[` token, ignoring intervening <comments> or <whitespace>. If this restriction fails, then it is not treated as a shebang, but instead as the start of an attribute. Preludes and `no_std` --------------------- This section has been moved to the [Preludes chapter](names/preludes). Main Functions -------------- A crate that contains a `main` [function](items/functions) can be compiled to an executable. If a `main` function is present, it must take no arguments, must not declare any [trait or lifetime bounds](trait-bounds), must not have any [where clauses](items/generics#where-clauses), and its return type must implement the [`Termination`](../std/process/trait.termination) trait. ``` fn main() {} ``` ``` fn main() -> ! { std::process::exit(0); } ``` ``` fn main() -> impl std::process::Termination { std::process::ExitCode::SUCCESS } ``` > **Note**: Types with implementations of [`Termination`](../std/process/trait.termination) in the standard library include: > > * `()` > * [`!`](types/never) > * [`Infallible`](../std/convert/enum.infallible) > * [`ExitCode`](../std/process/struct.exitcode) > * `Result<T, E> where T: Termination, E: Debug` > > ### The `no_main` attribute The *`no_main` [attribute](attributes)* may be applied at the crate level to disable emitting the `main` symbol for an executable binary. This is useful when some other object being linked to defines `main`. The `crate_name` attribute -------------------------- The *`crate_name` [attribute](attributes)* may be applied at the crate level to specify the name of the crate with the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax. ``` #![allow(unused)] #![crate_name = "mycrate"] fn main() { } ``` The crate name must not be empty, and must only contain [Unicode alphanumeric](../std/primitive.char#method.is_alphanumeric) or `_` (U+005F) characters. 1 This distinction would also exist in an interpreter. Static checks like syntactic analysis, type checking, and lints should happen before the program is executed regardless of when it is executed. 2 A crate is somewhat analogous to an *assembly* in the ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit* in the Owens and Flatt module system, or a *configuration* in Mesa. rust Type Layout Type Layout =========== The layout of a type is its size, alignment, and the relative offsets of its fields. For enums, how the discriminant is laid out and interpreted is also part of type layout. Type layout can be changed with each compilation. Instead of trying to document exactly what is done, we only document what is guaranteed today. Size and Alignment ------------------ All values have an alignment and size. The *alignment* of a value specifies what addresses are valid to store the value at. A value of alignment `n` must only be stored at an address that is a multiple of n. For example, a value with an alignment of 2 must be stored at an even address, while a value with an alignment of 1 can be stored at any address. Alignment is measured in bytes, and must be at least 1, and always a power of 2. The alignment of a value can be checked with the [`align_of_val`](../std/mem/fn.align_of_val) function. The *size* of a value is the offset in bytes between successive elements in an array with that item type including alignment padding. The size of a value is always a multiple of its alignment. The size of a value can be checked with the [`size_of_val`](../std/mem/fn.size_of_val) function. Types where all values have the same size and alignment, and both are known at compile time, implement the [`Sized`](../std/marker/trait.sized) trait and can be checked with the [`size_of`](../std/mem/fn.size_of) and [`align_of`](../std/mem/fn.align_of) functions. Types that are not [`Sized`](../std/marker/trait.sized) are known as [dynamically sized types](dynamically-sized-types). Since all values of a `Sized` type share the same size and alignment, we refer to those shared values as the size of the type and the alignment of the type respectively. Primitive Data Layout --------------------- The size of most primitives is given in this table. | Type | `size_of::<Type>()` | | --- | --- | | `bool` | 1 | | `u8` / `i8` | 1 | | `u16` / `i16` | 2 | | `u32` / `i32` | 4 | | `u64` / `i64` | 8 | | `u128` / `i128` | 16 | | `f32` | 4 | | `f64` | 8 | | `char` | 4 | `usize` and `isize` have a size big enough to contain every address on the target platform. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes. Most primitives are generally aligned to their size, although this is platform-specific behavior. In particular, on x86 u64 and f64 are only aligned to 32 bits. Pointers and References Layout ------------------------------ Pointers and references have the same layout. Mutability of the pointer or reference does not change the layout. Pointers to sized types have the same size and alignment as `usize`. Pointers to unsized types are sized. The size and alignment is guaranteed to be at least equal to the size and alignment of a pointer. > Note: Though you should not rely on this, all pointers to DSTs are currently twice the size of the size of `usize` and have the same alignment. > > Array Layout ------------ An array of `[T; N]` has a size of `size_of::<T>() * N` and the same alignment of `T`. Arrays are laid out so that the zero-based `nth` element of the array is offset from the start of the array by `n * size_of::<T>()` bytes. Slice Layout ------------ Slices have the same layout as the section of the array they slice. > Note: This is about the raw `[T]` type, not pointers (`&[T]`, `Box<[T]>`, etc.) to slices. > > `str` Layout ------------- String slices are a UTF-8 representation of characters that have the same layout as slices of type `[u8]`. Tuple Layout ------------ Tuples do not have any guarantees about their layout. The exception to this is the unit tuple (`()`) which is guaranteed as a zero-sized type to have a size of 0 and an alignment of 1. Trait Object Layout ------------------- Trait objects have the same layout as the value the trait object is of. > Note: This is about the raw trait object types, not pointers (`&dyn Trait`, `Box<dyn Trait>`, etc.) to trait objects. > > Closure Layout -------------- Closures have no layout guarantees. Representations --------------- All user-defined composite types (`struct`s, `enum`s, and `union`s) have a *representation* that specifies what the layout is for the type. The possible representations for a type are: * [Default](#the-default-representation) * [`C`](#the-c-representation) * The [primitive representations](#primitive-representations) * [`transparent`](#the-transparent-representation) The representation of a type can be changed by applying the `repr` attribute to it. The following example shows a struct with a `C` representation. ``` #![allow(unused)] fn main() { #[repr(C)] struct ThreeInts { first: i16, second: i8, third: i32 } } ``` The alignment may be raised or lowered with the `align` and `packed` modifiers respectively. They alter the representation specified in the attribute. If no representation is specified, the default one is altered. ``` #![allow(unused)] fn main() { // Default representation, alignment lowered to 2. #[repr(packed(2))] struct PackedStruct { first: i16, second: i8, third: i32 } // C representation, alignment raised to 8 #[repr(C, align(8))] struct AlignedStruct { first: i16, second: i8, third: i32 } } ``` > Note: As a consequence of the representation being an attribute on the item, the representation does not depend on generic parameters. Any two types with the same name have the same representation. For example, `Foo<Bar>` and `Foo<Baz>` both have the same representation. > > The representation of a type can change the padding between fields, but does not change the layout of the fields themselves. For example, a struct with a `C` representation that contains a struct `Inner` with the default representation will not change the layout of `Inner`. ### The Default Representation Nominal types without a `repr` attribute have the default representation. Informally, this representation is also called the `rust` representation. There are no guarantees of data layout made by this representation. ### The `C` Representation The `C` representation is designed for dual purposes. One purpose is for creating types that are interoperable with the C Language. The second purpose is to create types that you can soundly perform operations on that rely on data layout such as reinterpreting values as a different type. Because of this dual purpose, it is possible to create types that are not useful for interfacing with the C programming language. This representation can be applied to structs, unions, and enums. The exception is [zero-variant enums](items/enumerations#zero-variant-enums) for which the `C` representation is an error. #### `#[repr(C)]` Structs The alignment of the struct is the alignment of the most-aligned field in it. The size and offset of fields is determined by the following algorithm. Start with a current offset of 0 bytes. For each field in declaration order in the struct, first determine the size and alignment of the field. If the current offset is not a multiple of the field's alignment, then add padding bytes to the current offset until it is a multiple of the field's alignment. The offset for the field is what the current offset is now. Then increase the current offset by the size of the field. Finally, the size of the struct is the current offset rounded up to the nearest multiple of the struct's alignment. Here is this algorithm described in pseudocode. ``` /// Returns the amount of padding needed after `offset` to ensure that the /// following address will be aligned to `alignment`. fn padding_needed_for(offset: usize, alignment: usize) -> usize { let misalignment = offset % alignment; if misalignment > 0 { // round up to next multiple of `alignment` alignment - misalignment } else { // already a multiple of `alignment` 0 } } struct.alignment = struct.fields().map(|field| field.alignment).max(); let current_offset = 0; for field in struct.fields_in_declaration_order() { // Increase the current offset so that it's a multiple of the alignment // of this field. For the first field, this will always be zero. // The skipped bytes are called padding bytes. current_offset += padding_needed_for(current_offset, field.alignment); struct[field].offset = current_offset; current_offset += field.size; } struct.size = current_offset + padding_needed_for(current_offset, struct.alignment); ``` Warning: This pseudocode uses a naive algorithm that ignores overflow issues for the sake of clarity. To perform memory layout computations in actual code, use [`Layout`](../std/alloc/struct.layout). > Note: This algorithm can produce zero-sized structs. In C, an empty struct declaration like `struct Foo { }` is illegal. However, both gcc and clang support options to enable such structs, and assign them size zero. C++, in contrast, gives empty structs a size of 1, unless they are inherited from or they are fields that have the `[[no_unique_address]]` attribute, in which case they do not increase the overall size of the struct. > > #### `#[repr(C)]` Unions A union declared with `#[repr(C)]` will have the same size and alignment as an equivalent C union declaration in the C language for the target platform. The union will have a size of the maximum size of all of its fields rounded to its alignment, and an alignment of the maximum alignment of all of its fields. These maximums may come from different fields. ``` #![allow(unused)] fn main() { #[repr(C)] union Union { f1: u16, f2: [u8; 4], } assert_eq!(std::mem::size_of::<Union>(), 4); // From f2 assert_eq!(std::mem::align_of::<Union>(), 2); // From f1 #[repr(C)] union SizeRoundedUp { a: u32, b: [u16; 3], } assert_eq!(std::mem::size_of::<SizeRoundedUp>(), 8); // Size of 6 from b, // rounded up to 8 from // alignment of a. assert_eq!(std::mem::align_of::<SizeRoundedUp>(), 4); // From a } ``` #### `#[repr(C)]` Field-less Enums For [field-less enums](items/enumerations#custom-discriminant-values-for-fieldless-enumerations), the `C` representation has the size and alignment of the default `enum` size and alignment for the target platform's C ABI. > Note: The enum representation in C is implementation defined, so this is really a "best guess". In particular, this may be incorrect when the C code of interest is compiled with certain flags. > > Warning: There are crucial differences between an `enum` in the C language and Rust's [field-less enums](items/enumerations#custom-discriminant-values-for-fieldless-enumerations) with this representation. An `enum` in C is mostly a `typedef` plus some named constants; in other words, an object of an `enum` type can hold any integer value. For example, this is often used for bitflags in `C`. In contrast, Rust’s [field-less enums](items/enumerations#custom-discriminant-values-for-fieldless-enumerations) can only legally hold the discriminant values, everything else is [undefined behavior](behavior-considered-undefined). Therefore, using a field-less enum in FFI to model a C `enum` is often wrong. #### `#[repr(C)]` Enums With Fields The representation of a `repr(C)` enum with fields is a `repr(C)` struct with two fields, also called a "tagged union" in C: * a `repr(C)` version of the enum with all fields removed ("the tag") * a `repr(C)` union of `repr(C)` structs for the fields of each variant that had them ("the payload") > Note: Due to the representation of `repr(C)` structs and unions, if a variant has a single field there is no difference between putting that field directly in the union or wrapping it in a struct; any system which wishes to manipulate such an `enum`'s representation may therefore use whichever form is more convenient or consistent for them. > > ``` #![allow(unused)] fn main() { // This Enum has the same representation as ... #[repr(C)] enum MyEnum { A(u32), B(f32, u64), C { x: u32, y: u8 }, D, } // ... this struct. #[repr(C)] struct MyEnumRepr { tag: MyEnumDiscriminant, payload: MyEnumFields, } // This is the discriminant enum. #[repr(C)] enum MyEnumDiscriminant { A, B, C, D } // This is the variant union. #[repr(C)] union MyEnumFields { A: MyAFields, B: MyBFields, C: MyCFields, D: MyDFields, } #[repr(C)] #[derive(Copy, Clone)] struct MyAFields(u32); #[repr(C)] #[derive(Copy, Clone)] struct MyBFields(f32, u64); #[repr(C)] #[derive(Copy, Clone)] struct MyCFields { x: u32, y: u8 } // This struct could be omitted (it is a zero-sized type), and it must be in // C/C++ headers. #[repr(C)] #[derive(Copy, Clone)] struct MyDFields; } ``` > Note: `union`s with non-`Copy` fields are unstable, see [55149](https://github.com/rust-lang/rust/issues/55149). > > ### Primitive representations The *primitive representations* are the representations with the same names as the primitive integer types. That is: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`. Primitive representations can only be applied to enumerations and have different behavior whether the enum has fields or no fields. It is an error for [zero-variant enums](items/enumerations#zero-variant-enums) to have a primitive representation. Combining two primitive representations together is an error. #### Primitive Representation of Field-less Enums For [field-less enums](items/enumerations#custom-discriminant-values-for-fieldless-enumerations), primitive representations set the size and alignment to be the same as the primitive type of the same name. For example, a field-less enum with a `u8` representation can only have discriminants between 0 and 255 inclusive. #### Primitive Representation of Enums With Fields The representation of a primitive representation enum is a `repr(C)` union of `repr(C)` structs for each variant with a field. The first field of each struct in the union is the primitive representation version of the enum with all fields removed ("the tag") and the remaining fields are the fields of that variant. > Note: This representation is unchanged if the tag is given its own member in the union, should that make manipulation more clear for you (although to follow the C++ standard the tag member should be wrapped in a `struct`). > > ``` #![allow(unused)] fn main() { // This enum has the same representation as ... #[repr(u8)] enum MyEnum { A(u32), B(f32, u64), C { x: u32, y: u8 }, D, } // ... this union. #[repr(C)] union MyEnumRepr { A: MyVariantA, B: MyVariantB, C: MyVariantC, D: MyVariantD, } // This is the discriminant enum. #[repr(u8)] #[derive(Copy, Clone)] enum MyEnumDiscriminant { A, B, C, D } #[repr(C)] #[derive(Clone, Copy)] struct MyVariantA(MyEnumDiscriminant, u32); #[repr(C)] #[derive(Clone, Copy)] struct MyVariantB(MyEnumDiscriminant, f32, u64); #[repr(C)] #[derive(Clone, Copy)] struct MyVariantC { tag: MyEnumDiscriminant, x: u32, y: u8 } #[repr(C)] #[derive(Clone, Copy)] struct MyVariantD(MyEnumDiscriminant); } ``` > Note: `union`s with non-`Copy` fields are unstable, see [55149](https://github.com/rust-lang/rust/issues/55149). > > #### Combining primitive representations of enums with fields and `#[repr(C)]` For enums with fields, it is also possible to combine `repr(C)` and a primitive representation (e.g., `repr(C, u8)`). This modifies the [`repr(C)`](#reprc-enums-with-fields) by changing the representation of the discriminant enum to the chosen primitive instead. So, if you chose the `u8` representation, then the discriminant enum would have a size and alignment of 1 byte. The discriminant enum from the example [earlier](#reprc-enums-with-fields) then becomes: ``` #![allow(unused)] fn main() { #[repr(C, u8)] // `u8` was added enum MyEnum { A(u32), B(f32, u64), C { x: u32, y: u8 }, D, } // ... #[repr(u8)] // So `u8` is used here instead of `C` enum MyEnumDiscriminant { A, B, C, D } // ... } ``` For example, with a `repr(C, u8)` enum it is not possible to have 257 unique discriminants ("tags") whereas the same enum with only a `repr(C)` attribute will compile without any problems. Using a primitive representation in addition to `repr(C)` can change the size of an enum from the `repr(C)` form: ``` #![allow(unused)] fn main() { #[repr(C)] enum EnumC { Variant0(u8), Variant1, } #[repr(C, u8)] enum Enum8 { Variant0(u8), Variant1, } #[repr(C, u16)] enum Enum16 { Variant0(u8), Variant1, } // The size of the C representation is platform dependant assert_eq!(std::mem::size_of::<EnumC>(), 8); // One byte for the discriminant and one byte for the value in Enum8::Variant0 assert_eq!(std::mem::size_of::<Enum8>(), 2); // Two bytes for the discriminant and one byte for the value in Enum16::Variant0 // plus one byte of padding. assert_eq!(std::mem::size_of::<Enum16>(), 4); } ``` ### The alignment modifiers The `align` and `packed` modifiers can be used to respectively raise or lower the alignment of `struct`s and `union`s. `packed` may also alter the padding between fields (although it will not alter the padding inside of any field). The alignment is specified as an integer parameter in the form of `#[repr(align(x))]` or `#[repr(packed(x))]`. The alignment value must be a power of two from 1 up to 229. For `packed`, if no value is given, as in `#[repr(packed)]`, then the value is 1. For `align`, if the specified alignment is less than the alignment of the type without the `align` modifier, then the alignment is unaffected. For `packed`, if the specified alignment is greater than the type's alignment without the `packed` modifier, then the alignment and layout is unaffected. The alignments of each field, for the purpose of positioning fields, is the smaller of the specified alignment and the alignment of the field's type. Inter-field padding is guaranteed to be the minimum required in order to satisfy each field's (possibly altered) alignment (although note that, on its own, `packed` does not provide any guarantee about field ordering). An important consequence of these rules is that a type with `#[repr(packed(1))]` (or `#[repr(packed)]`) will have no inter-field padding. The `align` and `packed` modifiers cannot be applied on the same type and a `packed` type cannot transitively contain another `align`ed type. `align` and `packed` may only be applied to the [default](#the-default-representation) and [`C`](#the-c-representation) representations. The `align` modifier can also be applied on an `enum`. When it is, the effect on the `enum`'s alignment is the same as if the `enum` was wrapped in a newtype `struct` with the same `align` modifier. ***Warning:*** Dereferencing an unaligned pointer is [undefined behavior](behavior-considered-undefined) and it is possible to [safely create unaligned pointers to `packed` fields](https://github.com/rust-lang/rust/issues/27060). Like all ways to create undefined behavior in safe Rust, this is a bug. ### The `transparent` Representation The `transparent` representation can only be used on a [`struct`](items/structs) or an [`enum`](items/enumerations) with a single variant that has: * a single field with non-zero size, and * any number of fields with size 0 and alignment 1 (e.g. [`PhantomData<T>`](special-types-and-traits#phantomdatat)). Structs and enums with this representation have the same layout and ABI as the single non-zero sized field. This is different than the `C` representation because a struct with the `C` representation will always have the ABI of a `C` `struct` while, for example, a struct with the `transparent` representation with a primitive field will have the ABI of the primitive field. Because this representation delegates type layout to another type, it cannot be used with any other representation.
programming_docs
rust Glossary Glossary ======== ### Abstract syntax tree An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it. ### Alignment The alignment of a value specifies what addresses values are preferred to start at. Always a power of two. References to a value must be aligned. [More](type-layout#size-and-alignment). ### Arity Arity refers to the number of arguments a function or operator takes. For some examples, `f(2, 3)` and `g(4, 6)` have arity 2, while `h(8, 2, 6)` has arity 3. The `!` operator has arity 1. ### Array An array, sometimes also called a fixed-size array or an inline array, is a value describing a collection of elements, each selected by an index that can be computed at run time by the program. It occupies a contiguous region of memory. ### Associated item An associated item is an item that is associated with another item. Associated items are defined in [implementations](items/implementations) and declared in [traits](items/traits). Only functions, constants, and type aliases can be associated. Contrast to a [free item](#free-item). ### Blanket implementation Any implementation where a type appears [uncovered](#uncovered-type). `impl<T> Foo for T`, `impl<T> Bar<T> for T`, `impl<T> Bar<Vec<T>> for T`, and `impl<T> Bar<T> for Vec<T>` are considered blanket impls. However, `impl<T> Bar<Vec<T>> for Vec<T>` is not a blanket impl, as all instances of `T` which appear in this `impl` are covered by `Vec`. ### Bound Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint. ### Combinator Combinators are higher-order functions that apply only functions and earlier defined combinators to provide a result from its arguments. They can be used to manage control flow in a modular fashion. ### Crate A crate is the unit of compilation and linking. There are different [types of crates](linkage), such as libraries or executables. Crates may link and refer to other library crates, called external crates. A crate has a self-contained tree of [modules](items/modules), starting from an unnamed root module called the crate root. [Items](items) may be made visible to other crates by marking them as public in the crate root, including through <paths> of public modules. [More](crates-and-source-files). ### Dispatch Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called ‘trait objects’. ### Dynamically sized type A dynamically sized type (DST) is a type without a statically known size or alignment. ### Entity An [*entity*](names) is a language construct that can be referred to in some way within the source program, usually via a [path](paths). Entities include <types>, <items>, [generic parameters](items/generics), [variable bindings](patterns), [loop labels](tokens#lifetimes-and-loop-labels), [lifetimes](tokens#lifetimes-and-loop-labels), [fields](expressions/field-expr), <attributes>, and [lints](attributes/diagnostics#lint-check-attributes). ### Expression An expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects. For example, `2 + (3 * 4)` is an expression that returns the value 14. ### Free item An [item](items) that is not a member of an [implementation](items/implementations), such as a *free function* or a *free const*. Contrast to an [associated item](#associated-item). ### Fundamental traits A fundamental trait is one where adding an impl of it for an existing type is a breaking change. The `Fn` traits and `Sized` are fundamental. ### Fundamental type constructors A fundamental type constructor is a type where implementing a [blanket implementation](#blanket-implementation) over it is a breaking change. `&`, `&mut`, `Box`, and `Pin` are fundamental. Any time a type `T` is considered [local](#local-type), `&T`, `&mut T`, `Box<T>`, and `Pin<T>` are also considered local. Fundamental type constructors cannot [cover](#uncovered-type) other types. Any time the term "covered type" is used, the `T` in `&T`, `&mut T`, `Box<T>`, and `Pin<T>` is not considered covered. ### Inhabited A type is inhabited if it has constructors and therefore can be instantiated. An inhabited type is not "empty" in the sense that there can be values of the type. Opposite of [Uninhabited](#uninhabited). ### Inherent implementation An [implementation](items/implementations) that applies to a nominal type, not to a trait-type pair. [More](items/implementations#inherent-implementations). ### Inherent method A [method](items/associated-items#methods) defined in an [inherent implementation](items/implementations#inherent-implementations), not in a trait implementation. ### Initialized A variable is initialized if it has been assigned a value and hasn't since been moved from. All other memory locations are assumed to be uninitialized. Only unsafe Rust can create a memory location without initializing it. ### Local trait A `trait` which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given `trait Foo<T, U>`, `Foo` is always local, regardless of the types substituted for `T` and `U`. ### Local type A `struct`, `enum`, or `union` which was defined in the current crate. This is not affected by applied type arguments. `struct Foo` is considered local, but `Vec<Foo>` is not. `LocalType<ForeignType>` is local. Type aliases do not affect locality. ### Module A module is a container for zero or more <items>. Modules are organized in a tree, starting from an unnamed module at the root called the crate root or the root module. [Paths](paths) may be used to refer to items from other modules, which may be restricted by [visibility rules](visibility-and-privacy). [More](items/modules) ### Name A [*name*](names) is an [identifier](identifiers) or [lifetime or loop label](tokens#lifetimes-and-loop-labels) that refers to an [entity](#entity). A *name binding* is when an entity declaration introduces an identifier or label associated with that entity. [Paths](paths), identifiers, and labels are used to refer to an entity. ### Name resolution [*Name resolution*](names/name-resolution) is the compile-time process of tying <paths>, <identifiers>, and [labels](tokens#lifetimes-and-loop-labels) to [entity](#entity) declarations. ### Namespace A *namespace* is a logical grouping of declared [names](#name) based on the kind of [entity](#entity) the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace. Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities. ### Nominal types Types that can be referred to by a path directly. Specifically [enums](items/enumerations), [structs](items/structs), [unions](items/unions), and [trait objects](types/trait-object). ### Object safe traits [Traits](items/traits) that can be used as [trait objects](types/trait-object). Only traits that follow specific [rules](items/traits#object-safety) are object safe. ### Path A [*path*](paths) is a sequence of one or more path segments used to refer to an [entity](#entity) in the current scope or other levels of a [namespace](#namespace) hierarchy. ### Prelude Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive. ### Scope A [*scope*](names/scopes) is the region of source text where a named [entity](#entity) may be referenced with that name. ### Scrutinee A scrutinee is the expression that is matched on in `match` expressions and similar pattern matching constructs. For example, in `match x { A => 1, B => 2 }`, the expression `x` is the scrutinee. ### Size The size of a value has two definitions. The first is that it is how much memory must be allocated to store that value. The second is that it is the offset in bytes between successive elements in an array with that item type. It is a multiple of the alignment, including zero. The size can change depending on compiler version (as new optimizations are made) and target platform (similar to how `usize` varies per-platform). [More](type-layout#size-and-alignment). ### Slice A slice is dynamically-sized view into a contiguous sequence, written as `[T]`. It is often seen in its borrowed forms, either mutable or shared. The shared slice type is `&[T]`, while the mutable slice type is `&mut [T]`, where `T` represents the element type. ### Statement A statement is the smallest standalone element of a programming language that commands a computer to perform an action. ### String literal A string literal is a string stored directly in the final binary, and so will be valid for the `'static` duration. Its type is `'static` duration borrowed string slice, `&'static str`. ### String slice A string slice is the most primitive string type in Rust, written as `str`. It is often seen in its borrowed forms, either mutable or shared. The shared string slice type is `&str`, while the mutable string slice type is `&mut str`. Strings slices are always valid UTF-8. ### Trait A trait is a language item that is used for describing the functionalities a type must provide. It allows a type to make certain promises about its behavior. Generic functions and generic structs can use traits to constrain, or bound, the types they accept. ### Turbofish Paths with generic parameters in expressions must prefix the opening brackets with a `::`. Combined with the angular brackets for generics, this looks like a fish `::<>`. As such, this syntax is colloquially referred to as turbofish syntax. Examples: ``` #![allow(unused)] fn main() { let ok_num = Ok::<_, ()>(5); let vec = [1, 2, 3].iter().map(|n| n * 2).collect::<Vec<_>>(); } ``` This `::` prefix is required to disambiguate generic paths with multiple comparisons in a comma-separate list. See [the bastion of the turbofish](https://github.com/rust-lang/rust/blob/1.58.0/src/test/ui/parser/bastion-of-the-turbofish.rs) for an example where not having the prefix would be ambiguous. ### Uncovered type A type which does not appear as an argument to another type. For example, `T` is uncovered, but the `T` in `Vec<T>` is covered. This is only relevant for type arguments. ### Undefined behavior Compile-time or run-time behavior that is not specified. This may result in, but is not limited to: process termination or corruption; improper, incorrect, or unintended computation; or platform-specific results. [More](behavior-considered-undefined). ### Uninhabited A type is uninhabited if it has no constructors and therefore can never be instantiated. An uninhabited type is "empty" in the sense that there are no values of the type. The canonical example of an uninhabited type is the [never type](types/never) `!`, or an enum with no variants `enum Never { }`. Opposite of [Inhabited](#inhabited). rust Subtyping and Variance Subtyping and Variance ====================== Subtyping is implicit and can occur at any stage in type checking or inference. Subtyping is restricted to two cases: variance with respect to lifetimes and between types with higher ranked lifetimes. If we were to erase lifetimes from types, then the only subtyping would be due to type equality. Consider the following example: string literals always have `'static` lifetime. Nevertheless, we can assign `s` to `t`: ``` #![allow(unused)] fn main() { fn bar<'a>() { let s: &'static str = "hi"; let t: &'a str = s; } } ``` Since `'static` outlives the lifetime parameter `'a`, `&'static str` is a subtype of `&'a str`. [Higher-ranked](https://doc.rust-lang.org/nomicon/hrtb.html) [function pointers](types/function-pointer) and [trait objects](types/trait-object) have another subtype relation. They are subtypes of types that are given by substitutions of the higher-ranked lifetimes. Some examples: ``` #![allow(unused)] fn main() { // Here 'a is substituted for 'static let subtype: &(for<'a> fn(&'a i32) -> &'a i32) = &((|x| x) as fn(&_) -> &_); let supertype: &(fn(&'static i32) -> &'static i32) = subtype; // This works similarly for trait objects let subtype: &(dyn for<'a> Fn(&'a i32) -> &'a i32) = &|x| x; let supertype: &(dyn Fn(&'static i32) -> &'static i32) = subtype; // We can also substitute one higher-ranked lifetime for another let subtype: &(for<'a, 'b> fn(&'a i32, &'b i32))= &((|x, y| {}) as fn(&_, &_)); let supertype: &for<'c> fn(&'c i32, &'c i32) = subtype; } ``` Variance -------- Variance is a property that generic types have with respect to their arguments. A generic type's *variance* in a parameter is how the subtyping of the parameter affects the subtyping of the type. * `F<T>` is *covariant* over `T` if `T` being a subtype of `U` implies that `F<T>` is a subtype of `F<U>` (subtyping "passes through") * `F<T>` is *contravariant* over `T` if `T` being a subtype of `U` implies that `F<U>` is a subtype of `F<T>` * `F<T>` is *invariant* over `T` otherwise (no subtyping relation can be derived) Variance of types is automatically determined as follows | Type | Variance in `'a` | Variance in `T` | | --- | --- | --- | | `&'a T` | covariant | covariant | | `&'a mut T` | covariant | invariant | | `*const T` | | covariant | | `*mut T` | | invariant | | `[T]` and `[T; n]` | | covariant | | `fn() -> T` | | covariant | | `fn(T) -> ()` | | contravariant | | `std::cell::UnsafeCell<T>` | | invariant | | `std::marker::PhantomData<T>` | | covariant | | `dyn Trait<T> + 'a` | covariant | invariant | The variance of other `struct`, `enum`, and `union` types is decided by looking at the variance of the types of their fields. If the parameter is used in positions with different variances then the parameter is invariant. For example the following struct is covariant in `'a` and `T` and invariant in `'b`, `'c`, and `U`. ``` #![allow(unused)] fn main() { use std::cell::UnsafeCell; struct Variance<'a, 'b, 'c, T, U: 'a> { x: &'a U, // This makes `Variance` covariant in 'a, and would // make it covariant in U, but U is used later y: *const T, // Covariant in T z: UnsafeCell<&'b f64>, // Invariant in 'b w: *mut U, // Invariant in U, makes the whole struct invariant f: fn(&'c ()) -> &'c () // Both co- and contravariant, makes 'c invariant // in the struct. } } ``` When used outside of an `struct`, `enum`, or `union`, the variance for parameters is checked at each location separately. ``` #![allow(unused)] fn main() { use std::cell::UnsafeCell; fn generic_tuple<'short, 'long: 'short>( // 'long is used inside of a tuple in both a co- and invariant position. x: (&'long u32, UnsafeCell<&'long u32>), ) { // As the variance at these positions is computed separately, // we can freely shrink 'long in the covariant position. let _: (&'short u32, UnsafeCell<&'long u32>) = x; } fn takes_fn_ptr<'short, 'middle: 'short>( // 'middle is used in both a co- and contravariant position. f: fn(&'middle ()) -> &'middle (), ) { // As the variance at these positions is computed separately, // we can freely shrink 'middle in the covariant position // and extend it in the contravariant position. let _: fn(&'static ()) -> &'short () = f; } } ``` rust Linkage Linkage ======= > Note: This section is described more in terms of the compiler than of the language. > > The compiler supports various methods to link crates together both statically and dynamically. This section will explore the various methods to link crates together, and more information about native libraries can be found in the [FFI section of the book](../book/ch19-01-unsafe-rust#using-extern-functions-to-call-external-code). In one session of compilation, the compiler can generate multiple artifacts through the usage of either command line flags or the `crate_type` attribute. If one or more command line flags are specified, all `crate_type` attributes will be ignored in favor of only building the artifacts specified by command line. * `--crate-type=bin`, `#![crate_type = "bin"]` - A runnable executable will be produced. This requires that there is a `main` function in the crate which will be run when the program begins executing. This will link in all Rust and native dependencies, producing a single distributable binary. This is the default crate type. * `--crate-type=lib`, `#![crate_type = "lib"]` - A Rust library will be produced. This is an ambiguous concept as to what exactly is produced because a library can manifest itself in several forms. The purpose of this generic `lib` option is to generate the "compiler recommended" style of library. The output library will always be usable by rustc, but the actual type of library may change from time-to-time. The remaining output types are all different flavors of libraries, and the `lib` type can be seen as an alias for one of them (but the actual one is compiler-defined). * `--crate-type=dylib`, `#![crate_type = "dylib"]` - A dynamic Rust library will be produced. This is different from the `lib` output type in that this forces dynamic library generation. The resulting dynamic library can be used as a dependency for other libraries and/or executables. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows. * `--crate-type=staticlib`, `#![crate_type = "staticlib"]` - A static system library will be produced. This is different from other library outputs in that the compiler will never attempt to link to `staticlib` outputs. The purpose of this output type is to create a static library containing all of the local crate's code along with all upstream dependencies. This output type will create `*.a` files on Linux, macOS and Windows (MinGW), and `*.lib` files on Windows (MSVC). This format is recommended for use in situations such as linking Rust code into an existing non-Rust application because it will not have dynamic dependencies on other Rust code. * `--crate-type=cdylib`, `#![crate_type = "cdylib"]` - A dynamic system library will be produced. This is used when compiling a dynamic library to be loaded from another language. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows. * `--crate-type=rlib`, `#![crate_type = "rlib"]` - A "Rust library" file will be produced. This is used as an intermediate artifact and can be thought of as a "static Rust library". These `rlib` files, unlike `staticlib` files, are interpreted by the compiler in future linkage. This essentially means that `rustc` will look for metadata in `rlib` files like it looks for metadata in dynamic libraries. This form of output is used to produce statically linked executables as well as `staticlib` outputs. * `--crate-type=proc-macro`, `#![crate_type = "proc-macro"]` - The output produced is not specified, but if a `-L` path is provided to it then the compiler will recognize the output artifacts as a macro and it can be loaded for a program. Crates compiled with this crate type must only export [procedural macros](procedural-macros). The compiler will automatically set the `proc_macro` [configuration option](conditional-compilation). The crates are always compiled with the same target that the compiler itself was built with. For example, if you are executing the compiler from Linux with an `x86_64` CPU, the target will be `x86_64-unknown-linux-gnu` even if the crate is a dependency of another crate being built for a different target. Note that these outputs are stackable in the sense that if multiple are specified, then the compiler will produce each form of output at once without having to recompile. However, this only applies for outputs specified by the same method. If only `crate_type` attributes are specified, then they will all be built, but if one or more `--crate-type` command line flags are specified, then only those outputs will be built. With all these different kinds of outputs, if crate A depends on crate B, then the compiler could find B in various different forms throughout the system. The only forms looked for by the compiler, however, are the `rlib` format and the dynamic library format. With these two options for a dependent library, the compiler must at some point make a choice between these two formats. With this in mind, the compiler follows these rules when determining what format of dependencies will be used: 1. If a static library is being produced, all upstream dependencies are required to be available in `rlib` formats. This requirement stems from the reason that a dynamic library cannot be converted into a static format. Note that it is impossible to link in native dynamic dependencies to a static library, and in this case warnings will be printed about all unlinked native dynamic dependencies. 2. If an `rlib` file is being produced, then there are no restrictions on what format the upstream dependencies are available in. It is simply required that all upstream dependencies be available for reading metadata from. The reason for this is that `rlib` files do not contain any of their upstream dependencies. It wouldn't be very efficient for all `rlib` files to contain a copy of `libstd.rlib`! 3. If an executable is being produced and the `-C prefer-dynamic` flag is not specified, then dependencies are first attempted to be found in the `rlib` format. If some dependencies are not available in an rlib format, then dynamic linking is attempted (see below). 4. If a dynamic library or an executable that is being dynamically linked is being produced, then the compiler will attempt to reconcile the available dependencies in either the rlib or dylib format to create a final product. A major goal of the compiler is to ensure that a library never appears more than once in any artifact. For example, if dynamic libraries B and C were each statically linked to library A, then a crate could not link to B and C together because there would be two copies of A. The compiler allows mixing the rlib and dylib formats, but this restriction must be satisfied. The compiler currently implements no method of hinting what format a library should be linked with. When dynamically linking, the compiler will attempt to maximize dynamic dependencies while still allowing some dependencies to be linked in via an rlib. For most situations, having all libraries available as a dylib is recommended if dynamically linking. For other situations, the compiler will emit a warning if it is unable to determine which formats to link each library with. In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for all compilation needs, and the other options are just available if more fine-grained control is desired over the output format of a crate. Static and dynamic C runtimes ----------------------------- The standard library in general strives to support both statically linked and dynamically linked C runtimes for targets as appropriate. For example the `x86_64-pc-windows-msvc` and `x86_64-unknown-linux-musl` targets typically come with both runtimes and the user selects which one they'd like. All targets in the compiler have a default mode of linking to the C runtime. Typically targets are linked dynamically by default, but there are exceptions which are static by default such as: * `arm-unknown-linux-musleabi` * `arm-unknown-linux-musleabihf` * `armv7-unknown-linux-musleabihf` * `i686-unknown-linux-musl` * `x86_64-unknown-linux-musl` The linkage of the C runtime is configured to respect the `crt-static` target feature. These target features are typically configured from the command line via flags to the compiler itself. For example to enable a static runtime you would execute: ``` rustc -C target-feature=+crt-static foo.rs ``` whereas to link dynamically to the C runtime you would execute: ``` rustc -C target-feature=-crt-static foo.rs ``` Targets which do not support switching between linkage of the C runtime will ignore this flag. It's recommended to inspect the resulting binary to ensure that it's linked as you would expect after the compiler succeeds. Crates may also learn about how the C runtime is being linked. Code on MSVC, for example, needs to be compiled differently (e.g. with `/MT` or `/MD`) depending on the runtime being linked. This is exported currently through the [`cfg` attribute `target_feature` option](conditional-compilation#target_feature): ``` #![allow(unused)] fn main() { #[cfg(target_feature = "crt-static")] fn foo() { println!("the C runtime should be statically linked"); } #[cfg(not(target_feature = "crt-static"))] fn foo() { println!("the C runtime should be dynamically linked"); } } ``` Also note that Cargo build scripts can learn about this feature through [environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts). In a build script you can detect the linkage via: ``` use std::env; fn main() { let linkage = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new()); if linkage.contains("crt-static") { println!("the C runtime will be statically linked"); } else { println!("the C runtime will be dynamically linked"); } } ``` To use this feature locally, you typically will use the `RUSTFLAGS` environment variable to specify flags to the compiler through Cargo. For example to compile a statically linked binary on MSVC you would execute: ``` RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc ```
programming_docs
rust Conditional compilation Conditional compilation ======================= > **Syntax** > *ConfigurationPredicate* : > *ConfigurationOption* > | *ConfigurationAll* > | *ConfigurationAny* > | *ConfigurationNot* > > *ConfigurationOption* : > [IDENTIFIER](identifiers) (`=` ([STRING\_LITERAL](tokens#string-literals) | [RAW\_STRING\_LITERAL](tokens#raw-string-literals)))? > > *ConfigurationAll* > `all` `(` *ConfigurationPredicateList*? `)` > > *ConfigurationAny* > `any` `(` *ConfigurationPredicateList*? `)` > > *ConfigurationNot* > `not` `(` *ConfigurationPredicate* `)` > > *ConfigurationPredicateList* > *ConfigurationPredicate* (`,` *ConfigurationPredicate*)\* `,`? > > *Conditionally compiled source code* is source code that may or may not be considered a part of the source code depending on certain conditions. Source code can be conditionally compiled using the <attributes> [`cfg`](#the-cfg-attribute) and [`cfg_attr`](#the-cfg_attr-attribute) and the built-in [`cfg` macro](#the-cfg-macro). These conditions are based on the target architecture of the compiled crate, arbitrary values passed to the compiler, and a few other miscellaneous things further described below in detail. Each form of conditional compilation takes a *configuration predicate* that evaluates to true or false. The predicate is one of the following: * A configuration option. It is true if the option is set and false if it is unset. * `all()` with a comma separated list of configuration predicates. It is false if at least one predicate is false. If there are no predicates, it is true. * `any()` with a comma separated list of configuration predicates. It is true if at least one predicate is true. If there are no predicates, it is false. * `not()` with a configuration predicate. It is true if its predicate is false and false if its predicate is true. *Configuration options* are names and key-value pairs that are either set or unset. Names are written as a single identifier such as, for example, `unix`. Key-value pairs are written as an identifier, `=`, and then a string. For example, `target_arch = "x86_64"` is a configuration option. > **Note**: Whitespace around the `=` is ignored. `foo="bar"` and `foo = "bar"` are equivalent configuration options. > > Keys are not unique in the set of key-value configuration options. For example, both `feature = "std"` and `feature = "serde"` can be set at the same time. Set Configuration Options ------------------------- Which configuration options are set is determined statically during the compilation of the crate. Certain options are *compiler-set* based on data about the compilation. Other options are *arbitrarily-set*, set based on input passed to the compiler outside of the code. It is not possible to set a configuration option from within the source code of the crate being compiled. > **Note**: For `rustc`, arbitrary-set configuration options are set using the [`--cfg`](https://doc.rust-lang.org/rustc/command-line-arguments.html#--cfg-configure-the-compilation-environment) flag. > > > **Note**: Configuration options with the key `feature` are a convention used by [Cargo](https://doc.rust-lang.org/cargo/reference/features.html) for specifying compile-time options and optional dependencies. > > Warning: It is possible for arbitrarily-set configuration options to have the same value as compiler-set configuration options. For example, it is possible to do `rustc --cfg "unix" program.rs` while compiling to a Windows target, and have both `unix` and `windows` configuration options set at the same time. It is unwise to actually do this. ### `target_arch` Key-value option set once with the target's CPU architecture. The value is similar to the first element of the platform's target triple, but not identical. Example values: * `"x86"` * `"x86_64"` * `"mips"` * `"powerpc"` * `"powerpc64"` * `"arm"` * `"aarch64"` ### `target_feature` Key-value option set for each platform feature available for the current compilation target. Example values: * `"avx"` * `"avx2"` * `"crt-static"` * `"rdrand"` * `"sse"` * `"sse2"` * `"sse4.1"` See the [`target_feature` attribute](attributes/codegen#the-target_feature-attribute) for more details on the available features. An additional feature of `crt-static` is available to the `target_feature` option to indicate that a [static C runtime](linkage#static-and-dynamic-c-runtimes) is available. ### `target_os` Key-value option set once with the target's operating system. This value is similar to the second and third element of the platform's target triple. Example values: * `"windows"` * `"macos"` * `"ios"` * `"linux"` * `"android"` * `"freebsd"` * `"dragonfly"` * `"openbsd"` * `"netbsd"` ### `target_family` Key-value option providing a more generic description of a target, such as the family of the operating systems or architectures that the target generally falls into. Any number of `target_family` key-value pairs can be set. Example values: * `"unix"` * `"windows"` * `"wasm"` ### `unix` and `windows` `unix` is set if `target_family = "unix"` is set and `windows` is set if `target_family = "windows"` is set. ### `target_env` Key-value option set with further disambiguating information about the target platform with information about the ABI or `libc` used. For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty. This value is similar to the fourth element of the platform's target triple. One difference is that embedded ABIs such as `gnueabihf` will simply define `target_env` as `"gnu"`. Example values: * `""` * `"gnu"` * `"msvc"` * `"musl"` * `"sgx"` ### `target_endian` Key-value option set once with either a value of "little" or "big" depending on the endianness of the target's CPU. ### `target_pointer_width` Key-value option set once with the target's pointer width in bits. Example values: * `"16"` * `"32"` * `"64"` ### `target_vendor` Key-value option set once with the vendor of the target. Example values: * `"apple"` * `"fortanix"` * `"pc"` * `"unknown"` ### `test` Enabled when compiling the test harness. Done with `rustc` by using the [`--test`](https://doc.rust-lang.org/rustc/command-line-arguments.html#--test-build-a-test-harness) flag. See [Testing](attributes/testing) for more on testing support. ### `debug_assertions` Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library's [`debug_assert!`](../std/macro.debug_assert) macro. ### `proc_macro` Set when the crate being compiled is being compiled with the `proc_macro` [crate type](linkage). ### `panic` Key-value option set depending on the panic strategy. Note that more values may be added in the future. Example values: * `"abort"` * `"unwind"` Forms of conditional compilation -------------------------------- ### The `cfg` attribute > **Syntax** > *CfgAttrAttribute* : > `cfg` `(` *ConfigurationPredicate* `)` > > The `cfg` [attribute](attributes) conditionally includes the thing it is attached to based on a configuration predicate. It is written as `cfg`, `(`, a configuration predicate, and finally `)`. If the predicate is true, the thing is rewritten to not have the `cfg` attribute on it. If the predicate is false, the thing is removed from the source code. Some examples on functions: ``` #![allow(unused)] fn main() { // The function is only included in the build when compiling for macOS #[cfg(target_os = "macos")] fn macos_only() { // ... } // This function is only included when either foo or bar is defined #[cfg(any(foo, bar))] fn needs_foo_or_bar() { // ... } // This function is only included when compiling for a unixish OS with a 32-bit // architecture #[cfg(all(unix, target_pointer_width = "32"))] fn on_32bit_unix() { // ... } // This function is only included when foo is not defined #[cfg(not(foo))] fn needs_not_foo() { // ... } // This function is only included when the panic strategy is set to unwind #[cfg(panic = "unwind")] fn when_unwinding() { // ... } } ``` The `cfg` attribute is allowed anywhere attributes are allowed. ### The `cfg_attr` attribute > **Syntax** > *CfgAttrAttribute* : > `cfg_attr` `(` *ConfigurationPredicate* `,` *CfgAttrs*? `)` > > *CfgAttrs* : > [*Attr*](attributes) (`,` [*Attr*](attributes))\* `,`? > > The `cfg_attr` [attribute](attributes) conditionally includes <attributes> based on a configuration predicate. When the configuration predicate is true, this attribute expands out to the attributes listed after the predicate. For example, the following module will either be found at `linux.rs` or `windows.rs` based on the target. ``` #[cfg_attr(target_os = "linux", path = "linux.rs")] #[cfg_attr(windows, path = "windows.rs")] mod os; ``` Zero, one, or more attributes may be listed. Multiple attributes will each be expanded into separate attributes. For example: ``` #[cfg_attr(feature = "magic", sparkles, crackles)] fn bewitched() {} // When the `magic` feature flag is enabled, the above will expand to: #[sparkles] #[crackles] fn bewitched() {} ``` > **Note**: The `cfg_attr` can expand to another `cfg_attr`. For example, `#[cfg_attr(target_os = "linux", cfg_attr(feature = "multithreaded", some_other_attribute))]` is valid. This example would be equivalent to `#[cfg_attr(all(target_os = "linux", feature ="multithreaded"), some_other_attribute)]`. > > The `cfg_attr` attribute is allowed anywhere attributes are allowed. ### The `cfg` macro The built-in `cfg` macro takes in a single configuration predicate and evaluates to the `true` literal when the predicate is true and the `false` literal when it is false. For example: ``` #![allow(unused)] fn main() { let machine_kind = if cfg!(unix) { "unix" } else if cfg!(windows) { "windows" } else { "unknown" }; println!("I'm running on a {} machine!", machine_kind); } ``` rust Visibility and Privacy Visibility and Privacy ====================== > **Syntax** > *Visibility* : > `pub` > | `pub` `(` `crate` `)` > | `pub` `(` `self` `)` > | `pub` `(` `super` `)` > | `pub` `(` `in` [*SimplePath*](paths#simple-paths) `)` > > These two terms are often used interchangeably, and what they are attempting to convey is the answer to the question "Can this item be used at this location?" Rust's name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition. To control whether interfaces can be used across modules, Rust checks each use of an item to see whether it should be allowed or not. This is where privacy warnings are generated, or otherwise "you used a private item of another module and weren't allowed to." By default, everything is *private*, with two exceptions: Associated items in a `pub` Trait are public by default; Enum variants in a `pub` enum are also public by default. When an item is declared as `pub`, it can be thought of as being accessible to the outside world. For example: ``` fn main() {} // Declare a private struct struct Foo; // Declare a public struct with a private field pub struct Bar { field: i32, } // Declare a public enum with two public variants pub enum State { PubliclyAccessibleState, PubliclyAccessibleState2, } ``` With the notion of an item being either public or private, Rust allows item accesses in two cases: 1. If an item is public, then it can be accessed externally from some module `m` if you can access all the item's ancestor modules from `m`. You can also potentially be able to name the item through re-exports. See below. 2. If an item is private, it may be accessed by the current module and its descendants. These two cases are surprisingly powerful for creating module hierarchies exposing public APIs while hiding internal implementation details. To help explain, here's a few use cases and what they would entail: * A library developer needs to expose functionality to crates which link against their library. As a consequence of the first case, this means that anything which is usable externally must be `pub` from the root down to the destination item. Any private item in the chain will disallow external accesses. * A crate needs a global available "helper module" to itself, but it doesn't want to expose the helper module as a public API. To accomplish this, the root of the crate's hierarchy would have a private module which then internally has a "public API". Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case. * When writing unit tests for a module, it's often a common idiom to have an immediate child of the module to-be-tested named `mod test`. This module could access any items of the parent module through the second case, meaning that internal implementation details could also be seamlessly tested from the child module. In the second case, it mentions that a private item "can be accessed" by the current module and its descendants, but the exact meaning of accessing an item depends on what the item is. Accessing a module, for example, would mean looking inside of it (to import more items). On the other hand, accessing a function would mean that it is invoked. Additionally, path expressions and import statements are considered to access an item in the sense that the import/expression is only valid if the destination is in the current visibility scope. Here's an example of a program which exemplifies the three cases outlined above: ``` // This module is private, meaning that no external crate can access this // module. Because it is private at the root of this current crate, however, any // module in the crate may access any publicly visible item in this module. mod crate_helper_module { // This function can be used by anything in the current crate pub fn crate_helper() {} // This function *cannot* be used by anything else in the crate. It is not // publicly visible outside of the `crate_helper_module`, so only this // current module and its descendants may access it. fn implementation_detail() {} } // This function is "public to the root" meaning that it's available to external // crates linking against this one. pub fn public_api() {} // Similarly to 'public_api', this module is public so external crates may look // inside of it. pub mod submodule { use crate::crate_helper_module; pub fn my_method() { // Any item in the local crate may invoke the helper module's public // interface through a combination of the two rules above. crate_helper_module::crate_helper(); } // This function is hidden to any module which is not a descendant of // `submodule` fn my_implementation() {} #[cfg(test)] mod test { #[test] fn test_my_implementation() { // Because this module is a descendant of `submodule`, it's allowed // to access private items inside of `submodule` without a privacy // violation. super::my_implementation(); } } } fn main() {} ``` For a Rust program to pass the privacy checking pass, all paths must be valid accesses given the two rules above. This includes all use statements, expressions, types, etc. `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)` ------------------------------------------------------------ In addition to public and private, Rust allows users to declare an item as visible only within a given scope. The rules for `pub` restrictions are as follows: * `pub(in path)` makes an item visible within the provided `path`. `path` must be an ancestor module of the item whose visibility is being declared. * `pub(crate)` makes an item visible within the current crate. * `pub(super)` makes an item visible to the parent module. This is equivalent to `pub(in super)`. * `pub(self)` makes an item visible to the current module. This is equivalent to `pub(in self)` or not using `pub` at all. > **Edition Differences**: Starting with the 2018 edition, paths for `pub(in path)` must start with `crate`, `self`, or `super`. The 2015 edition may also use paths starting with `::` or modules from the crate root. > > Here's an example: ``` pub mod outer_mod { pub mod inner_mod { // This function is visible within `outer_mod` pub(in crate::outer_mod) fn outer_mod_visible_fn() {} // Same as above, this is only valid in the 2015 edition. pub(in outer_mod) fn outer_mod_visible_fn_2015() {} // This function is visible to the entire crate pub(crate) fn crate_visible_fn() {} // This function is visible within `outer_mod` pub(super) fn super_mod_visible_fn() { // This function is visible since we're in the same `mod` inner_mod_visible_fn(); } // This function is visible only within `inner_mod`, // which is the same as leaving it private. pub(self) fn inner_mod_visible_fn() {} } pub fn foo() { inner_mod::outer_mod_visible_fn(); inner_mod::crate_visible_fn(); inner_mod::super_mod_visible_fn(); // This function is no longer visible since we're outside of `inner_mod` // Error! `inner_mod_visible_fn` is private //inner_mod::inner_mod_visible_fn(); } } fn bar() { // This function is still visible since we're in the same crate outer_mod::inner_mod::crate_visible_fn(); // This function is no longer visible since we're outside of `outer_mod` // Error! `super_mod_visible_fn` is private //outer_mod::inner_mod::super_mod_visible_fn(); // This function is no longer visible since we're outside of `outer_mod` // Error! `outer_mod_visible_fn` is private //outer_mod::inner_mod::outer_mod_visible_fn(); outer_mod::foo(); } fn main() { bar() } ``` > **Note:** This syntax only adds another restriction to the visibility of an item. It does not guarantee that the item is visible within all parts of the specified scope. To access an item, all of its parent items up to the current scope must still be visible as well. > > Re-exporting and Visibility --------------------------- Rust allows publicly re-exporting items through a `pub use` directive. Because this is a public directive, this allows the item to be used in the current module through the rules above. It essentially allows public access into the re-exported item. For example, this program is valid: ``` pub use self::implementation::api; mod implementation { pub mod api { pub fn f() {} } } fn main() {} ``` This means that any external crate referencing `implementation::api::f` would receive a privacy violation, while the path `api::f` would be allowed. When re-exporting a private item, it can be thought of as allowing the "privacy chain" being short-circuited through the reexport instead of passing through the namespace hierarchy as it normally would. rust Items Items ===== > **Syntax:** > *Item*: > [*OuterAttribute*](attributes)\* > *VisItem* > | *MacroItem* > > *VisItem*: > [*Visibility*](visibility-and-privacy)? > ( > [*Module*](items/modules) > | [*ExternCrate*](items/extern-crates) > | [*UseDeclaration*](items/use-declarations) > | [*Function*](items/functions) > | [*TypeAlias*](items/type-aliases) > | [*Struct*](items/structs) > | [*Enumeration*](items/enumerations) > | [*Union*](items/unions) > | [*ConstantItem*](items/constant-items) > | [*StaticItem*](items/static-items) > | [*Trait*](items/traits) > | [*Implementation*](items/implementations) > | [*ExternBlock*](items/external-blocks) > ) > > *MacroItem*: > [*MacroInvocationSemi*](macros#macro-invocation) > | [*MacroRulesDefinition*](macros-by-example) > > An *item* is a component of a crate. Items are organized within a crate by a nested set of [modules](items/modules). Every crate has a single "outermost" anonymous module; all further items within the crate have <paths> within the module tree of the crate. Items are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory. There are several kinds of items: * [modules](items/modules) * [`extern crate` declarations](items/extern-crates) * [`use` declarations](items/use-declarations) * [function definitions](items/functions) * [type definitions](items/type-aliases) * [struct definitions](items/structs) * [enumeration definitions](items/enumerations) * [union definitions](items/unions) * [constant items](items/constant-items) * [static items](items/static-items) * [trait definitions](items/traits) * [implementations](items/implementations) * [`extern` blocks](items/external-blocks) Some items form an implicit scope for the declaration of sub-items. In other words, within a function or module, declarations of items can (in many cases) be mixed with the statements, control blocks, and similar artifacts that otherwise compose the item body. The meaning of these scoped items is the same as if the item was declared outside the scope — it is still a static item — except that the item's *path name* within the module namespace is qualified by the name of the enclosing item, or is private to the enclosing item (in the case of functions). The grammar specifies the exact locations in which sub-item declarations may appear.
programming_docs
rust Types Types ===== Every variable, item, and value in a Rust program has a type. The *type* of a *value* defines the interpretation of the memory holding it and the operations that may be performed on the value. Built-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types. User-defined types have limited capabilities. The list of types is: * Primitive types: + [Boolean](types/boolean) — `bool` + [Numeric](types/numeric) — integer and float + [Textual](types/textual) — `char` and `str` + [Never](types/never) — `!` — a type with no values * Sequence types: + [Tuple](types/tuple) + [Array](types/array) + [Slice](types/slice) * User-defined types: + [Struct](types/struct) + [Enum](types/enum) + [Union](types/union) * Function types: + [Functions](types/function-item) + [Closures](types/closure) * Pointer types: + [References](types/pointer#shared-references-) + [Raw pointers](types/pointer#raw-pointers-const-and-mut) + [Function pointers](types/function-pointer) * Trait types: + [Trait objects](types/trait-object) + [Impl trait](types/impl-trait) Type expressions ---------------- > **Syntax** > *Type* : > *TypeNoBounds* > | [*ImplTraitType*](types/impl-trait) > | [*TraitObjectType*](types/trait-object) > > *TypeNoBounds* : > [*ParenthesizedType*](types#parenthesized-types) > | [*ImplTraitTypeOneBound*](types/impl-trait) > | [*TraitObjectTypeOneBound*](types/trait-object) > | [*TypePath*](paths#paths-in-types) > | [*TupleType*](types/tuple#tuple-types) > | [*NeverType*](types/never) > | [*RawPointerType*](types/pointer#raw-pointers-const-and-mut) > | [*ReferenceType*](types/pointer#shared-references-) > | [*ArrayType*](types/array) > | [*SliceType*](types/slice) > | [*InferredType*](types/inferred) > | [*QualifiedPathInType*](paths#qualified-paths) > | [*BareFunctionType*](types/function-pointer) > | [*MacroInvocation*](macros#macro-invocation) > > A *type expression* as defined in the *Type* grammar rule above is the syntax for referring to a type. It may refer to: * Sequence types ([tuple](types/tuple), [array](types/array), [slice](types/slice)). * [Type paths](paths#paths-in-types) which can reference: + Primitive types ([boolean](types/boolean), [numeric](types/numeric), [textual](types/textual)). + Paths to an [item](items) ([struct](types/struct), [enum](types/enum), [union](types/union), [type alias](items/type-aliases), [trait](types/trait-object)). + [`Self` path](paths#self-1) where `Self` is the implementing type. + Generic [type parameters](types/parameters). * Pointer types ([reference](types/pointer#shared-references-), [raw pointer](types/pointer#raw-pointers-const-and-mut), [function pointer](types/function-pointer)). * The [inferred type](types/inferred) which asks the compiler to determine the type. * [Parentheses](#parenthesized-types) which are used for disambiguation. * Trait types: [Trait objects](types/trait-object) and [impl trait](types/impl-trait). * The [never](types/never) type. * [Macros](macros) which expand to a type expression. ### Parenthesized types > *ParenthesizedType* : > `(` [*Type*](types#type-expressions) `)` > > In some situations the combination of types may be ambiguous. Use parentheses around a type to avoid ambiguity. For example, the `+` operator for [type boundaries](trait-bounds) within a [reference type](types/pointer#shared-references-) is unclear where the boundary applies, so the use of parentheses is required. Grammar rules that require this disambiguation use the [*TypeNoBounds*](types#type-expressions) rule instead of [*Type*](types#type-expressions). ``` #![allow(unused)] fn main() { use std::any::Any; type T<'a> = &'a (dyn Any + Send); } ``` Recursive types --------------- Nominal types — [structs](types/struct), [enumerations](types/enum), and [unions](types/union) — may be recursive. That is, each `enum` variant or `struct` or `union` field may refer, directly or indirectly, to the enclosing `enum` or `struct` type itself. Such recursion has restrictions: * Recursive types must include a nominal type in the recursion (not mere [type aliases](items/type-aliases), or other structural types such as [arrays](types/array) or [tuples](types/tuple)). So `type Rec = &'static [Rec]` is not allowed. * The size of a recursive type must be finite; in other words the recursive fields of the type must be [pointer types](types/pointer). An example of a *recursive* type and its use: ``` #![allow(unused)] fn main() { enum List<T> { Nil, Cons(T, Box<List<T>>) } let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil)))); } ``` rust Comments Comments ======== > **Lexer** > LINE\_COMMENT : > `//` (~[`/` `!`] | `//`) ~`\n`\* > | `//` > > BLOCK\_COMMENT : > `/*` (~[`*` `!`] | `**` | *BlockCommentOrDoc*) (*BlockCommentOrDoc* | ~`*/`)\* `*/` > | `/**/` > | `/***/` > > INNER\_LINE\_DOC : > `//!` ~[`\n` *IsolatedCR*]\* > > INNER\_BLOCK\_DOC : > `/*!` ( *BlockCommentOrDoc* | ~[`*/` *IsolatedCR*] )\* `*/` > > OUTER\_LINE\_DOC : > `///` (~`/` ~[`\n` *IsolatedCR*]\*)? > > OUTER\_BLOCK\_DOC : > `/**` (~`*` | *BlockCommentOrDoc* ) (*BlockCommentOrDoc* | ~[`*/` *IsolatedCR*])\* `*/` > > *BlockCommentOrDoc* : > BLOCK\_COMMENT > | OUTER\_BLOCK\_DOC > | INNER\_BLOCK\_DOC > > *IsolatedCR* : > *A `\r` not followed by a `\n`* > > Non-doc comments ---------------- Comments follow the general C++ style of line (`//`) and block (`/* ... */`) comment forms. Nested block comments are supported. Non-doc comments are interpreted as a form of whitespace. Doc comments ------------ Line doc comments beginning with exactly *three* slashes (`///`), and block doc comments (`/** ... */`), both inner doc comments, are interpreted as a special syntax for [`doc` attributes](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html). That is, they are equivalent to writing `#[doc="..."]` around the body of the comment, i.e., `/// Foo` turns into `#[doc="Foo"]` and `/** Bar */` turns into `#[doc="Bar"]`. Line comments beginning with `//!` and block comments `/*! ... */` are doc comments that apply to the parent of the comment, rather than the item that follows. That is, they are equivalent to writing `#![doc="..."]` around the body of the comment. `//!` comments are usually used to document modules that occupy a source file. Isolated CRs (`\r`), i.e. not followed by LF (`\n`), are not allowed in doc comments. Examples -------- ``` #![allow(unused)] fn main() { //! A doc comment that applies to the implicit anonymous module of this crate pub mod outer_module { //! - Inner line doc //!! - Still an inner line doc (but with a bang at the beginning) /*! - Inner block doc */ /*!! - Still an inner block doc (but with a bang at the beginning) */ // - Only a comment /// - Outer line doc (exactly 3 slashes) //// - Only a comment /* - Only a comment */ /** - Outer block doc (exactly) 2 asterisks */ /*** - Only a comment */ pub mod inner_module {} pub mod nested_comments { /* In Rust /* we can /* nest comments */ */ */ // All three types of block comments can contain or be nested inside // any other type: /* /* */ /** */ /*! */ */ /*! /* */ /** */ /*! */ */ /** /* */ /** */ /*! */ */ pub mod dummy_item {} } pub mod degenerate_cases { // empty inner line doc //! // empty inner block doc /*!*/ // empty line comment // // empty outer line doc /// // empty block comment /**/ pub mod dummy_item {} // empty 2-asterisk block isn't a doc block, it is a block comment /***/ } /* The next one isn't allowed because outer doc comments require an item that will receive the doc */ /// Where is my item? mod boo {} } } ``` rust Procedural Macros Procedural Macros ================= *Procedural macros* allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors: * [Function-like macros](#function-like-procedural-macros) - `custom!(...)` * [Derive macros](#derive-macros) - `#[derive(CustomDerive)]` * [Attribute macros](#attribute-macros) - `#[CustomAttribute]` Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST. Procedural macros must be defined in a crate with the [crate type](linkage) of `proc-macro`. > **Note**: When using Cargo, Procedural macro crates are defined with the `proc-macro` key in your manifest: > > > ``` > [lib] > proc-macro = true > > ``` > As functions, they must either return syntax, panic, or loop endlessly. Returned syntax either replaces or adds the syntax depending on the kind of procedural macro. Panics are caught by the compiler and are turned into a compiler error. Endless loops are not caught by the compiler which hangs the compiler. Procedural macros run during compilation, and thus have the same resources that the compiler has. For example, standard input, error, and output are the same that the compiler has access to. Similarly, file access is the same. Because of this, procedural macros have the same security concerns that [Cargo's build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html) have. Procedural macros have two ways of reporting errors. The first is to panic. The second is to emit a [`compile_error`](../std/macro.compile_error) macro invocation. ### The `proc_macro` crate Procedural macro crates almost always will link to the compiler-provided [`proc_macro` crate](https://doc.rust-lang.org/proc_macro/index.html). The `proc_macro` crate provides types required for writing procedural macros and facilities to make it easier. This crate primarily contains a [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) type. Procedural macros operate over *token streams* instead of AST nodes, which is a far more stable interface over time for both the compiler and for procedural macros to target. A *token stream* is roughly equivalent to `Vec<TokenTree>` where a `TokenTree` can roughly be thought of as lexical token. For example `foo` is an `Ident` token, `.` is a `Punct` token, and `1.2` is a `Literal` token. The `TokenStream` type, unlike `Vec<TokenTree>`, is cheap to clone. All tokens have an associated `Span`. A `Span` is an opaque value that cannot be modified but can be manufactured. `Span`s represent an extent of source code within a program and are primarily used for error reporting. While you cannot modify a `Span` itself, you can always change the `Span` *associated* with any token, such as through getting a `Span` from another token. ### Procedural macro hygiene Procedural macros are *unhygienic*. This means they behave as if the output token stream was simply written inline to the code it's next to. This means that it's affected by external items and also affects external imports. Macro authors need to be careful to ensure their macros work in as many contexts as possible given this limitation. This often includes using absolute paths to items in libraries (for example, `::std::option::Option` instead of `Option`) or by ensuring that generated functions have names that are unlikely to clash with other functions (like `__internal_foo` instead of `foo`). ### Function-like procedural macros *Function-like procedural macros* are procedural macros that are invoked using the macro invocation operator (`!`). These macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro` [attribute](attributes) and a signature of `(TokenStream) -> TokenStream`. The input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is what is inside the delimiters of the macro invocation and the output [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) replaces the entire macro invocation. For example, the following macro definition ignores its input and outputs a function `answer` into its scope. ``` #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro] pub fn make_answer(_item: TokenStream) -> TokenStream { "fn answer() -> u32 { 42 }".parse().unwrap() } ``` And then we use it in a binary crate to print "42" to standard output. ``` extern crate proc_macro_examples; use proc_macro_examples::make_answer; make_answer!(); fn main() { println!("{}", answer()); } ``` Function-like procedural macros may be invoked in any macro invocation position, which includes <statements>, <expressions>, <patterns>, [type expressions](types#type-expressions), [item](items) positions, including items in [`extern` blocks](items/external-blocks), inherent and trait [implementations](items/implementations), and [trait definitions](items/traits). ### Derive macros *Derive macros* define new inputs for the [`derive` attribute](attributes/derive). These macros can create new <items> given the token stream of a [struct](items/structs), [enum](items/enumerations), or [union](items/unions). They can also define [derive macro helper attributes](#derive-macro-helper-attributes). Custom derive macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro_derive` attribute and a signature of `(TokenStream) -> TokenStream`. The input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the token stream of the item that has the `derive` attribute on it. The output [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) must be a set of items that are then appended to the [module](items/modules) or [block](expressions/block-expr) that the item from the input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is in. The following is an example of a derive macro. Instead of doing anything useful with its input, it just appends a function `answer`. ``` #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(AnswerFn)] pub fn derive_answer_fn(_item: TokenStream) -> TokenStream { "fn answer() -> u32 { 42 }".parse().unwrap() } ``` And then using said derive macro: ``` extern crate proc_macro_examples; use proc_macro_examples::AnswerFn; #[derive(AnswerFn)] struct Struct; fn main() { assert_eq!(42, answer()); } ``` #### Derive macro helper attributes Derive macros can add additional <attributes> into the scope of the [item](items) they are on. Said attributes are called *derive macro helper attributes*. These attributes are [inert](attributes#active-and-inert-attributes), and their only purpose is to be fed into the derive macro that defined them. That said, they can be seen by all macros. The way to define helper attributes is to put an `attributes` key in the `proc_macro_derive` macro with a comma separated list of identifiers that are the names of the helper attributes. For example, the following derive macro defines a helper attribute `helper`, but ultimately doesn't do anything with it. ``` #![crate_type="proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(HelperAttr, attributes(helper))] pub fn derive_helper_attr(_item: TokenStream) -> TokenStream { TokenStream::new() } ``` And then usage on the derive macro on a struct: ``` #[derive(HelperAttr)] struct Struct { #[helper] field: () } ``` ### Attribute macros *Attribute macros* define new [outer attributes](attributes) which can be attached to <items>, including items in [`extern` blocks](items/external-blocks), inherent and trait [implementations](items/implementations), and [trait definitions](items/traits). Attribute macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro_attribute` [attribute](attributes) that has a signature of `(TokenStream, TokenStream) -> TokenStream`. The first [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the delimited token tree following the attribute's name, not including the outer delimiters. If the attribute is written as a bare attribute name, the attribute [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is empty. The second [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the rest of the [item](items) including other <attributes> on the [item](items). The returned [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) replaces the [item](items) with an arbitrary number of <items>. For example, this attribute macro takes the input stream and returns it as is, effectively being the no-op of attributes. ``` #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream { item } ``` This following example shows the stringified [`TokenStream`s](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) that the attribute macros see. The output will show in the output of the compiler. The output is shown in the comments after the function prefixed with "out:". ``` // my-macro/src/lib.rs extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream { println!("attr: \"{}\"", attr.to_string()); println!("item: \"{}\"", item.to_string()); item } ``` ``` // src/lib.rs extern crate my_macro; use my_macro::show_streams; // Example: Basic function #[show_streams] fn invoke1() {} // out: attr: "" // out: item: "fn invoke1() { }" // Example: Attribute with input #[show_streams(bar)] fn invoke2() {} // out: attr: "bar" // out: item: "fn invoke2() {}" // Example: Multiple tokens in the input #[show_streams(multiple => tokens)] fn invoke3() {} // out: attr: "multiple => tokens" // out: item: "fn invoke3() {}" // Example: #[show_streams { delimiters }] fn invoke4() {} // out: attr: "delimiters" // out: item: "fn invoke4() {}" ``` ### Declarative macro tokens and procedural macro tokens Declarative `macro_rules` macros and procedural macros use similar, but different definitions for tokens (or rather [`TokenTree`s](https://doc.rust-lang.org/proc_macro/enum.TokenTree.html).) Token trees in `macro_rules` (corresponding to `tt` matchers) are defined as * Delimited groups (`(...)`, `{...}`, etc) * All operators supported by the language, both single-character and multi-character ones (`+`, `+=`). + Note that this set doesn't include the single quote `'`. * Literals (`"string"`, `1`, etc) + Note that negation (e.g. `-1`) is never a part of such literal tokens, but a separate operator token. * Identifiers, including keywords (`ident`, `r#ident`, `fn`) * Lifetimes (`'ident`) * Metavariable substitutions in `macro_rules` (e.g. `$my_expr` in `macro_rules! mac { ($my_expr: expr) => { $my_expr } }` after the `mac`'s expansion, which will be considered a single token tree regardless of the passed expression) Token trees in procedural macros are defined as * Delimited groups (`(...)`, `{...}`, etc) * All punctuation characters used in operators supported by the language (`+`, but not `+=`), and also the single quote `'` character (typically used in lifetimes, see below for lifetime splitting and joining behavior) * Literals (`"string"`, `1`, etc) + Negation (e.g. `-1`) is supported as a part of integer and floating point literals. * Identifiers, including keywords (`ident`, `r#ident`, `fn`) Mismatches between these two definitions are accounted for when token streams are passed to and from procedural macros. Note that the conversions below may happen lazily, so they might not happen if the tokens are not actually inspected. When passed to a proc-macro * All multi-character operators are broken into single characters. * Lifetimes are broken into a `'` character and an identifier. * All metavariable substitutions are represented as their underlying token streams. + Such token streams may be wrapped into delimited groups ([`Group`](https://doc.rust-lang.org/proc_macro/struct.Group.html)) with implicit delimiters ([`Delimiter::None`](https://doc.rust-lang.org/proc_macro/enum.Delimiter.html#variant.None)) when it's necessary for preserving parsing priorities. + `tt` and `ident` substitutions are never wrapped into such groups and always represented as their underlying token trees. When emitted from a proc macro * Punctuation characters are glued into multi-character operators when applicable. * Single quotes `'` joined with identifiers are glued into lifetimes. * Negative literals are converted into two tokens (the `-` and the literal) possibly wrapped into a delimited group ([`Group`](https://doc.rust-lang.org/proc_macro/struct.Group.html)) with implicit delimiters ([`Delimiter::None`](https://doc.rust-lang.org/proc_macro/enum.Delimiter.html#variant.None)) when it's necessary for preserving parsing priorities. Note that neither declarative nor procedural macros support doc comment tokens (e.g. `/// Doc`), so they are always converted to token streams representing their equivalent `#[doc = r"str"]` attributes when passed to macros.
programming_docs
rust Appendix: Macro Follow-Set Ambiguity Formal Specification Appendix: Macro Follow-Set Ambiguity Formal Specification ========================================================= This page documents the formal specification of the follow rules for [Macros By Example](macros-by-example). They were originally specified in [RFC 550](https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.md), from which the bulk of this text is copied, and expanded upon in subsequent RFCs. Definitions & Conventions ------------------------- * `macro`: anything invokable as `foo!(...)` in source code. * `MBE`: macro-by-example, a macro defined by `macro_rules`. * `matcher`: the left-hand-side of a rule in a `macro_rules` invocation, or a subportion thereof. * `macro parser`: the bit of code in the Rust parser that will parse the input using a grammar derived from all of the matchers. * `fragment`: The class of Rust syntax that a given matcher will accept (or "match"). * `repetition` : a fragment that follows a regular repeating pattern * `NT`: non-terminal, the various "meta-variables" or repetition matchers that can appear in a matcher, specified in MBE syntax with a leading `$` character. * `simple NT`: a "meta-variable" non-terminal (further discussion below). * `complex NT`: a repetition matching non-terminal, specified via repetition operators (`*`, `+`, `?`). * `token`: an atomic element of a matcher; i.e. identifiers, operators, open/close delimiters, *and* simple NT's. * `token tree`: a tree structure formed from tokens (the leaves), complex NT's, and finite sequences of token trees. * `delimiter token`: a token that is meant to divide the end of one fragment and the start of the next fragment. * `separator token`: an optional delimiter token in an complex NT that separates each pair of elements in the matched repetition. * `separated complex NT`: a complex NT that has its own separator token. * `delimited sequence`: a sequence of token trees with appropriate open- and close-delimiters at the start and end of the sequence. * `empty fragment`: The class of invisible Rust syntax that separates tokens, i.e. whitespace, or (in some lexical contexts), the empty token sequence. * `fragment specifier`: The identifier in a simple NT that specifies which fragment the NT accepts. * `language`: a context-free language. Example: ``` #![allow(unused)] fn main() { macro_rules! i_am_an_mbe { (start $foo:expr $($i:ident),* end) => ($foo) } } ``` `(start $foo:expr $($i:ident),* end)` is a matcher. The whole matcher is a delimited sequence (with open- and close-delimiters `(` and `)`), and `$foo` and `$i` are simple NT's with `expr` and `ident` as their respective fragment specifiers. `$(i:ident),*` is *also* an NT; it is a complex NT that matches a comma-separated repetition of identifiers. The `,` is the separator token for the complex NT; it occurs in between each pair of elements (if any) of the matched fragment. Another example of a complex NT is `$(hi $e:expr ;)+`, which matches any fragment of the form `hi <expr>; hi <expr>; ...` where `hi <expr>;` occurs at least once. Note that this complex NT does not have a dedicated separator token. (Note that Rust's parser ensures that delimited sequences always occur with proper nesting of token tree structure and correct matching of open- and close-delimiters.) We will tend to use the variable "M" to stand for a matcher, variables "t" and "u" for arbitrary individual tokens, and the variables "tt" and "uu" for arbitrary token trees. (The use of "tt" does present potential ambiguity with its additional role as a fragment specifier; but it will be clear from context which interpretation is meant.) "SEP" will range over separator tokens, "OP" over the repetition operators `*`, `+`, and `?`, "OPEN"/"CLOSE" over matching token pairs surrounding a delimited sequence (e.g. `[` and `]`). Greek letters "α" "β" "γ" "δ" stand for potentially empty token-tree sequences. (However, the Greek letter "ε" (epsilon) has a special role in the presentation and does not stand for a token-tree sequence.) * This Greek letter convention is usually just employed when the presence of a sequence is a technical detail; in particular, when we wish to *emphasize* that we are operating on a sequence of token-trees, we will use the notation "tt ..." for the sequence, not a Greek letter. Note that a matcher is merely a token tree. A "simple NT", as mentioned above, is an meta-variable NT; thus it is a non-repetition. For example, `$foo:ty` is a simple NT but `$($foo:ty)+` is a complex NT. Note also that in the context of this formalism, the term "token" generally *includes* simple NTs. Finally, it is useful for the reader to keep in mind that according to the definitions of this formalism, no simple NT matches the empty fragment, and likewise no token matches the empty fragment of Rust syntax. (Thus, the *only* NT that can match the empty fragment is a complex NT.) This is not actually true, because the `vis` matcher can match an empty fragment. Thus, for the purposes of the formalism, we will treat `$v:vis` as actually being `$($v:vis)?`, with a requirement that the matcher match an empty fragment. ### The Matcher Invariants To be valid, a matcher must meet the following three invariants. The definitions of FIRST and FOLLOW are described later. 1. For any two successive token tree sequences in a matcher `M` (i.e. `M = ... tt uu ...`) with `uu ...` nonempty, we must have FOLLOW(`... tt`) ∪ {ε} ⊇ FIRST(`uu ...`). 2. For any separated complex NT in a matcher, `M = ... $(tt ...) SEP OP ...`, we must have `SEP` ∈ FOLLOW(`tt ...`). 3. For an unseparated complex NT in a matcher, `M = ... $(tt ...) OP ...`, if OP = `*` or `+`, we must have FOLLOW(`tt ...`) ⊇ FIRST(`tt ...`). The first invariant says that whatever actual token that comes after a matcher, if any, must be somewhere in the predetermined follow set. This ensures that a legal macro definition will continue to assign the same determination as to where `... tt` ends and `uu ...` begins, even as new syntactic forms are added to the language. The second invariant says that a separated complex NT must use a separator token that is part of the predetermined follow set for the internal contents of the NT. This ensures that a legal macro definition will continue to parse an input fragment into the same delimited sequence of `tt ...`'s, even as new syntactic forms are added to the language. The third invariant says that when we have a complex NT that can match two or more copies of the same thing with no separation in between, it must be permissible for them to be placed next to each other as per the first invariant. This invariant also requires they be nonempty, which eliminates a possible ambiguity. **NOTE: The third invariant is currently unenforced due to historical oversight and significant reliance on the behaviour. It is currently undecided what to do about this going forward. Macros that do not respect the behaviour may become invalid in a future edition of Rust. See the [tracking issue](https://github.com/rust-lang/rust/issues/56575).** ### FIRST and FOLLOW, informally A given matcher M maps to three sets: FIRST(M), LAST(M) and FOLLOW(M). Each of the three sets is made up of tokens. FIRST(M) and LAST(M) may also contain a distinguished non-token element ε ("epsilon"), which indicates that M can match the empty fragment. (But FOLLOW(M) is always just a set of tokens.) Informally: * FIRST(M): collects the tokens potentially used first when matching a fragment to M. * LAST(M): collects the tokens potentially used last when matching a fragment to M. * FOLLOW(M): the set of tokens allowed to follow immediately after some fragment matched by M. In other words: t ∈ FOLLOW(M) if and only if there exists (potentially empty) token sequences α, β, γ, δ where: + M matches β, + t matches γ, and + The concatenation α β γ δ is a parseable Rust program. We use the shorthand ANYTOKEN to denote the set of all tokens (including simple NTs). For example, if any token is legal after a matcher M, then FOLLOW(M) = ANYTOKEN. (To review one's understanding of the above informal descriptions, the reader at this point may want to jump ahead to the [examples of FIRST/LAST](#examples-of-first-and-last) before reading their formal definitions.) ### FIRST, LAST Below are formal inductive definitions for FIRST and LAST. "A ∪ B" denotes set union, "A ∩ B" denotes set intersection, and "A \ B" denotes set difference (i.e. all elements of A that are not present in B). #### FIRST FIRST(M) is defined by case analysis on the sequence M and the structure of its first token-tree (if any): * if M is the empty sequence, then FIRST(M) = { ε }, * if M starts with a token t, then FIRST(M) = { t }, (Note: this covers the case where M starts with a delimited token-tree sequence, `M = OPEN tt ... CLOSE ...`, in which case `t = OPEN` and thus FIRST(M) = { `OPEN` }.) (Note: this critically relies on the property that no simple NT matches the empty fragment.) * Otherwise, M is a token-tree sequence starting with a complex NT: `M = $( tt ... ) OP α`, or `M = $( tt ... ) SEP OP α`, (where `α` is the (potentially empty) sequence of token trees for the rest of the matcher). + Let SEP\_SET(M) = { SEP } if SEP is present and ε ∈ FIRST(`tt ...`); otherwise SEP\_SET(M) = {}. * Let ALPHA\_SET(M) = FIRST(`α`) if OP = `*` or `?` and ALPHA\_SET(M) = {} if OP = `+`. * FIRST(M) = (FIRST(`tt ...`) \ {ε}) ∪ SEP\_SET(M) ∪ ALPHA\_SET(M). The definition for complex NTs deserves some justification. SEP\_SET(M) defines the possibility that the separator could be a valid first token for M, which happens when there is a separator defined and the repeated fragment could be empty. ALPHA\_SET(M) defines the possibility that the complex NT could be empty, meaning that M's valid first tokens are those of the following token-tree sequences `α`. This occurs when either `*` or `?` is used, in which case there could be zero repetitions. In theory, this could also occur if `+` was used with a potentially-empty repeating fragment, but this is forbidden by the third invariant. From there, clearly FIRST(M) can include any token from SEP\_SET(M) or ALPHA\_SET(M), and if the complex NT match is nonempty, then any token starting FIRST(`tt ...`) could work too. The last piece to consider is ε. SEP\_SET(M) and FIRST(`tt ...`) \ {ε} cannot contain ε, but ALPHA\_SET(M) could. Hence, this definition allows M to accept ε if and only if ε ∈ ALPHA\_SET(M) does. This is correct because for M to accept ε in the complex NT case, both the complex NT and α must accept it. If OP = `+`, meaning that the complex NT cannot be empty, then by definition ε ∉ ALPHA\_SET(M). Otherwise, the complex NT can accept zero repetitions, and then ALPHA\_SET(M) = FOLLOW(`α`). So this definition is correct with respect to \varepsilon as well. #### LAST LAST(M), defined by case analysis on M itself (a sequence of token-trees): * if M is the empty sequence, then LAST(M) = { ε } * if M is a singleton token t, then LAST(M) = { t } * if M is the singleton complex NT repeating zero or more times, `M = $( tt ... ) *`, or `M = $( tt ... ) SEP *` + Let sep\_set = { SEP } if SEP present; otherwise sep\_set = {}. + if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep\_set + otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) ∪ {ε}. * if M is the singleton complex NT repeating one or more times, `M = $( tt ... ) +`, or `M = $( tt ... ) SEP +` + Let sep\_set = { SEP } if SEP present; otherwise sep\_set = {}. + if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep\_set + otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) * if M is the singleton complex NT repeating zero or one time, `M = $( tt ...) ?`, then LAST(M) = LAST(`tt ...`) ∪ {ε}. * if M is a delimited token-tree sequence `OPEN tt ... CLOSE`, then LAST(M) = { `CLOSE` }. * if M is a non-empty sequence of token-trees `tt uu ...`, + If ε ∈ LAST(`uu ...`), then LAST(M) = LAST(`tt`) ∪ (LAST(`uu ...`) \ { ε }). + Otherwise, the sequence `uu ...` must be non-empty; then LAST(M) = LAST(`uu ...`). ### Examples of FIRST and LAST Below are some examples of FIRST and LAST. (Note in particular how the special ε element is introduced and eliminated based on the interaction between the pieces of the input.) Our first example is presented in a tree structure to elaborate on how the analysis of the matcher composes. (Some of the simpler subtrees have been elided.) ``` INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~ ~~~~~~~ ~ | | | FIRST: { $d:ident } { $e:expr } { h } INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ ~~~~~~~~~~~~~~~~~~ ~~~~~~~ ~~~ | | | FIRST: { $d:ident } { h, ε } { f } INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ~~~~~~~~~ ~ | | | | FIRST: { $d:ident, ε } { h, ε, ; } { f } { g } INPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | FIRST: { $d:ident, h, ;, f } ``` Thus: * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $( f ;)+ g`) = { `$d:ident`, `h`, `;`, `f` } Note however that: * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $($( f ;)+ g)*`) = { `$d:ident`, `h`, `;`, `f`, ε } Here are similar examples but now for LAST. * LAST(`$d:ident $e:expr`) = { `$e:expr` } * LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε } * LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` } * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` } * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` } ### FOLLOW(M) Finally, the definition for FOLLOW(M) is built up as follows. pat, expr, etc. represent simple nonterminals with the given fragment specifier. * FOLLOW(pat) = {`=>`, `,`, `=`, `|`, `if`, `in`}`. * FOLLOW(expr) = FOLLOW(stmt) = {`=>`, `,`, `;`}`. * FOLLOW(ty) = FOLLOW(path) = {`{`, `[`, `,`, `=>`, `:`, `=`, `>`, `>>`, `;`, `|`, `as`, `where`, block nonterminals}. * FOLLOW(vis) = {`,`l any keyword or identifier except a non-raw `priv`; any token that can begin a type; ident, ty, and path nonterminals}. * FOLLOW(t) = ANYTOKEN for any other simple token, including block, ident, tt, item, lifetime, literal and meta simple nonterminals, and all terminals. * FOLLOW(M), for any other M, is defined as the intersection, as t ranges over (LAST(M) \ {ε}), of FOLLOW(t). The tokens that can begin a type are, as of this writing, {`(`, `[`, `!`, `*`, `&`, `&&`, `?`, lifetimes, `>`, `>>`, `::`, any non-keyword identifier, `super`, `self`, `Self`, `extern`, `crate`, `$crate`, `_`, `for`, `impl`, `fn`, `unsafe`, `typeof`, `dyn`}, although this list may not be complete because people won't always remember to update the appendix when new ones are added. Examples of FOLLOW for complex M: * FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`) * FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`) * FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN ### Examples of valid and invalid matchers With the above specification in hand, we can present arguments for why particular matchers are legal and others are not. * `($ty:ty < foo ,)` : illegal, because FIRST(`< foo ,`) = { `<` } ⊈ FOLLOW(`ty`) * `($ty:ty , foo <)` : legal, because FIRST(`, foo <`) = { `,` } is ⊆ FOLLOW(`ty`). * `($pa:pat $pb:pat $ty:ty ,)` : illegal, because FIRST(`$pb:pat $ty:ty ,`) = { `$pb:pat` } ⊈ FOLLOW(`pat`), and also FIRST(`$ty:ty ,`) = { `$ty:ty` } ⊈ FOLLOW(`pat`). * `( $($a:tt $b:tt)* ; )` : legal, because FIRST(`$b:tt`) = { `$b:tt` } is ⊆ FOLLOW(`tt`) = ANYTOKEN, as is FIRST(`;`) = { `;` }. * `( $($t:tt),* , $(t:tt),* )` : legal, (though any attempt to actually use this macro will signal a local ambiguity error during expansion). * `($ty:ty $(; not sep)* -)` : illegal, because FIRST(`$(; not sep)* -`) = { `;`, `-` } is not in FOLLOW(`ty`). * `($($ty:ty)-+)` : illegal, because separator `-` is not in FOLLOW(`ty`). * `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT). rust Macros By Example Macros By Example ================= > **Syntax** > *MacroRulesDefinition* : > `macro_rules` `!` [IDENTIFIER](identifiers) *MacroRulesDef* > > *MacroRulesDef* : > `(` *MacroRules* `)` `;` > | `[` *MacroRules* `]` `;` > | `{` *MacroRules* `}` > > *MacroRules* : > *MacroRule* ( `;` *MacroRule* )\* `;`? > > *MacroRule* : > *MacroMatcher* `=>` *MacroTranscriber* > > *MacroMatcher* : > `(` *MacroMatch*\* `)` > | `[` *MacroMatch*\* `]` > | `{` *MacroMatch*\* `}` > > *MacroMatch* : > [*Token*](tokens)*except `$` and [delimiters](tokens#delimiters)* > | *MacroMatcher* > | `$` ( [IDENTIFIER\_OR\_KEYWORD](identifiers) *except `crate`* | [RAW\_IDENTIFIER](identifiers) | `_` ) `:` *MacroFragSpec* > | `$` `(` *MacroMatch*+ `)` *MacroRepSep*? *MacroRepOp* > > *MacroFragSpec* : > `block` | `expr` | `ident` | `item` | `lifetime` | `literal` > | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis` > > *MacroRepSep* : > [*Token*](tokens)*except [delimiters](tokens#delimiters) and MacroRepOp* > > *MacroRepOp* : > `*` | `+` | `?` > > *MacroTranscriber* : > [*DelimTokenTree*](macros) > > `macro_rules` allows users to define syntax extension in a declarative way. We call such extensions "macros by example" or simply "macros". Each macro by example has a name, and one or more *rules*. Each rule has two parts: a *matcher*, describing the syntax that it matches, and a *transcriber*, describing the syntax that will replace a successfully matched invocation. Both the matcher and the transcriber must be surrounded by delimiters. Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns. Transcribing ------------ When a macro is invoked, the macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match; if this results in an error, then future matches are not tried. When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to parse the macro invocation one token at a time, then it is an error. In the following example, the compiler does not look ahead past the identifier to see if the following token is a `)`, even though that would allow it to parse the invocation unambiguously: ``` #![allow(unused)] fn main() { macro_rules! ambiguity { ($($i:ident)* $j:ident) => { }; } ambiguity!(error); // Error: local ambiguity } ``` In both the matcher and the transcriber, the `$` token is used to invoke special behaviours from the macro engine (described below in [Metavariables](#metavariables) and [Repetitions](#repetitions)). Tokens that aren't part of such an invocation are matched and transcribed literally, with one exception. The exception is that the outer delimiters for the matcher will match any pair of delimiters. Thus, for instance, the matcher `(())` will match `{()}` but not `{{}}`. The character `$` cannot be matched or transcribed literally. When forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type. The second macro can't use literal tokens to match the fragments in the matcher, only a fragment specifier of the same type. The `ident`, `lifetime`, and `tt` fragment types are an exception, and *can* be matched by literal tokens. The following illustrates this restriction: ``` #![allow(unused)] fn main() { macro_rules! foo { ($l:expr) => { bar!($l); } // ERROR: ^^ no rules expected this token in macro call } macro_rules! bar { (3) => {} } foo!(3); } ``` The following illustrates how tokens can be directly matched after matching a `tt` fragment: ``` #![allow(unused)] fn main() { // compiles OK macro_rules! foo { ($l:tt) => { bar!($l); } } macro_rules! bar { (3) => {} } foo!(3); } ``` Metavariables ------------- In the matcher, `$` *name* `:` *fragment-specifier* matches a Rust syntax fragment of the kind specified and binds it to the metavariable `$`*name*. Valid fragment specifiers are: * `item`: an [*Item*](items) * `block`: a [*BlockExpression*](expressions/block-expr) * `stmt`: a [*Statement*](statements) without the trailing semicolon (except for item statements that require semicolons) * `pat_param`: a [*PatternNoTopAlt*](patterns) * `pat`: at least any [*PatternNoTopAlt*](patterns), and possibly more depending on edition * `expr`: an [*Expression*](expressions) * `ty`: a [*Type*](types#type-expressions) * `ident`: an [IDENTIFIER\_OR\_KEYWORD](identifiers) or [RAW\_IDENTIFIER](identifiers) * `path`: a [*TypePath*](paths#paths-in-types) style path * `tt`: a [*TokenTree*](macros#macro-invocation) (a single [token](tokens) or tokens in matching delimiters `()`, `[]`, or `{}`) * `meta`: an [*Attr*](attributes), the contents of an attribute * `lifetime`: a [LIFETIME\_TOKEN](tokens#lifetimes-and-loop-labels) * `vis`: a possibly empty [*Visibility*](visibility-and-privacy) qualifier * `literal`: matches `-`?[*LiteralExpression*](expressions/literal-expr) In the transcriber, metavariables are referred to simply by `$`*name*, since the fragment kind is specified in the matcher. Metavariables are replaced with the syntax element that matched them. The keyword metavariable `$crate` can be used to refer to the current crate; see [Hygiene](#hygiene) below. Metavariables can be transcribed more than once or not at all. For reasons of backwards compatibility, though `_` [is also an expression](expressions/underscore-expr), a standalone underscore is not matched by the `expr` fragment specifier. However, `_` is matched by the `expr` fragment specifier when it appears as a subexpression. > **Edition Differences**: Starting with the 2021 edition, `pat` fragment-specifiers match top-level or-patterns (that is, they accept [*Pattern*](patterns)). > > Before the 2021 edition, they match exactly the same fragments as `pat_param` (that is, they accept [*PatternNoTopAlt*](patterns)). > > The relevant edition is the one in effect for the `macro_rules!` definition. > > Repetitions ----------- In both the matcher and transcriber, repetitions are indicated by placing the tokens to be repeated inside `$(`…`)`, followed by a repetition operator, optionally with a separator token between. The separator token can be any token other than a delimiter or one of the repetition operators, but `;` and `,` are the most common. For instance, `$( $i:ident ),*` represents any number of identifiers separated by commas. Nested repetitions are permitted. The repetition operators are: * `*` — indicates any number of repetitions. * `+` — indicates any number but at least one. * `?` — indicates an optional fragment with zero or one occurrences. Since `?` represents at most one occurrence, it cannot be used with a separator. The repeated fragment both matches and transcribes to the specified number of the fragment, separated by the separator token. Metavariables are matched to every repetition of their corresponding fragment. For instance, the `$( $i:ident ),*` example above matches `$i` to all of the identifiers in the list. During transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly: 1. A metavariable must appear in exactly the same number, kind, and nesting order of repetitions in the transcriber as it did in the matcher. So for the matcher `$( $i:ident ),*`, the transcribers `=> { $i }`, `=> { $( $( $i)* )* }`, and `=> { $( $i )+ }` are all illegal, but `=> { $( $i );* }` is correct and replaces a comma-separated list of identifiers with a semicolon-separated list. 2. Each repetition in the transcriber must contain at least one metavariable to decide how many times to expand it. If multiple metavariables appear in the same repetition, they must be bound to the same number of fragments. For instance, `( $( $i:ident ),* ; $( $j:ident ),* ) => (( $( ($i,$j) ),* ))` must bind the same number of `$i` fragments as `$j` fragments. This means that invoking the macro with `(a, b, c; d, e, f)` is legal and expands to `((a,d), (b,e), (c,f))`, but `(a, b, c; d, e)` is illegal because it does not have the same number. This requirement applies to every layer of nested repetitions. Scoping, Exporting, and Importing --------------------------------- For historical reasons, the scoping of macros by example does not work entirely like items. Macros have two forms of scope: textual scope, and path-based scope. Textual scope is based on the order that things appear in source files, or even across multiple files, and is the default scoping. It is explained further below. Path-based scope works exactly the same way that item scoping does. The scoping, exporting, and importing of macros is controlled largely by attributes. When a macro is invoked by an unqualified identifier (not part of a multi-part path), it is first looked up in textual scoping. If this does not yield any results, then it is looked up in path-based scoping. If the macro's name is qualified with a path, then it is only looked up in path-based scoping. ``` use lazy_static::lazy_static; // Path-based import. macro_rules! lazy_static { // Textual definition. (lazy) => {}; } lazy_static!{lazy} // Textual lookup finds our macro first. self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one. ``` ### Textual Scope Textual scope is based largely on the order that things appear in source files, and works similarly to the scope of local variables declared with `let` except it also applies at the module level. When `macro_rules!` is used to define a macro, the macro enters the scope after the definition (note that it can still be used recursively, since names are looked up from the invocation site), up until its surrounding scope, typically a module, is closed. This can enter child modules and even span across multiple files: ``` //// src/lib.rs mod has_macro { // m!{} // Error: m is not in scope. macro_rules! m { () => {}; } m!{} // OK: appears after declaration of m. mod uses_macro; } // m!{} // Error: m is not in scope. //// src/has_macro/uses_macro.rs m!{} // OK: appears after declaration of m in src/lib.rs ``` It is not an error to define a macro multiple times; the most recent declaration will shadow the previous one unless it has gone out of scope. ``` #![allow(unused)] fn main() { macro_rules! m { (1) => {}; } m!(1); mod inner { m!(1); macro_rules! m { (2) => {}; } // m!(1); // Error: no rule matches '1' m!(2); macro_rules! m { (3) => {}; } m!(3); } m!(1); } ``` Macros can be declared and used locally inside functions as well, and work similarly: ``` #![allow(unused)] fn main() { fn foo() { // m!(); // Error: m is not in scope. macro_rules! m { () => {}; } m!(); } // m!(); // Error: m is not in scope. } ``` ### The `macro_use` attribute The *`macro_use` attribute* has two purposes. First, it can be used to make a module's macro scope not end when the module is closed, by applying it to a module: ``` #![allow(unused)] fn main() { #[macro_use] mod inner { macro_rules! m { () => {}; } } m!(); } ``` Second, it can be used to import macros from another crate, by attaching it to an `extern crate` declaration appearing in the crate's root module. Macros imported this way are imported into the [`macro_use` prelude](names/preludes#macro_use-prelude), not textually, which means that they can be shadowed by any other name. While macros imported by `#[macro_use]` can be used before the import statement, in case of a conflict, the last macro imported wins. Optionally, a list of macros to import can be specified using the [*MetaListIdents*](attributes#meta-item-attribute-syntax) syntax; this is not supported when `#[macro_use]` is applied to a module. ``` #[macro_use(lazy_static)] // Or #[macro_use] to import all macros. extern crate lazy_static; lazy_static!{} // self::lazy_static!{} // Error: lazy_static is not defined in `self` ``` Macros to be imported with `#[macro_use]` must be exported with `#[macro_export]`, which is described below. ### Path-Based Scope By default, a macro has no path-based scope. However, if it has the `#[macro_export]` attribute, then it is declared in the crate root scope and can be referred to normally as such: ``` #![allow(unused)] fn main() { self::m!(); m!(); // OK: Path-based lookup finds m in the current module. mod inner { super::m!(); crate::m!(); } mod mac { #[macro_export] macro_rules! m { () => {}; } } } ``` Macros labeled with `#[macro_export]` are always `pub` and can be referred to by other crates, either by path or by `#[macro_use]` as described above. Hygiene ------- By default, all identifiers referred to in a macro are expanded as-is, and are looked up at the macro's invocation site. This can lead to issues if a macro refers to an item or macro which isn't in scope at the invocation site. To alleviate this, the `$crate` metavariable can be used at the start of a path to force lookup to occur inside the crate defining the macro. ``` //// Definitions in the `helper_macro` crate. #[macro_export] macro_rules! helped { // () => { helper!() } // This might lead to an error due to 'helper' not being in scope. () => { $crate::helper!() } } #[macro_export] macro_rules! helper { () => { () } } //// Usage in another crate. // Note that `helper_macro::helper` is not imported! use helper_macro::helped; fn unit() { helped!(); } ``` Note that, because `$crate` refers to the current crate, it must be used with a fully qualified module path when referring to non-macro items: ``` #![allow(unused)] fn main() { pub mod inner { #[macro_export] macro_rules! call_foo { () => { $crate::inner::foo() }; } pub fn foo() {} } } ``` Additionally, even though `$crate` allows a macro to refer to items within its own crate when expanding, its use has no effect on visibility. An item or macro referred to must still be visible from the invocation site. In the following example, any attempt to invoke `call_foo!()` from outside its crate will fail because `foo()` is not public. ``` #![allow(unused)] fn main() { #[macro_export] macro_rules! call_foo { () => { $crate::foo() }; } fn foo() {} } ``` > **Version & Edition Differences**: Prior to Rust 1.30, `$crate` and `local_inner_macros` (below) were unsupported. They were added alongside path-based imports of macros (described above), to ensure that helper macros did not need to be manually imported by users of a macro-exporting crate. Crates written for earlier versions of Rust that use helper macros need to be modified to use `$crate` or `local_inner_macros` to work well with path-based imports. > > When a macro is exported, the `#[macro_export]` attribute can have the `local_inner_macros` keyword added to automatically prefix all contained macro invocations with `$crate::`. This is intended primarily as a tool to migrate code written before `$crate` was added to the language to work with Rust 2018's path-based imports of macros. Its use is discouraged in new code. ``` #![allow(unused)] fn main() { #[macro_export(local_inner_macros)] macro_rules! helped { () => { helper!() } // Automatically converted to $crate::helper!(). } #[macro_export] macro_rules! helper { () => { () } } } ``` Follow-set Ambiguity Restrictions --------------------------------- The parser used by the macro system is reasonably powerful, but it is limited in order to prevent ambiguity in current or future versions of the language. In particular, in addition to the rule about ambiguous expansions, a nonterminal matched by a metavariable must be followed by a token which has been decided can be safely used after that kind of match. As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted in Rust today, since `[,]` cannot be part of a legal expression and therefore the parse would always be unambiguous. However, because `[` can start trailing expressions, `[` is not a character which can safely be ruled out as coming after an expression. If `[,]` were accepted in a later version of Rust, this matcher would become ambiguous or would misparse, breaking working code. Matchers like `$i:expr,` or `$i:expr;` would be legal, however, because `,` and `;` are legal expression separators. The specific rules are: * `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`. * `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`. * `pat` may only be followed by one of: `=>`, `,`, `=`, `if`, or `in`. * `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` fragment specifier. * `vis` may only be followed by one of: `,`, an identifier other than a non-raw `priv`, any token that can begin a type, or a metavariable with a `ident`, `ty`, or `path` fragment specifier. * All other fragment specifiers have no restrictions. > **Edition Differences**: Before the 2021 edition, `pat` may also be followed by `|`. > > When repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means: * If the repetition includes a separator, that separator must be able to follow the contents of the repetition. * If the repetition can repeat multiple times (`*` or `+`), then the contents must be able to follow themselves. * The contents of the repetition must be able to follow whatever comes before, and whatever comes after must be able to follow the contents of the repetition. * If the repetition can match zero times (`*` or `?`), then whatever comes after must be able to follow whatever comes before. For more detail, see the [formal specification](macro-ambiguity).
programming_docs
rust Inline assembly Inline assembly =============== Support for inline assembly is provided via the [`asm!`](https://doc.rust-lang.org/core/arch/macro.asm.html) and [`global_asm!`](https://doc.rust-lang.org/core/arch/macro.global_asm.html) macros. It can be used to embed handwritten assembly in the assembly output generated by the compiler. Support for inline assembly is stable on the following architectures: * x86 and x86-64 * ARM * AArch64 * RISC-V The compiler will emit an error if `asm!` is used on an unsupported target. Example ------- ``` #![allow(unused)] fn main() { use std::arch::asm; // Multiply x by 6 using shifts and adds let mut x: u64 = 4; unsafe { asm!( "mov {tmp}, {x}", "shl {tmp}, 1", "shl {x}, 2", "add {x}, {tmp}", x = inout(reg) x, tmp = out(reg) _, ); } assert_eq!(x, 4 * 6); } ``` Syntax ------ The following ABNF specifies the general syntax: ``` format_string := STRING_LITERAL / RAW_STRING_LITERAL dir_spec := "in" / "out" / "lateout" / "inout" / "inlateout" reg_spec := <register class> / "\"" <explicit register> "\"" operand_expr := expr / "_" / expr "=>" expr / expr "=>" "_" reg_operand := dir_spec "(" reg_spec ")" operand_expr operand := reg_operand clobber_abi := "clobber_abi(" <abi> *("," <abi>) [","] ")" option := "pure" / "nomem" / "readonly" / "preserves_flags" / "noreturn" / "nostack" / "att_syntax" / "raw" options := "options(" option *("," option) [","] ")" asm := "asm!(" format_string *("," format_string) *("," [ident "="] operand) *("," clobber_abi) *("," options) [","] ")" global_asm := "global_asm!(" format_string *("," format_string) *("," [ident "="] operand) *("," options) [","] ")" ``` Scope ----- Inline assembly can be used in one of two ways. With the `asm!` macro, the assembly code is emitted in a function scope and integrated into the compiler-generated assembly code of a function. This assembly code must obey [strict rules](#rules-for-inline-assembly) to avoid undefined behavior. Note that in some cases the compiler may choose to emit the assembly code as a separate function and generate a call to it. With the `global_asm!` macro, the assembly code is emitted in a global scope, outside a function. This can be used to hand-write entire functions using assembly code, and generally provides much more freedom to use arbitrary registers and assembler directives. Template string arguments ------------------------- The assembler template uses the same syntax as [format strings](../std/fmt/index#syntax) (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795](https://github.com/rust-lang/rfcs/pull/2795)) are not supported. An `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments. As with format strings, named arguments must appear after positional arguments. Explicit [register operands](#register-operands) must appear at the end of the operand list, after named arguments if any. Explicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated. The exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler. Currently, all supported targets follow the assembly code syntax used by LLVM's internal assembler which usually corresponds to that of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior. Further constraints on the directives used by inline assembly are indicated by [Directives Support](#directives-support). Operand type ------------ Several types of operands are supported: * `in(<reg>) <expr>` + `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string. + The allocated register will contain the value of `<expr>` at the start of the asm code. + The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register). * `out(<reg>) <expr>` + `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string. + The allocated register will contain an undefined value at the start of the asm code. + `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the asm code. + An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber). * `lateout(<reg>) <expr>` + Identical to `out` except that the register allocator can reuse a register allocated to an `in`. + You should only write to the register after all inputs are read, otherwise you may clobber an input. * `inout(<reg>) <expr>` + `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string. + The allocated register will contain the value of `<expr>` at the start of the asm code. + `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register are written at the end of the asm code. * `inout(<reg>) <in expr> => <out expr>` + Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`. + `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the asm code. + An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber). + `<in expr>` and `<out expr>` may have different types. * `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>` + Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`). + You should only write to the register after all inputs are read, otherwise you may clobber an input. Operand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output. Since `global_asm!` exists outside a function, it cannot use input/output operands. Register operands ----------------- Input and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `"eax"`) while register classes are specified as identifiers (e.g. `reg`). Note that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands. Only the following types are allowed as operands for inline assembly: * Integers (signed and unsigned) * Floating-point numbers * Pointers (thin only) * Function pointers * SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM). Here is the list of currently supported register classes: | Architecture | Register class | Registers | LLVM constraint code | | --- | --- | --- | --- | | x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `bp`, `r[8-15]` (x86-64 only) | `r` | | x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` | | x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` | | x86-64 | `reg_byte`\* | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `bpl`, `r[8-15]b` | `q` | | x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` | | x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` | | x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` | | x86 | `kreg` | `k[1-7]` | `Yk` | | x86 | `kreg0` | `k0` | Only clobbers | | x86 | `x87_reg` | `st([0-7])` | Only clobbers | | x86 | `mmx_reg` | `mm[0-7]` | Only clobbers | | x86-64 | `tmm_reg` | `tmm[0-7]` | Only clobbers | | AArch64 | `reg` | `x[0-30]` | `r` | | AArch64 | `vreg` | `v[0-31]` | `w` | | AArch64 | `vreg_low16` | `v[0-15]` | `x` | | AArch64 | `preg` | `p[0-15]`, `ffr` | Only clobbers | | ARM (ARM/Thumb2) | `reg` | `r[0-12]`, `r14` | `r` | | ARM (Thumb1) | `reg` | `r[0-7]` | `r` | | ARM | `sreg` | `s[0-31]` | `t` | | ARM | `sreg_low16` | `s[0-15]` | `x` | | ARM | `dreg` | `d[0-31]` | `w` | | ARM | `dreg_low16` | `d[0-15]` | `t` | | ARM | `dreg_low8` | `d[0-8]` | `x` | | ARM | `qreg` | `q[0-15]` | `w` | | ARM | `qreg_low8` | `q[0-7]` | `t` | | ARM | `qreg_low4` | `q[0-3]` | `x` | | RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` | | RISC-V | `freg` | `f[0-31]` | `f` | | RISC-V | `vreg` | `v[0-31]` | Only clobbers | > **Notes**: > > * On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register. > * On x86-64 the high byte registers (e.g. `ah`) are not available in the `reg_byte` register class. > * Some register classes are marked as "Only clobbers" which means that registers in these classes cannot be used for inputs or outputs, only clobbers of the form `out(<explicit register>) _` or `lateout(<explicit register>) _`. > > Each register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled. | Architecture | Register class | Target feature | Allowed types | | --- | --- | --- | --- | | x86-32 | `reg` | None | `i16`, `i32`, `f32` | | x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` | | x86 | `reg_byte` | None | `i8` | | x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` | | x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` | | x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` | | x86 | `kreg` | `avx512f` | `i8`, `i16` | | x86 | `kreg` | `avx512bw` | `i32`, `i64` | | x86 | `mmx_reg` | N/A | Only clobbers | | x86 | `x87_reg` | N/A | Only clobbers | | x86 | `tmm_reg` | N/A | Only clobbers | | AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` | | AArch64 | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` | | AArch64 | `preg` | N/A | Only clobbers | | ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` | | ARM | `sreg` | `vfp2` | `i32`, `f32` | | ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` | | ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` | | RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` | | RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` | | RISC-V | `freg` | `f` | `f32` | | RISC-V | `freg` | `d` | `f64` | | RISC-V | `vreg` | N/A | Only clobbers | > **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target). > > If a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture. When separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types. Register names -------------- Some registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases: | Architecture | Base register | Aliases | | --- | --- | --- | | x86 | `ax` | `eax`, `rax` | | x86 | `bx` | `ebx`, `rbx` | | x86 | `cx` | `ecx`, `rcx` | | x86 | `dx` | `edx`, `rdx` | | x86 | `si` | `esi`, `rsi` | | x86 | `di` | `edi`, `rdi` | | x86 | `bp` | `bpl`, `ebp`, `rbp` | | x86 | `sp` | `spl`, `esp`, `rsp` | | x86 | `ip` | `eip`, `rip` | | x86 | `st(0)` | `st` | | x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` | | x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` | | AArch64 | `x[0-30]` | `w[0-30]` | | AArch64 | `x29` | `fp` | | AArch64 | `x30` | `lr` | | AArch64 | `sp` | `wsp` | | AArch64 | `xzr` | `wzr` | | AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` | | ARM | `r[0-3]` | `a[1-4]` | | ARM | `r[4-9]` | `v[1-6]` | | ARM | `r9` | `rfp` | | ARM | `r10` | `sl` | | ARM | `r11` | `fp` | | ARM | `r12` | `ip` | | ARM | `r13` | `sp` | | ARM | `r14` | `lr` | | ARM | `r15` | `pc` | | RISC-V | `x0` | `zero` | | RISC-V | `x1` | `ra` | | RISC-V | `x2` | `sp` | | RISC-V | `x3` | `gp` | | RISC-V | `x4` | `tp` | | RISC-V | `x[5-7]` | `t[0-2]` | | RISC-V | `x8` | `fp`, `s0` | | RISC-V | `x9` | `s1` | | RISC-V | `x[10-17]` | `a[0-7]` | | RISC-V | `x[18-27]` | `s[2-11]` | | RISC-V | `x[28-31]` | `t[3-6]` | | RISC-V | `f[0-7]` | `ft[0-7]` | | RISC-V | `f[8-9]` | `fs[0-1]` | | RISC-V | `f[10-17]` | `fa[0-7]` | | RISC-V | `f[18-27]` | `fs[2-11]` | | RISC-V | `f[28-31]` | `ft[8-11]` | Some registers cannot be used for input or output operands: | Architecture | Unsupported register | Reason | | --- | --- | --- | | All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. | | All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V) | The frame pointer cannot be used as an input or output. | | ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. | | All | `si` (x86-32), `bx` (x86-64), `r6` (ARM), `x19` (AArch64), `x9` (RISC-V) | This is used internally by LLVM as a "base pointer" for functions with complex stack frames. | | x86 | `ip` | This is the program counter, not a real register. | | AArch64 | `xzr` | This is a constant zero register which can't be modified. | | AArch64 | `x18` | This is an OS-reserved register on some AArch64 targets. | | ARM | `pc` | This is the program counter, not a real register. | | ARM | `r9` | This is an OS-reserved register on some ARM targets. | | RISC-V | `x0` | This is a constant zero register which can't be modified. | | RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. | The frame pointer and base pointer registers are reserved for internal use by LLVM. While `asm!` statements cannot explicitly specify the use of reserved registers, in some cases LLVM will allocate one of these reserved registers for `reg` operands. Assembly code making use of reserved registers should be careful since `reg` operands may use the same registers. Template modifiers ------------------ The placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder. The supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers](http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers), but do not use the same letter codes. | Architecture | Register class | Modifier | Example output | LLVM modifier | | --- | --- | --- | --- | --- | | x86-32 | `reg` | None | `eax` | `k` | | x86-64 | `reg` | None | `rax` | `q` | | x86-32 | `reg_abcd` | `l` | `al` | `b` | | x86-64 | `reg` | `l` | `al` | `b` | | x86 | `reg_abcd` | `h` | `ah` | `h` | | x86 | `reg` | `x` | `ax` | `w` | | x86 | `reg` | `e` | `eax` | `k` | | x86-64 | `reg` | `r` | `rax` | `q` | | x86 | `reg_byte` | None | `al` / `ah` | None | | x86 | `xmm_reg` | None | `xmm0` | `x` | | x86 | `ymm_reg` | None | `ymm0` | `t` | | x86 | `zmm_reg` | None | `zmm0` | `g` | | x86 | `*mm_reg` | `x` | `xmm0` | `x` | | x86 | `*mm_reg` | `y` | `ymm0` | `t` | | x86 | `*mm_reg` | `z` | `zmm0` | `g` | | x86 | `kreg` | None | `k1` | None | | AArch64 | `reg` | None | `x0` | `x` | | AArch64 | `reg` | `w` | `w0` | `w` | | AArch64 | `reg` | `x` | `x0` | `x` | | AArch64 | `vreg` | None | `v0` | None | | AArch64 | `vreg` | `v` | `v0` | None | | AArch64 | `vreg` | `b` | `b0` | `b` | | AArch64 | `vreg` | `h` | `h0` | `h` | | AArch64 | `vreg` | `s` | `s0` | `s` | | AArch64 | `vreg` | `d` | `d0` | `d` | | AArch64 | `vreg` | `q` | `q0` | `q` | | ARM | `reg` | None | `r0` | None | | ARM | `sreg` | None | `s0` | None | | ARM | `dreg` | None | `d0` | `P` | | ARM | `qreg` | None | `q0` | `q` | | ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` | | RISC-V | `reg` | None | `x1` | None | | RISC-V | `freg` | None | `f0` | None | > **Notes**: > > * on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register. > * on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size. > * on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change. > > As stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand. ABI clobbers ------------ The `clobber_abi` keyword can be used to apply a default set of clobbers to an `asm!` block. This will automatically insert the necessary clobber constraints as needed for calling a function with a particular calling convention: if the calling convention does not fully preserve the value of a register across a call then `lateout("...") _` is implicitly added to the operands list (where the `...` is replaced by the register's name). `clobber_abi` may be specified any number of times. It will insert a clobber for all unique registers in the union of all specified calling conventions. Generic register class outputs are disallowed by the compiler when `clobber_abi` is used: all outputs must specify an explicit register. Explicit register outputs have precedence over the implicit clobbers inserted by `clobber_abi`: a clobber will only be inserted for a register if that register is not used as an output. The following ABIs can be used with `clobber_abi`: | Architecture | ABI name | Clobbered registers | | --- | --- | --- | | x86-32 | `"C"`, `"system"`, `"efiapi"`, `"cdecl"`, `"stdcall"`, `"fastcall"` | `ax`, `cx`, `dx`, `xmm[0-7]`, `mm[0-7]`, `k[0-7]`, `st([0-7])` | | x86-64 | `"C"`, `"system"` (on Windows), `"efiapi"`, `"win64"` | `ax`, `cx`, `dx`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]` | | x86-64 | `"C"`, `"system"` (on non-Windows), `"sysv64"` | `ax`, `cx`, `dx`, `si`, `di`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]` | | AArch64 | `"C"`, `"system"`, `"efiapi"` | `x[0-17]`, `x18`\*, `x30`, `v[0-31]`, `p[0-15]`, `ffr` | | ARM | `"C"`, `"system"`, `"efiapi"`, `"aapcs"` | `r[0-3]`, `r12`, `r14`, `s[0-15]`, `d[0-7]`, `d[16-31]` | | RISC-V | `"C"`, `"system"`, `"efiapi"` | `x1`, `x[5-7]`, `x[10-17]`, `x[28-31]`, `f[0-7]`, `f[10-17]`, `f[28-31]`, `v[0-31]` | > Notes: > > * On AArch64 `x18` only included in the clobber list if it is not considered as a reserved register on the target. > > The list of clobbered registers for each ABI is updated in rustc as architectures gain new registers: this ensures that `asm!` clobbers will continue to be correct when LLVM starts using these new registers in its generated code. Options ------- Flags are used to further influence the behavior of the inline assembly block. Currently the following options are defined: * `pure`: The `asm!` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm!` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used. * `nomem`: The `asm!` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm!` block since it knows that they are not read or written to by the `asm!`. * `readonly`: The `asm!` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm!` block since it knows that they are not written to by the `asm!`. * `preserves_flags`: The `asm!` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm!` block. * `noreturn`: The `asm!` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked. * `nostack`: The `asm!` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call. * `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`. * `raw`: This causes the template string to be parsed as a raw assembly string, with no special handling for `{` and `}`. This is primarily useful when including raw assembly code from an external file using `include_str!`. The compiler performs some additional checks on options: * The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both. * The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted. * It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`). * It is a compile-time error to specify `noreturn` on an asm block with outputs. `global_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful for global-scope inline assembly Rules for inline assembly ------------------------- To avoid undefined behavior, these rules must be followed when using function-scope inline assembly (`asm!`): * Any registers not specified as inputs will contain an undefined value on entry to the asm block. + An "undefined value" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code). * Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined. + This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules. + Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation. * Behavior is undefined if execution unwinds out of an asm block. + This also applies if the assembly code calls a function which then unwinds. * The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function. + Refer to the unsafe code guidelines for the exact rules. + If the `readonly` option is set, then only memory reads are allowed. + If the `nomem` option is set then no reads or writes to memory are allowed. + These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block. * The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed. + This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves. + Runtime code patching is allowed, via target-specific mechanisms. * Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer. + On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call. + You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page). + You should adjust the stack pointer when allocating stack memory as required by the target ABI. + The stack pointer must be restored to its original value before leaving the asm block. * If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block. * If the `pure` option is set then behavior is undefined if the `asm!` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm!` code with the same inputs result in different outputs. + When used with the `nomem` option, "inputs" are just the direct inputs of the `asm!`. + When used with the `readonly` option, "inputs" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read. * These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set: + x86 - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF). - Floating-point status word (all). - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE). + ARM - Condition flags in `CPSR` (N, Z, C, V) - Saturation flag in `CPSR` (Q) - Greater than or equal flags in `CPSR` (GE). - Condition flags in `FPSCR` (N, Z, C, V) - Saturation flag in `FPSCR` (QC) - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC). + AArch64 - Condition flags (`NZCV` register). - Floating-point status (`FPSR` register). + RISC-V - Floating-point exception flags in `fcsr` (`fflags`). - Vector extension state (`vtype`, `vl`, `vcsr`). * On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit. + Behavior is undefined if the direction flag is set on exiting an asm block. * On x86, the x87 floating-point register stack must remain unchanged unless all of the `st([0-7])` registers have been marked as clobbered with `out("st(0)") _, out("st(1)") _, ...`. + If all x87 registers are clobbered then the x87 register stack is guaranteed to be empty upon entering an `asm` block. Assembly code must ensure that the x87 register stack is also empty when exiting the asm block. * The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block. + This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers. + When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*. - You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited (without first entering it again). - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds). - You cannot jump from an address in one `asm!` block to an address in another, even within the same function or block, without treating their contexts as potentially different and requiring context switching. You cannot assume that any particular value in those contexts (e.g. current stack pointer or temporary values below the stack pointer) will remain unchanged between the two `asm!` blocks. - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited. * You cannot assume that two `asm!` blocks adjacent in source code, even without any other code between them, will end up in successive addresses in the binary without any other instructions between them. * You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places. * On x86, inline assembly must not end with an instruction prefix (such as `LOCK`) that would apply to instructions generated by the compiler. + The compiler is currently unable to detect this due to the way inline assembly is compiled, but may catch and reject this in the future. > **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call. > > ### Directives Support Inline assembly supports a subset of the directives supported by both GNU AS and LLVM's internal assembler, given as follows. The result of using other directives is assembler-specific (and may cause an error, or may be accepted as-is). If inline assembly includes any "stateful" directive that modifies how subsequent assembly is processed, the block must undo the effects of any such directives before the inline assembly ends. The following directives are guaranteed to be supported by the assembler: * `.2byte` * `.4byte` * `.8byte` * `.align` * `.ascii` * `.asciz` * `.alt_entry` * `.balign` * `.balignl` * `.balignw` * `.balign` * `.balignl` * `.balignw` * `.bss` * `.byte` * `.comm` * `.data` * `.def` * `.double` * `.endef` * `.equ` * `.equiv` * `.eqv` * `.fill` * `.float` * `.globl` * `.global` * `.lcomm` * `.inst` * `.long` * `.octa` * `.option` * `.private_extern` * `.p2align` * `.pushsection` * `.popsection` * `.quad` * `.scl` * `.section` * `.set` * `.short` * `.size` * `.skip` * `.sleb128` * `.space` * `.string` * `.text` * `.type` * `.uleb128` * `.word` #### Target Specific Directive Support ##### Dwarf Unwinding The following directives are supported on ELF targets that support DWARF unwind info: * `.cfi_adjust_cfa_offset` * `.cfi_def_cfa` * `.cfi_def_cfa_offset` * `.cfi_def_cfa_register` * `.cfi_endproc` * `.cfi_escape` * `.cfi_lsda` * `.cfi_offset` * `.cfi_personality` * `.cfi_register` * `.cfi_rel_offset` * `.cfi_remember_state` * `.cfi_restore` * `.cfi_restore_state` * `.cfi_return_column` * `.cfi_same_value` * `.cfi_sections` * `.cfi_signal_frame` * `.cfi_startproc` * `.cfi_undefined` * `.cfi_window_save` ##### Structured Exception Handling On targets with structured exception Handling, the following additional directives are guaranteed to be supported: * `.seh_endproc` * `.seh_endprologue` * `.seh_proc` * `.seh_pushreg` * `.seh_savereg` * `.seh_setframe` * `.seh_stackalloc` ##### x86 (32-bit and 64-bit) On x86 targets, both 32-bit and 64-bit, the following additional directives are guaranteed to be supported: * `.nops` * `.code16` * `.code32` * `.code64` Use of `.code16`, `.code32`, and `.code64` directives are only supported if the state is reset to the default before exiting the assembly block. 32-bit x86 uses `.code32` by default, and x86\_64 uses `.code64` by default. ##### ARM (32-bit) On ARM, the following additional directives are guaranteed to be supported: * `.even` * `.fnstart` * `.fnend` * `.save` * `.movsp` * `.code` * `.thumb` * `.thumb_func`
programming_docs
rust Destructors Destructors =========== When an [initialized](glossary#initialized) [variable](variables) or [temporary](expressions#temporaries) goes out of [scope](#drop-scopes), its *destructor* is run, or it is *dropped*. [Assignment](expressions/operator-expr#assignment-expressions) also runs the destructor of its left-hand operand, if it's initialized. If a variable has been partially initialized, only its initialized fields are dropped. The destructor of a type `T` consists of: 1. If `T: Drop`, calling [`<T as std::ops::Drop>::drop`](../std/ops/trait.drop#tymethod.drop) 2. Recursively running the destructor of all of its fields. * The fields of a [struct](types/struct) are dropped in declaration order. * The fields of the active [enum variant](types/enum) are dropped in declaration order. * The fields of a [tuple](types/tuple) are dropped in order. * The elements of an [array](types/array) or owned [slice](types/slice) are dropped from the first element to the last. * The variables that a [closure](types/closure) captures by move are dropped in an unspecified order. * [Trait objects](types/trait-object) run the destructor of the underlying type. * Other types don't result in any further drops. If a destructor must be run manually, such as when implementing your own smart pointer, [`std::ptr::drop_in_place`](../std/ptr/fn.drop_in_place) can be used. Some examples: ``` #![allow(unused)] fn main() { struct PrintOnDrop(&'static str); impl Drop for PrintOnDrop { fn drop(&mut self) { println!("{}", self.0); } } let mut overwritten = PrintOnDrop("drops when overwritten"); overwritten = PrintOnDrop("drops when scope ends"); let tuple = (PrintOnDrop("Tuple first"), PrintOnDrop("Tuple second")); let moved; // No destructor run on assignment. moved = PrintOnDrop("Drops when moved"); // Drops now, but is then uninitialized. moved; // Uninitialized does not drop. let uninitialized: PrintOnDrop; // After a partial move, only the remaining fields are dropped. let mut partial_move = (PrintOnDrop("first"), PrintOnDrop("forgotten")); // Perform a partial move, leaving only `partial_move.0` initialized. core::mem::forget(partial_move.1); // When partial_move's scope ends, only the first field is dropped. } ``` Drop scopes ----------- Each variable or temporary is associated to a *drop scope*. When control flow leaves a drop scope all variables associated to that scope are dropped in reverse order of declaration (for variables) or creation (for temporaries). Drop scopes are determined after replacing [`for`](expressions/loop-expr#iterator-loops), [`if let`](expressions/if-expr#if-let-expressions), and [`while let`](expressions/loop-expr#predicate-pattern-loops) expressions with the equivalent expressions using [`match`](expressions/match-expr). Overloaded operators are not distinguished from built-in operators and [binding modes](patterns#binding-modes) are not considered. Given a function, or closure, there are drop scopes for: * The entire function * Each [statement](statements) * Each [expression](expressions) * Each block, including the function body + In the case of a [block expression](expressions/block-expr), the scope for the block and the expression are the same scope. * Each arm of a `match` expression Drop scopes are nested within one another as follows. When multiple scopes are left at once, such as when returning from a function, variables are dropped from the inside outwards. * The entire function scope is the outer most scope. * The function body block is contained within the scope of the entire function. * The parent of the expression in an expression statement is the scope of the statement. * The parent of the initializer of a [`let` statement](statements#let-statements) is the `let` statement's scope. * The parent of a statement scope is the scope of the block that contains the statement. * The parent of the expression for a `match` guard is the scope of the arm that the guard is for. * The parent of the expression after the `=>` in a `match` expression is the scope of the arm that it's in. * The parent of the arm scope is the scope of the `match` expression that it belongs to. * The parent of all other scopes is the scope of the immediately enclosing expression. ### Scopes of function parameters All function parameters are in the scope of the entire function body, so are dropped last when evaluating the function. Each actual function parameter is dropped after any bindings introduced in that parameter's pattern. ``` #![allow(unused)] fn main() { struct PrintOnDrop(&'static str); impl Drop for PrintOnDrop { fn drop(&mut self) { println!("drop({})", self.0); } } // Drops `y`, then the second parameter, then `x`, then the first parameter fn patterns_in_parameters( (x, _): (PrintOnDrop, PrintOnDrop), (_, y): (PrintOnDrop, PrintOnDrop), ) {} // drop order is 3 2 0 1 patterns_in_parameters( (PrintOnDrop("0"), PrintOnDrop("1")), (PrintOnDrop("2"), PrintOnDrop("3")), ); } ``` ### Scopes of local variables Local variables declared in a `let` statement are associated to the scope of the block that contains the `let` statement. Local variables declared in a `match` expression are associated to the arm scope of the `match` arm that they are declared in. ``` #![allow(unused)] fn main() { struct PrintOnDrop(&'static str); impl Drop for PrintOnDrop { fn drop(&mut self) { println!("drop({})", self.0); } } let declared_first = PrintOnDrop("Dropped last in outer scope"); { let declared_in_block = PrintOnDrop("Dropped in inner scope"); } let declared_last = PrintOnDrop("Dropped first in outer scope"); } ``` If multiple patterns are used in the same arm for a `match` expression, then an unspecified pattern will be used to determine the drop order. ### Temporary scopes The *temporary scope* of an expression is the scope that is used for the temporary variable that holds the result of that expression when used in a [place context](expressions#place-expressions-and-value-expressions), unless it is [promoted](destructors#constant-promotion). Apart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following: * The entire function body. * A statement. * The body of a [`if`](expressions/if-expr#if-expressions), [`while`](expressions/loop-expr#predicate-loops) or [`loop`](expressions/loop-expr#infinite-loops) expression. * The `else` block of an `if` expression. * The condition expression of an `if` or `while` expression, or a `match` guard. * The expression for a match arm. * The second operand of a [lazy boolean expression](expressions/operator-expr#lazy-boolean-operators). > **Notes**: > > Temporaries that are created in the final expression of a function body are dropped *after* any named variables bound in the function body, as there is no smaller enclosing temporary scope. > > The [scrutinee](glossary#scrutinee) of a `match` expression is not a temporary scope, so temporaries in the scrutinee can be dropped after the `match` expression. For example, the temporary for `1` in `match 1 { ref mut z => z };` lives until the end of the statement. > > Some examples: ``` #![allow(unused)] fn main() { struct PrintOnDrop(&'static str); impl Drop for PrintOnDrop { fn drop(&mut self) { println!("drop({})", self.0); } } let local_var = PrintOnDrop("local var"); // Dropped once the condition has been evaluated if PrintOnDrop("If condition").0 == "If condition" { // Dropped at the end of the block PrintOnDrop("If body").0 } else { unreachable!() }; // Dropped at the end of the statement (PrintOnDrop("first operand").0 == "" // Dropped at the ) || PrintOnDrop("second operand").0 == "") // Dropped at the end of the expression || PrintOnDrop("third operand").0 == ""; // Dropped at the end of the function, after local variables. // Changing this to a statement containing a return expression would make the // temporary be dropped before the local variables. Binding to a variable // which is then returned would also make the temporary be dropped first. match PrintOnDrop("Matched value in final expression") { // Dropped once the condition has been evaluated _ if PrintOnDrop("guard condition").0 == "" => (), _ => (), } } ``` ### Operands Temporaries are also created to hold the result of operands to an expression while the other operands are evaluated. The temporaries are associated to the scope of the expression with that operand. Since the temporaries are moved from once the expression is evaluated, dropping them has no effect unless one of the operands to an expression breaks out of the expression, returns, or panics. ``` #![allow(unused)] fn main() { struct PrintOnDrop(&'static str); impl Drop for PrintOnDrop { fn drop(&mut self) { println!("drop({})", self.0); } } loop { // Tuple expression doesn't finish evaluating so operands drop in reverse order ( PrintOnDrop("Outer tuple first"), PrintOnDrop("Outer tuple second"), ( PrintOnDrop("Inner tuple first"), PrintOnDrop("Inner tuple second"), break, ), PrintOnDrop("Never created"), ); } } ``` ### Constant promotion Promotion of a value expression to a `'static` slot occurs when the expression could be written in a constant and borrowed, and that borrow could be dereferenced where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain [interior mutability](interior-mutability) or <destructors> (these properties are determined based on the value where possible, e.g. `&None` always has the type `&'static Option<_>`, as it contains nothing disallowed). ### Temporary lifetime extension > **Note**: The exact rules for temporary lifetime extension are subject to change. This is describing the current behavior only. > > The temporary scopes for expressions in `let` statements are sometimes *extended* to the scope of the block containing the `let` statement. This is done when the usual temporary scope would be too small, based on certain syntactic rules. For example: ``` #![allow(unused)] fn main() { let x = &mut 0; // Usually a temporary would be dropped by now, but the temporary for `0` lives // to the end of the block. println!("{}", x); } ``` If a borrow, dereference, field, or tuple indexing expression has an extended temporary scope then so does its operand. If an indexing expression has an extended temporary scope then the indexed expression also has an extended temporary scope. #### Extending based on patterns An *extending pattern* is either * An [identifier pattern](patterns#identifier-patterns) that binds by reference or mutable reference. * A [struct](patterns#struct-patterns), [tuple](patterns#tuple-patterns), [tuple struct](patterns#tuple-struct-patterns), or [slice](patterns#slice-patterns) pattern where at least one of the direct subpatterns is a extending pattern. So `ref x`, `V(ref x)` and `[ref x, y]` are all extending patterns, but `x`, `&ref x` and `&(ref x,)` are not. If the pattern in a `let` statement is an extending pattern then the temporary scope of the initializer expression is extended. #### Extending based on expressions For a let statement with an initializer, an *extending expression* is an expression which is one of the following: * The initializer expression. * The operand of an extending [borrow expression](expressions/operator-expr#borrow-operators). * The operand(s) of an extending [array](expressions/array-expr#array-expressions), [cast](expressions/operator-expr#type-cast-expressions), [braced struct](expressions/struct-expr), or [tuple](expressions/tuple-expr#tuple-expressions) expression. * The final expression of any extending [block expression](expressions/block-expr). So the borrow expressions in `&mut 0`, `(&1, &mut 2)`, and `Some { 0: &mut 3 }` are all extending expressions. The borrows in `&0 + &1` and `Some(&mut 0)` are not: the latter is syntactically a function call expression. The operand of any extending borrow expression has its temporary scope extended. #### Examples Here are some examples where expressions have extended temporary scopes: ``` #![allow(unused)] fn main() { fn temp() {} trait Use { fn use_temp(&self) -> &Self { self } } impl Use for () {} // The temporary that stores the result of `temp()` lives in the same scope // as x in these cases. let x = &temp(); let x = &temp() as &dyn Send; let x = (&*&temp(),); let x = { [Some { 0: &temp(), }] }; let ref x = temp(); let ref x = *&temp(); x; } ``` Here are some examples where expressions don't have extended temporary scopes: ``` #![allow(unused)] fn main() { fn temp() {} trait Use { fn use_temp(&self) -> &Self { self } } impl Use for () {} // The temporary that stores the result of `temp()` only lives until the // end of the let statement in these cases. let x = Some(&temp()); // ERROR let x = (&temp()).use_temp(); // ERROR x; } ``` Not running destructors ----------------------- [`std::mem::forget`](../std/mem/fn.forget) can be used to prevent the destructor of a variable from being run, and [`std::mem::ManuallyDrop`](../std/mem/struct.manuallydrop) provides a wrapper to prevent a variable or field from being dropped automatically. > Note: Preventing a destructor from being run via [`std::mem::forget`](../std/mem/fn.forget) or other means is safe even if it has a type that isn't `'static`. Besides the places where destructors are guaranteed to run as defined by this document, types may *not* safely rely on a destructor being run for soundness. > > rust Expressions Expressions =========== > **Syntax** > *Expression* : > *ExpressionWithoutBlock* > | *ExpressionWithBlock* > > *ExpressionWithoutBlock* : > [*OuterAttribute*](attributes)\*[†](#expression-attributes) > ( > [*LiteralExpression*](expressions/literal-expr) > | [*PathExpression*](expressions/path-expr) > | [*OperatorExpression*](expressions/operator-expr) > | [*GroupedExpression*](expressions/grouped-expr) > | [*ArrayExpression*](expressions/array-expr) > | [*AwaitExpression*](expressions/await-expr) > | [*IndexExpression*](expressions/array-expr#array-and-slice-indexing-expressions) > | [*TupleExpression*](expressions/tuple-expr) > | [*TupleIndexingExpression*](expressions/tuple-expr#tuple-indexing-expressions) > | [*StructExpression*](expressions/struct-expr) > | [*CallExpression*](expressions/call-expr) > | [*MethodCallExpression*](expressions/method-call-expr) > | [*FieldExpression*](expressions/field-expr) > | [*ClosureExpression*](expressions/closure-expr) > | [*ContinueExpression*](expressions/loop-expr#continue-expressions) > | [*BreakExpression*](expressions/loop-expr#break-expressions) > | [*RangeExpression*](expressions/range-expr) > | [*ReturnExpression*](expressions/return-expr) > | [*UnderscoreExpression*](expressions/underscore-expr) > | [*MacroInvocation*](macros#macro-invocation) > ) > > *ExpressionWithBlock* : > [*OuterAttribute*](attributes)\*[†](#expression-attributes) > ( > [*BlockExpression*](expressions/block-expr) > | [*AsyncBlockExpression*](expressions/block-expr#async-blocks) > | [*UnsafeBlockExpression*](expressions/block-expr#unsafe-blocks) > | [*LoopExpression*](expressions/loop-expr) > | [*IfExpression*](expressions/if-expr#if-expressions) > | [*IfLetExpression*](expressions/if-expr#if-let-expressions) > | [*MatchExpression*](expressions/match-expr) > ) > > An expression may have two roles: it always produces a *value*, and it may have *effects* (otherwise known as "side effects"). An expression *evaluates to* a value, and has effects during *evaluation*. Many expressions contain sub-expressions, called the *operands* of the expression. The meaning of each kind of expression dictates several things: * Whether or not to evaluate the operands when evaluating the expression * The order in which to evaluate the operands * How to combine the operands' values to obtain the value of the expression In this way, the structure of expressions dictates the structure of execution. Blocks are just another kind of expression, so blocks, statements, expressions, and blocks again can recursively nest inside each other to an arbitrary depth. > **Note**: We give names to the operands of expressions so that we may discuss them, but these names are not stable and may be changed. > > Expression precedence --------------------- The precedence of Rust operators and expressions is ordered as follows, going from strong to weak. Binary Operators at the same precedence level are grouped in the order given by their associativity. | Operator/Expression | Associativity | | --- | --- | | Paths | | | Method calls | | | Field expressions | left to right | | Function calls, array indexing | | | `?` | | | Unary `-` `*` `!` `&` `&mut` | | | `as` | left to right | | `*` `/` `%` | left to right | | `+` `-` | left to right | | `<<` `>>` | left to right | | `&` | left to right | | `^` | left to right | | `|` | left to right | | `==` `!=` `<` `>` `<=` `>=` | Require parentheses | | `&&` | left to right | | `||` | left to right | | `..` `..=` | Require parentheses | | `=` `+=` `-=` `*=` `/=` `%=` `&=` `|=` `^=` `<<=` `>>=` | right to left | | `return` `break` closures | | Evaluation order of operands ---------------------------- The following list of expressions all evaluate their operands the same way, as described after the list. Other expressions either don't take operands or evaluate them conditionally as described on their respective pages. * Dereference expression * Error propagation expression * Negation expression * Arithmetic and logical binary operators * Comparison operators * Type cast expression * Grouped expression * Array expression * Await expression * Index expression * Tuple expression * Tuple index expression * Struct expression * Call expression * Method call expression * Field expression * Break expression * Range expression * Return expression The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code. > **Note**: Which subexpressions are the operands of an expression is determined by expression precedence as per the previous section. > > For example, the two `next` method calls will always be called in the same order: ``` #![allow(unused)] fn main() { // Using vec instead of array to avoid references // since there is no stable owned array iterator // at the time this example was written. let mut one_two = vec![1, 2].into_iter(); assert_eq!( (1, 2), (one_two.next().unwrap(), one_two.next().unwrap()) ); } ``` > **Note**: Since this is applied recursively, these expressions are also evaluated from innermost to outermost, ignoring siblings until there are no inner subexpressions. > > Place Expressions and Value Expressions --------------------------------------- Expressions are divided into two main categories: place expressions and value expressions; there is also a third, minor category of expressions called assignee expressions. Within each expression, operands may likewise occur in either place context or value context. The evaluation of an expression depends both on its own category and the context it occurs within. A *place expression* is an expression that represents a memory location. These expressions are [paths](expressions/path-expr) which refer to local variables, [static variables](items/static-items), [dereferences](expressions/operator-expr#the-dereference-operator) (`*expr`), [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) expressions (`expr[expr]`), [field](expressions/field-expr) references (`expr.f`) and parenthesized place expressions. All other expressions are value expressions. A *value expression* is an expression that represents an actual value. The following contexts are *place expression* contexts: * The left operand of a [compound assignment](expressions/operator-expr#compound-assignment-expressions) expression. * The operand of a unary [borrow](expressions/operator-expr#borrow-operators), [address-of](expressions/operator-expr#raw-address-of-operators) or [dereference](expressions/operator-expr#the-dereference-operator) operator. * The operand of a field expression. * The indexed operand of an array indexing expression. * The operand of any [implicit borrow](#implicit-borrows). * The initializer of a [let statement](statements#let-statements). * The [scrutinee](glossary#scrutinee) of an [`if let`](expressions/if-expr#if-let-expressions), [`match`](expressions/match-expr), or [`while let`](expressions/loop-expr#predicate-pattern-loops) expression. * The base of a [functional update](expressions/struct-expr#functional-update-syntax) struct expression. > Note: Historically, place expressions were called *lvalues* and value expressions were called *rvalues*. > > An *assignee expression* is an expression that appears in the left operand of an [assignment](expressions/operator-expr#assignment-expressions) expression. Explicitly, the assignee expressions are: * Place expressions. * [Underscores](expressions/underscore-expr). * [Tuples](expressions/tuple-expr) of assignee expressions. * [Slices](expressions/array-expr) of assingee expressions. * [Tuple structs](expressions/struct-expr) of assignee expressions. * [Structs](expressions/struct-expr) of assignee expressions (with optionally named fields). * [Unit structs](expressions/struct-expr). Arbitrary parenthesisation is permitted inside assignee expressions. ### Moved and copied types When a place expression is evaluated in a value expression context, or is bound by value in a pattern, it denotes the value held *in* that memory location. If the type of that value implements [`Copy`](special-types-and-traits#copy), then the value will be copied. In the remaining situations, if that type is [`Sized`](special-types-and-traits#sized), then it may be possible to move the value. Only the following place expressions may be moved out of: * [Variables](variables) which are not currently borrowed. * [Temporary values](#temporaries). * [Fields](expressions/field-expr) of a place expression which can be moved out of and don't implement [`Drop`](special-types-and-traits#drop). * The result of [dereferencing](expressions/operator-expr#the-dereference-operator) an expression with type [`Box<T>`](../std/boxed/struct.box) and that can also be moved out of. After moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized. In all other cases, trying to use a place expression in a value expression context is an error. ### Mutability For a place expression to be [assigned](expressions/operator-expr#assignment-expressions) to, mutably [borrowed](expressions/operator-expr#borrow-operators), [implicitly mutably borrowed](#implicit-borrows), or bound to a pattern containing `ref mut`, it must be *mutable*. We call these *mutable place expressions*. In contrast, other place expressions are called *immutable place expressions*. The following expressions can be mutable place expression contexts: * Mutable <variables> which are not currently borrowed. * [Mutable `static` items](items/static-items#mutable-statics). * [Temporary values](#temporaries). * [Fields](expressions/field-expr): this evaluates the subexpression in a mutable place expression context. * [Dereferences](expressions/operator-expr#the-dereference-operator) of a `*mut T` pointer. * Dereference of a variable, or field of a variable, with type `&mut T`. Note: This is an exception to the requirement of the next rule. * Dereferences of a type that implements `DerefMut`: this then requires that the value being dereferenced is evaluated in a mutable place expression context. * [Array indexing](expressions/array-expr#array-and-slice-indexing-expressions) of a type that implements `IndexMut`: this then evaluates the value being indexed, but not the index, in mutable place expression context. ### Temporaries When using a value expression in most place expression contexts, a temporary unnamed memory location is created and initialized to that value. The expression evaluates to that location instead, except if [promoted](destructors#constant-promotion) to a `static`. The [drop scope](destructors#drop-scopes) of the temporary is usually the end of the enclosing statement. ### Implicit Borrows Certain expressions will treat an expression as a place expression by implicitly borrowing it. For example, it is possible to compare two unsized [slices](types/slice) for equality directly, because the `==` operator implicitly borrows its operands: ``` #![allow(unused)] fn main() { let c = [1, 2, 3]; let d = vec![1, 2, 3]; let a: &[i32]; let b: &[i32]; a = &c; b = &d; // ... *a == *b; // Equivalent form: ::std::cmp::PartialEq::eq(&*a, &*b); } ``` Implicit borrows may be taken in the following expressions: * Left operand in [method-call](expressions/method-call-expr) expressions. * Left operand in [field](expressions/field-expr) expressions. * Left operand in [call expressions](expressions/call-expr). * Left operand in [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) expressions. * Operand of the [dereference operator](expressions/operator-expr#the-dereference-operator) (`*`). * Operands of [comparison](expressions/operator-expr#comparison-operators). * Left operands of the [compound assignment](expressions/operator-expr#compound-assignment-expressions). Overloading Traits ------------------ Many of the following operators and expressions can also be overloaded for other types using traits in `std::ops` or `std::cmp`. These traits also exist in `core::ops` and `core::cmp` with the same names. Expression Attributes --------------------- [Outer attributes](attributes) before an expression are allowed only in a few specific cases: * Before an expression used as a [statement](statements). * Elements of [array expressions](expressions/array-expr), [tuple expressions](expressions/tuple-expr), [call expressions](expressions/call-expr), and tuple-style [struct](expressions/struct-expr) expressions. * The tail expression of [block expressions](expressions/block-expr). They are never allowed before: * [Range](expressions/range-expr) expressions. * Binary operator expressions ([*ArithmeticOrLogicalExpression*](expressions/operator-expr#arithmetic-and-logical-binary-operators), [*ComparisonExpression*](expressions/operator-expr#comparison-operators), [*LazyBooleanExpression*](expressions/operator-expr#lazy-boolean-operators), [*TypeCastExpression*](expressions/operator-expr#type-cast-expressions), [*AssignmentExpression*](expressions/operator-expr#assignment-expressions), [*CompoundAssignmentExpression*](expressions/operator-expr#compound-assignment-expressions)).
programming_docs
rust The Rust runtime The Rust runtime ================ This section documents features that define some aspects of the Rust runtime. The `panic_handler` attribute ----------------------------- The *`panic_handler` attribute* can only be applied to a function with signature `fn(&PanicInfo) -> !`. The function marked with this [attribute](attributes) defines the behavior of panics. The [`PanicInfo`](https://doc.rust-lang.org/core/panic/struct.PanicInfo.html) struct contains information about the location of the panic. There must be a single `panic_handler` function in the dependency graph of a binary, dylib or cdylib crate. Below is shown a `panic_handler` function that logs the panic message and then halts the thread. ``` #![no_std] use core::fmt::{self, Write}; use core::panic::PanicInfo; struct Sink { // .. _0: (), } impl Sink { fn new() -> Sink { Sink { _0: () }} } impl fmt::Write for Sink { fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) } } #[panic_handler] fn panic(info: &PanicInfo) -> ! { let mut sink = Sink::new(); // logs "panicked at '$reason', src/main.rs:27:4" to some `sink` let _ = writeln!(sink, "{}", info); loop {} } ``` ### Standard behavior The standard library provides an implementation of `panic_handler` that defaults to unwinding the stack but that can be [changed to abort the process](../book/ch09-01-unrecoverable-errors-with-panic). The standard library's panic behavior can be modified at runtime with the [set\_hook](../std/panic/fn.set_hook) function. The `global_allocator` attribute -------------------------------- The *`global_allocator` attribute* is used on a [static item](items/static-items) implementing the [`GlobalAlloc`](https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html) trait to set the global allocator. The `windows_subsystem` attribute --------------------------------- The *`windows_subsystem` attribute* may be applied at the crate level to set the [subsystem](https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx) when linking on a Windows target. It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the subsystem with a value of either `console` or `windows`. This attribute is ignored on non-Windows targets, and for non-`bin` [crate types](linkage). The "console" subsystem is the default. If a console process is run from an existing console then it will be attached to that console, otherwise a new console window will be created. The "windows" subsystem is commonly used by GUI applications that do not want to display a console window on startup. It will run detached from any existing console. ``` #![allow(unused)] #![windows_subsystem = "windows"] fn main() { } ``` rust Introduction Introduction ============ This book is the primary reference for the Rust programming language. It provides three kinds of material: * Chapters that informally describe each language construct and their use. * Chapters that informally describe the memory model, concurrency model, runtime services, linkage model, and debugging facilities. * Appendix chapters providing rationale and references to languages that influenced the design. Warning: This book is incomplete. Documenting everything takes a while. See the [GitHub issues](https://github.com/rust-lang/reference/issues) for what is not documented in this book. Rust releases ------------- Rust has a new language release every six weeks. The first stable release of the language was Rust 1.0.0, followed by Rust 1.1.0 and so on. Tools (`rustc`, `cargo`, etc.) and documentation ([Standard library](../std/index), this book, etc.) are released with the language release. The latest release of this book, matching the latest Rust version, can always be found at [https://doc.rust-lang.org/reference/](index). Prior versions can be found by adding the Rust version before the "reference" directory. For example, the Reference for Rust 1.49.0 is located at [https://doc.rust-lang.org/1.49.0/reference/](https://doc.rust-lang.org/1.49.0/reference/index.html). What *The Reference* is not --------------------------- This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate [book](../index) is available to help acquire such background familiarity. This book also does not serve as a reference to the [standard library](../std/index) included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you're looking for may be there, not here. Similarly, this book does not usually document the specifics of `rustc` as a tool or of Cargo. `rustc` has its own [book](https://doc.rust-lang.org/rustc/index.html). Cargo has a [book](https://doc.rust-lang.org/cargo/index.html) that contains a [reference](https://doc.rust-lang.org/cargo/reference/index.html). There are a few pages such as <linkage> that still describe how `rustc` works. This book also only serves as a reference to what is available in stable Rust. For unstable features being worked on, see the [Unstable Book](https://doc.rust-lang.org/unstable-book/index.html). Rust compilers, including `rustc`, will perform optimizations. The reference does not specify what optimizations are allowed or disallowed. Instead, think of the compiled program as a black box. You can only probe by running it, feeding it input and observing its output. Everything that happens that way must conform to what the reference says. Finally, this book is not normative. It may include details that are specific to `rustc` itself, and should not be taken as a specification for the Rust language. We intend to produce such a book someday, and until then, the reference is the closest thing we have to one. How to use this book -------------------- This book does not assume you are reading this book sequentially. Each chapter generally can be read standalone, but will cross-link to other chapters for facets of the language they refer to, but do not discuss. There are two main ways to read this document. The first is to answer a specific question. If you know which chapter answers that question, you can jump to that chapter in the table of contents. Otherwise, you can press `s` or click the magnifying glass on the top bar to search for keywords related to your question. For example, say you wanted to know when a temporary value created in a let statement is dropped. If you didn't already know that the [lifetime of temporaries](expressions#temporaries) is defined in the [expressions chapter](expressions), you could search "temporary let" and the first search result will take you to that section. The second is to generally improve your knowledge of a facet of the language. In that case, just browse the table of contents until you see something you want to know more about, and just start reading. If a link looks interesting, click it, and read about that section. That said, there is no wrong way to read this book. Read it however you feel helps you best. ### Conventions Like all technical books, this book has certain conventions in how it displays information. These conventions are documented here. * Statements that define a term contain that term in *italics*. Whenever that term is used outside of that chapter, it is usually a link to the section that has this definition. An *example term* is an example of a term being defined. * Differences in the language by which edition the crate is compiled under are in a blockquote that start with the words "Edition Differences:" in **bold**. > **Edition Differences**: In the 2015 edition, this syntax is valid that is disallowed as of the 2018 edition. > > * Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in blockquotes that start with the word "Note:" in **bold**. > **Note**: This is an example note. > > * Warnings that show unsound behavior in the language or possibly confusing interactions of language features are in a special warning box. Warning: This is an example warning. * Code snippets inline in the text are inside `<code>` tags. Longer code examples are in a syntax highlighted box that has controls for copying, executing, and showing hidden lines in the top right corner. ``` // This is a hidden line. fn main() { println!("This is a code example"); } ``` All examples are written for the latest edition unless otherwise stated. * The grammar and lexical structure is in blockquotes with either "Lexer" or "Syntax" in **bold superscript** as the first line. > **Syntax** > *ExampleGrammar*: > `~` [*Expression*](expressions) > | `box` [*Expression*](expressions) > > See [Notation](notation) for more detail. Contributing ------------ We welcome contributions of all kinds. You can contribute to this book by opening an issue or sending a pull request to [the Rust Reference repository](https://github.com/rust-lang/reference/). If this book does not answer your question, and you think its answer is in scope of it, please do not hesitate to [file an issue](https://github.com/rust-lang/reference/issues) or ask about it in the `t-lang/doc` stream on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/237824-t-lang.2Fdoc). Knowing what people use this book for the most helps direct our attention to making those sections the best that they can be. We also want the reference to be as normative as possible, so if you see anything that is wrong or is non-normative but not specifically called out, please also [file an issue](https://github.com/rust-lang/reference/issues). rust Unsafety Unsafety ======== Unsafe operations are those that can potentially violate the memory-safety guarantees of Rust's static semantics. The following language level features cannot be used in the safe subset of Rust: * Dereferencing a [raw pointer](types/pointer). * Reading or writing a [mutable](items/static-items#mutable-statics) or [external](items/external-blocks) static variable. * Accessing a field of a [`union`](items/unions), other than to assign to it. * Calling an unsafe function (including an intrinsic or foreign function). * Implementing an [unsafe trait](items/traits#unsafe-traits). rust Behavior considered undefined Behavior considered undefined ============================= Rust code is incorrect if it exhibits any of the behaviors in the following list. This includes code within `unsafe` blocks and `unsafe` functions. `unsafe` only means that avoiding undefined behavior is on the programmer; it does not change anything about the fact that Rust programs must never cause undefined behavior. It is the programmer's responsibility when writing `unsafe` code to ensure that any safe code interacting with the `unsafe` code cannot trigger these behaviors. `unsafe` code that satisfies this property for any safe client is called *sound*; if `unsafe` code can be misused by safe code to exhibit undefined behavior, it is *unsound*. ***Warning:*** The following list is not exhaustive. There is no formal model of Rust's semantics for what is and is not allowed in unsafe code, so there may be more behavior considered unsafe. The following list is just what we know for sure is undefined behavior. Please read the [Rustonomicon](https://doc.rust-lang.org/nomicon/index.html) before writing unsafe code. * Data races. * Evaluating a [dereference expression](expressions/operator-expr#the-dereference-operator) (`*expr`) on a raw pointer that is [dangling](#dangling-pointers) or unaligned, even in [place expression context](expressions#place-expressions-and-value-expressions) (e.g. `addr_of!(&*expr)`). * Breaking the [pointer aliasing rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules). `&mut T` and `&T` follow LLVM’s scoped [noalias](http://llvm.org/docs/LangRef.html#noalias) model, except if the `&T` contains an [`UnsafeCell<U>`](../std/cell/struct.unsafecell). * Mutating immutable data. All data inside a [`const`](items/constant-items) item is immutable. Moreover, all data reached through a shared reference or data owned by an immutable binding is immutable, unless that data is contained within an [`UnsafeCell<U>`](../std/cell/struct.unsafecell). * Invoking undefined behavior via compiler intrinsics. * Executing code compiled with platform features that the current platform does not support (see [`target_feature`](attributes/codegen#the-target_feature-attribute)), *except* if the platform explicitly documents this to be safe. * Calling a function with the wrong call ABI or unwinding from a function with the wrong unwind ABI. * Producing an invalid value, even in private fields and locals. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation. The following values are invalid (at their respective type): + A value other than `false` (`0`) or `true` (`1`) in a [`bool`](types/boolean). + A discriminant in an `enum` not included in the type definition. + A null `fn` pointer. + A value in a `char` which is a surrogate or above `char::MAX`. + A `!` (all values are invalid for this type). + An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer obtained from [uninitialized memory](http://llvm.org/docs/LangRef.html#undefined-values), or uninitialized memory in a `str`. + A reference or `Box<T>` that is [dangling](#dangling-pointers), unaligned, or points to an invalid value. + Invalid metadata in a wide reference, `Box<T>`, or raw pointer: - `dyn Trait` metadata is invalid if it is not a pointer to a vtable for `Trait` that matches the actual dynamic trait the pointer or reference points to. - Slice metadata is invalid if the length is not a valid `usize` (i.e., it must not be read from uninitialized memory). + Invalid values for a type with a custom definition of invalid values. In the standard library, this affects [`NonNull<T>`](https://doc.rust-lang.org/core/ptr/struct.NonNull.html) and [`NonZero*`](https://doc.rust-lang.org/core/num/index.html). > **Note**: `rustc` achieves this with the unstable `rustc_layout_scalar_valid_range_*` attributes. > > * Incorrect use of inline assembly. For more details, refer to the [rules](inline-assembly#rules-for-inline-assembly) to follow when writing code that uses inline assembly. **Note:** Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside `union`s and in "padding" (the gaps between the fields/elements of a type). > **Note**: Undefined behavior affects the entire program. For example, calling a function in C that exhibits undefined behavior of C means your entire program contains undefined behaviour that can also affect the Rust code. And vice versa, undefined behavior in Rust can cause adverse affects on code executed by any FFI calls to other languages. > > ### Dangling pointers A reference/pointer is "dangling" if it is null or not all of the bytes it points to are part of the same live allocation (so in particular they all have to be part of *some* allocation). The span of bytes it points to is determined by the pointer value and the size of the pointee type (using `size_of_val`). If the size is 0, then the pointer must either point inside of a live allocation (including pointing just after the last byte of the allocation), or it must be directly constructed from a non-zero integer literal. Note that dynamically sized types (such as slices and strings) point to their entire range, so it is important that the length metadata is never too large. In particular, the dynamic size of a Rust value (as determined by `size_of_val`) must never exceed `isize::MAX`. rust Trait and lifetime bounds Trait and lifetime bounds ========================= > **Syntax** > *TypeParamBounds* : > *TypeParamBound* ( `+` *TypeParamBound* )\* `+`? > > *TypeParamBound* : > *Lifetime* | *TraitBound* > > *TraitBound* : > `?`? [*ForLifetimes*](#higher-ranked-trait-bounds)? [*TypePath*](paths#paths-in-types) > | `(` `?`? [*ForLifetimes*](#higher-ranked-trait-bounds)? [*TypePath*](paths#paths-in-types) `)` > > *LifetimeBounds* : > ( *Lifetime* `+` )\* *Lifetime*? > > *Lifetime* : > [LIFETIME\_OR\_LABEL](tokens#lifetimes-and-loop-labels) > | `'static` > | `'_` > > [Trait](items/traits#trait-bounds) and lifetime bounds provide a way for [generic items](items/generics) to restrict which types and lifetimes are used as their parameters. Bounds can be provided on any type in a [where clause](items/generics#where-clauses). There are also shorter forms for certain common cases: * Bounds written after declaring a [generic parameter](items/generics): `fn f<A: Copy>() {}` is the same as `fn f<A> where A: Copy () {}`. * In trait declarations as [supertraits](items/traits#supertraits): `trait Circle : Shape {}` is equivalent to `trait Circle where Self : Shape {}`. * In trait declarations as bounds on [associated types](items/associated-items#associated-types): `trait A { type B: Copy; }` is equivalent to `trait A where Self::B: Copy { type B; }`. Bounds on an item must be satisfied when using the item. When type checking and borrow checking a generic item, the bounds can be used to determine that a trait is implemented for a type. For example, given `Ty: Trait` * In the body of a generic function, methods from `Trait` can be called on `Ty` values. Likewise associated constants on the `Trait` can be used. * Associated types from `Trait` can be used. * Generic functions and types with a `T: Trait` bounds can be used with `Ty` being used for `T`. ``` #![allow(unused)] fn main() { type Surface = i32; trait Shape { fn draw(&self, surface: Surface); fn name() -> &'static str; } fn draw_twice<T: Shape>(surface: Surface, sh: T) { sh.draw(surface); // Can call method because T: Shape sh.draw(surface); } fn copy_and_draw_twice<T: Copy>(surface: Surface, sh: T) where T: Shape { let shape_copy = sh; // doesn't move sh because T: Copy draw_twice(surface, sh); // Can use generic function because T: Shape } struct Figure<S: Shape>(S, S); fn name_figure<U: Shape>( figure: Figure<U>, // Type Figure<U> is well-formed because U: Shape ) { println!( "Figure of two {}", U::name(), // Can use associated function ); } } ``` Bounds that don't use the item's parameters or [higher-ranked lifetimes](#higher-ranked-trait-bounds) are checked when the item is defined. It is an error for such a bound to be false. [`Copy`](special-types-and-traits#copy), [`Clone`](special-types-and-traits#clone), and [`Sized`](special-types-and-traits#sized) bounds are also checked for certain generic types when using the item, even if the use does not provide a concrete type. It is an error to have `Copy` or `Clone` as a bound on a mutable reference, [trait object](types/trait-object), or [slice](types/slice). It is an error to have `Sized` as a bound on a trait object or slice. ``` #![allow(unused)] fn main() { struct A<'a, T> where i32: Default, // Allowed, but not useful i32: Iterator, // Error: `i32` is not an iterator &'a mut T: Copy, // (at use) Error: the trait bound is not satisfied [T]: Sized, // (at use) Error: size cannot be known at compilation { f: &'a T, } struct UsesA<'a, T>(A<'a, T>); } ``` Trait and lifetime bounds are also used to name [trait objects](types/trait-object). `?Sized` -------- `?` is only used to relax the implicit [`Sized`](special-types-and-traits#sized) trait bound for [type parameters](types/parameters) or [associated types](items/associated-items#associated-types). `?Sized` may not be used as a bound for other types. Lifetime bounds --------------- Lifetime bounds can be applied to types or to other lifetimes. The bound `'a: 'b` is usually read as `'a` *outlives* `'b`. `'a: 'b` means that `'a` lasts at least as long as `'b`, so a reference `&'a ()` is valid whenever `&'b ()` is valid. ``` #![allow(unused)] fn main() { fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b { y = x; // &'a i32 is a subtype of &'b i32 because 'a: 'b let r: &'b &'a i32 = &&0; // &'b &'a i32 is well formed because 'a: 'b } } ``` `T: 'a` means that all lifetime parameters of `T` outlive `'a`. For example, if `'a` is an unconstrained lifetime parameter, then `i32: 'static` and `&'static str: 'a` are satisfied, but `Vec<&'a ()>: 'static` is not. Higher-ranked trait bounds -------------------------- > *ForLifetimes* : > `for` [*GenericParams*](items/generics) > > Type bounds may be *higher ranked* over lifetimes. These bounds specify a bound that is true *for all* lifetimes. For example, a bound such as `for<'a> &'a T: PartialEq<i32>` would require an implementation like ``` #![allow(unused)] fn main() { struct T; impl<'a> PartialEq<i32> for &'a T { // ... fn eq(&self, other: &i32) -> bool {true} } } ``` and could then be used to compare a `&'a T` with any lifetime to an `i32`. Only a higher-ranked bound can be used here, because the lifetime of the reference is shorter than any possible lifetime parameter on the function: ``` #![allow(unused)] fn main() { fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) { let zero = 0; f(&zero); } } ``` Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent to the last one. ``` #![allow(unused)] fn main() { fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) { let zero = 0; f(&zero); } } ```
programming_docs
rust Whitespace Whitespace ========== Whitespace is any non-empty string containing only characters that have the [`Pattern_White_Space`](https://www.unicode.org/reports/tr31/) Unicode property, namely: * `U+0009` (horizontal tab, `'\t'`) * `U+000A` (line feed, `'\n'`) * `U+000B` (vertical tab) * `U+000C` (form feed) * `U+000D` (carriage return, `'\r'`) * `U+0020` (space, `' '`) * `U+0085` (next line) * `U+200E` (left-to-right mark) * `U+200F` (right-to-left mark) * `U+2028` (line separator) * `U+2029` (paragraph separator) Rust is a "free-form" language, meaning that all forms of whitespace serve only to separate *tokens* in the grammar, and have no semantic significance. A Rust program has identical meaning if each whitespace element is replaced with any other legal whitespace element, such as a single space character. rust Notation Notation ======== Grammar ------- The following notations are used by the *Lexer* and *Syntax* grammar snippets: | Notation | Examples | Meaning | | --- | --- | --- | | CAPITAL | KW\_IF, INTEGER\_LITERAL | A token produced by the lexer | | *ItalicCamelCase* | *LetStatement*, *Item* | A syntactical production | | `string` | `x`, `while`, `*` | The exact character(s) | | \x | \n, \r, \t, \0 | The character represented by this escape | | x? | `pub`? | An optional item | | x\* | *OuterAttribute*\* | 0 or more of x | | x+ | *MacroMatch*+ | 1 or more of x | | xa..b | HEX\_DIGIT1..6 | a to b repetitions of x | | | | `u8` | `u16`, Block | Item | Either one or another | | [ ] | [`b` `B`] | Any of the characters listed | | [ - ] | [`a`-`z`] | Any of the characters in the range | | ~[ ] | ~[`b` `B`] | Any characters, except those listed | | ~`string` | ~`\n`, ~`*/` | Any characters, except this sequence | | ( ) | (`,` *Parameter*)? | Groups items | String table productions ------------------------ Some rules in the grammar — notably [unary operators](expressions/operator-expr#borrow-operators), [binary operators](expressions/operator-expr#arithmetic-and-logical-binary-operators), and <keywords> — are given in a simplified form: as a listing of printable strings. These cases form a subset of the rules regarding the [token](tokens) rule, and are assumed to be the result of a lexical-analysis phase feeding the parser, driven by a DFA, operating over the disjunction of all such string table entries. When such a string in `monospace` font occurs inside the grammar, it is an implicit reference to a single member of such a string table production. See <tokens> for more information. rust Impl trait Impl trait ========== > **Syntax** > *ImplTraitType* : `impl` [*TypeParamBounds*](../trait-bounds) > > *ImplTraitTypeOneBound* : `impl` [*TraitBound*](../trait-bounds) > > `impl Trait` provides ways to specify unnamed but concrete types that implement a specific trait. It can appear in two sorts of places: argument position (where it can act as an anonymous type parameter to functions), and return position (where it can act as an abstract return type). ``` #![allow(unused)] fn main() { trait Trait {} impl Trait for () {} // argument position: anonymous type parameter fn foo(arg: impl Trait) { } // return position: abstract return type fn bar() -> impl Trait { } } ``` Anonymous type parameters ------------------------- > Note: This is often called "impl Trait in argument position". (The term "parameter" is more correct here, but "impl Trait in argument position" is the phrasing used during the development of this feature, and it remains in parts of the implementation.) > > Functions can use `impl` followed by a set of trait bounds to declare a parameter as having an anonymous type. The caller must provide a type that satisfies the bounds declared by the anonymous type parameter, and the function can only use the methods available through the trait bounds of the anonymous type parameter. For example, these two forms are almost equivalent: ``` trait Trait {} // generic type parameter fn foo<T: Trait>(arg: T) { } // impl Trait in argument position fn foo(arg: impl Trait) { } ``` That is, `impl Trait` in argument position is syntactic sugar for a generic type parameter like `<T: Trait>`, except that the type is anonymous and doesn't appear in the [*GenericParams*](../items/generics) list. > **Note:** For function parameters, generic type parameters and `impl Trait` are not exactly equivalent. With a generic parameter such as `<T: Trait>`, the caller has the option to explicitly specify the generic argument for `T` at the call site using [*GenericArgs*](../paths#paths-in-expressions), for example, `foo::<usize>(1)`. If `impl Trait` is the type of *any* function parameter, then the caller can't ever provide any generic arguments when calling that function. This includes generic arguments for the return type or any const generics. > > Therefore, changing the function signature from either one to the other can constitute a breaking change for the callers of a function. > > Abstract return types --------------------- > Note: This is often called "impl Trait in return position". > > Functions can use `impl Trait` to return an abstract return type. These types stand in for another concrete type where the caller may only use the methods declared by the specified `Trait`. Each possible return value from the function must resolve to the same concrete type. `impl Trait` in return position allows a function to return an unboxed abstract type. This is particularly useful with [closures](closure) and iterators. For example, closures have a unique, un-writable type. Previously, the only way to return a closure from a function was to use a [trait object](trait-object): ``` #![allow(unused)] fn main() { fn returns_closure() -> Box<dyn Fn(i32) -> i32> { Box::new(|x| x + 1) } } ``` This could incur performance penalties from heap allocation and dynamic dispatch. It wasn't possible to fully specify the type of the closure, only to use the `Fn` trait. That means that the trait object is necessary. However, with `impl Trait`, it is possible to write this more simply: ``` #![allow(unused)] fn main() { fn returns_closure() -> impl Fn(i32) -> i32 { |x| x + 1 } } ``` which also avoids the drawbacks of using a boxed trait object. Similarly, the concrete types of iterators could become very complex, incorporating the types of all previous iterators in a chain. Returning `impl Iterator` means that a function only exposes the `Iterator` trait as a bound on its return type, instead of explicitly specifying all of the other iterator types involved. ### Differences between generics and `impl Trait` in return position In argument position, `impl Trait` is very similar in semantics to a generic type parameter. However, there are significant differences between the two in return position. With `impl Trait`, unlike with a generic type parameter, the function chooses the return type, and the caller cannot choose the return type. The function: ``` fn foo<T: Trait>() -> T { ``` allows the caller to determine the return type, `T`, and the function returns that type. The function: ``` fn foo() -> impl Trait { ``` doesn't allow the caller to determine the return type. Instead, the function chooses the return type, but only promises that it will implement `Trait`. Limitations ----------- `impl Trait` can only appear as a parameter or return type of a free or inherent function. It cannot appear inside implementations of traits, nor can it be the type of a let binding or appear inside a type alias. rust Trait objects Trait objects ============= > **Syntax** > *TraitObjectType* : > `dyn`? [*TypeParamBounds*](../trait-bounds) > > *TraitObjectTypeOneBound* : > `dyn`? [*TraitBound*](../trait-bounds) > > A *trait object* is an opaque value of another type that implements a set of traits. The set of traits is made up of an [object safe](../items/traits#object-safety) *base trait* plus any number of [auto traits](../special-types-and-traits#auto-traits). Trait objects implement the base trait, its auto traits, and any [supertraits](../items/traits#supertraits) of the base trait. Trait objects are written as the keyword `dyn` followed by a set of trait bounds, but with the following restrictions on the trait bounds. All traits except the first trait must be auto traits, there may not be more than one lifetime, and opt-out bounds (e.g. `?Sized`) are not allowed. Furthermore, paths to traits may be parenthesized. For example, given a trait `Trait`, the following are all trait objects: * `dyn Trait` * `dyn Trait + Send` * `dyn Trait + Send + Sync` * `dyn Trait + 'static` * `dyn Trait + Send + 'static` * `dyn Trait +` * `dyn 'static + Trait`. * `dyn (Trait)` > **Edition Differences**: Before the 2021 edition, the `dyn` keyword may be omitted. > > Note: For clarity, it is recommended to always use the `dyn` keyword on your trait objects unless your codebase supports compiling with Rust 1.26 or lower. > > > **Edition Differences**: In the 2015 edition, if the first bound of the trait object is a path that starts with `::`, then the `dyn` will be treated as a part of the path. The first path can be put in parenthesis to get around this. As such, if you want a trait object with the trait `::your_module::Trait`, you should write it as `dyn (::your_module::Trait)`. > > Beginning in the 2018 edition, `dyn` is a true keyword and is not allowed in paths, so the parentheses are not necessary. > > Two trait object types alias each other if the base traits alias each other and if the sets of auto traits are the same and the lifetime bounds are the same. For example, `dyn Trait + Send + UnwindSafe` is the same as `dyn Trait + UnwindSafe + Send`. Due to the opaqueness of which concrete type the value is of, trait objects are [dynamically sized types](../dynamically-sized-types). Like all DSTs, trait objects are used behind some type of pointer; for example `&dyn SomeTrait` or `Box<dyn SomeTrait>`. Each instance of a pointer to a trait object includes: * a pointer to an instance of a type `T` that implements `SomeTrait` * a *virtual method table*, often just called a *vtable*, which contains, for each method of `SomeTrait` and its [supertraits](../items/traits#supertraits) that `T` implements, a pointer to `T`'s implementation (i.e. a function pointer). The purpose of trait objects is to permit "late binding" of methods. Calling a method on a trait object results in virtual dispatch at runtime: that is, a function pointer is loaded from the trait object vtable and invoked indirectly. The actual implementation for each vtable entry can vary on an object-by-object basis. An example of a trait object: ``` trait Printable { fn stringify(&self) -> String; } impl Printable for i32 { fn stringify(&self) -> String { self.to_string() } } fn print(a: Box<dyn Printable>) { println!("{}", a.stringify()); } fn main() { print(Box::new(10) as Box<dyn Printable>); } ``` In this example, the trait `Printable` occurs as a trait object in both the type signature of `print`, and the cast expression in `main`. Trait Object Lifetime Bounds ---------------------------- Since a trait object can contain references, the lifetimes of those references need to be expressed as part of the trait object. This lifetime is written as `Trait + 'a`. There are [defaults](../lifetime-elision#default-trait-object-lifetimes) that allow this lifetime to usually be inferred with a sensible choice. rust Numeric types Numeric types ============= Integer types ------------- The unsigned integer types consist of: | Type | Minimum | Maximum | | --- | --- | --- | | `u8` | 0 | 28-1 | | `u16` | 0 | 216-1 | | `u32` | 0 | 232-1 | | `u64` | 0 | 264-1 | | `u128` | 0 | 2128-1 | The signed two's complement integer types consist of: | Type | Minimum | Maximum | | --- | --- | --- | | `i8` | -(27) | 27-1 | | `i16` | -(215) | 215-1 | | `i32` | -(231) | 231-1 | | `i64` | -(263) | 263-1 | | `i128` | -(2127) | 2127-1 | Floating-point types -------------------- The IEEE 754-2008 "binary32" and "binary64" floating-point types are `f32` and `f64`, respectively. Machine-dependent integer types ------------------------------- The `usize` type is an unsigned integer type with the same number of bits as the platform's pointer type. It can represent every memory address in the process. The `isize` type is a signed integer type with the same number of bits as the platform's pointer type. The theoretical upper bound on object and array size is the maximum `isize` value. This ensures that `isize` can be used to calculate differences between pointers into an object or array and can address every byte within an object along with one byte past the end. `usize` and `isize` are at least 16-bits wide. > **Note**: Many pieces of Rust code may assume that pointers, `usize`, and `isize` are either 32-bit or 64-bit. As a consequence, 16-bit pointer support is limited and may require explicit care and acknowledgment from a library to support. > > rust Union types Union types =========== A *union type* is a nominal, heterogeneous C-like union, denoted by the name of a [`union` item](../items/unions). Unions have no notion of an "active field". Instead, every union access transmutes parts of the content of the union to the type of the accessed field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is required to read from a union field. Union field types are also restricted to a subset of types which ensures that they never need dropping. See the [item](../items/unions) documentation for further details. The memory layout of a `union` is undefined by default (in particular, fields do *not* have to be at offset 0), but the `#[repr(...)]` attribute can be used to fix a layout. rust Pointer types Pointer types ============= All pointers are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions. References (`&` and `&mut`) --------------------------- > **Syntax** > *ReferenceType* : > `&` [*Lifetime*](../trait-bounds)? `mut`? [*TypeNoBounds*](../types#type-expressions) > > ### Shared references (`&`) These point to memory *owned by some other value*. When a shared reference to a value is created it prevents direct mutation of the value. [Interior mutability](../interior-mutability) provides an exception for this in certain circumstances. As the name suggests, any number of shared references to a value may exist. A shared reference type is written `&type`, or `&'a type` when you need to specify an explicit lifetime. Copying a reference is a "shallow" operation: it involves only copying the pointer itself, that is, pointers are `Copy`. Releasing a reference has no effect on the value it points to, but referencing of a [temporary value](../expressions#temporaries) will keep it alive during the scope of the reference itself. ### Mutable references (`&mut`) These also point to memory owned by some other value. A mutable reference type is written `&mut type` or `&'a mut type`. A mutable reference (that hasn't been borrowed) is the only way to access the value it points to, so is not `Copy`. Raw pointers (`*const` and `*mut`) ---------------------------------- > **Syntax** > *RawPointerType* : > `*` ( `mut` | `const` ) [*TypeNoBounds*](../types#type-expressions) > > Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as `*const T` or `*mut T`. For example `*const i32` means a raw pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer is an [`unsafe` operation](../unsafety). This can also be used to convert a raw pointer to a reference by reborrowing it (`&*` or `&mut *`). Raw pointers are generally discouraged; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions. When comparing raw pointers they are compared by their address, rather than by what they point to. When comparing raw pointers to [dynamically sized types](../dynamically-sized-types) they also have their additional data compared. Raw pointers can be created directly using [`core::ptr::addr_of!`](https://doc.rust-lang.org/core/ptr/macro.addr_of.html) for `*const` pointers and [`core::ptr::addr_of_mut!`](https://doc.rust-lang.org/core/ptr/macro.addr_of_mut.html) for `*mut` pointers. Smart Pointers -------------- The standard library contains additional 'smart pointer' types beyond references and raw pointers. rust Never type Never type ========== > **Syntax** > *NeverType* : `!` > > The never type `!` is a type with no values, representing the result of computations that never complete. Expressions of type `!` can be coerced into any other type. ``` let x: ! = panic!(); // Can be coerced into any type. let y: u32 = x; ``` **NB.** The never type was expected to be stabilized in 1.41, but due to some last minute regressions detected the stabilization was temporarily reverted. The `!` type can only appear in function return types presently. See [the tracking issue](https://github.com/rust-lang/rust/issues/35121) for more details. rust Closure types Closure types ============= A [closure expression](../expressions/closure-expr) produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured variables. For instance, the following closure: ``` #![allow(unused)] fn main() { fn f<F : FnOnce() -> String> (g: F) { println!("{}", g()); } let mut s = String::from("foo"); let t = String::from("bar"); f(|| { s += &t; s }); // Prints "foobar". } ``` generates a closure type roughly like the following: ``` struct Closure<'a> { s : String, t : &'a String, } impl<'a> FnOnce<()> for Closure<'a> { type Output = String; fn call_once(self) -> String { self.s += &*self.t; self.s } } ``` so that the call to `f` works as if it were: ``` f(Closure{s: s, t: &t}); ``` Capture modes ------------- The compiler prefers to capture a closed-over variable by immutable borrow, followed by unique immutable borrow (see below), by mutable borrow, and finally by move. It will pick the first choice of these that is compatible with how the captured variable is used inside the closure body. The compiler does not take surrounding code into account, such as the lifetimes of involved variables, or of the closure itself. If the `move` keyword is used, then all captures are by move or, for `Copy` types, by copy, regardless of whether a borrow would work. The `move` keyword is usually used to allow the closure to outlive the captured values, such as if the closure is being returned or used to spawn a new thread. Composite types such as structs, tuples, and enums are always captured entirely, not by individual fields. It may be necessary to borrow into a local variable in order to capture a single field: ``` #![allow(unused)] fn main() { use std::collections::HashSet; struct SetVec { set: HashSet<u32>, vec: Vec<u32> } impl SetVec { fn populate(&mut self) { let vec = &mut self.vec; self.set.iter().for_each(|&n| { vec.push(n); }) } } } ``` If, instead, the closure were to use `self.vec` directly, then it would attempt to capture `self` by mutable reference. But since `self.set` is already borrowed to iterate over, the code would not compile. Unique immutable borrows in captures ------------------------------------ Captures can occur by a special kind of borrow called a *unique immutable borrow*, which cannot be used anywhere else in the language and cannot be written out explicitly. It occurs when modifying the referent of a mutable reference, as in the following example: ``` #![allow(unused)] fn main() { let mut b = false; let x = &mut b; { let mut c = || { *x = true; }; // The following line is an error: // let y = &x; c(); } let z = &x; } ``` In this case, borrowing `x` mutably is not possible, because `x` is not `mut`. But at the same time, borrowing `x` immutably would make the assignment illegal, because a `& &mut` reference might not be unique, so it cannot safely be used to modify a value. So a unique immutable borrow is used: it borrows `x` immutably, but like a mutable borrow, it must be unique. In the above example, uncommenting the declaration of `y` will produce an error because it would violate the uniqueness of the closure's borrow of `x`; the declaration of z is valid because the closure's lifetime has expired at the end of the block, releasing the borrow. Call traits and coercions ------------------------- Closure types all implement [`FnOnce`](../../std/ops/trait.fnonce), indicating that they can be called once by consuming ownership of the closure. Additionally, some closures implement more specific call traits: * A closure which does not move out of any captured variables implements [`FnMut`](../../std/ops/trait.fnmut), indicating that it can be called by mutable reference. * A closure which does not mutate or move out of any captured variables implements [`Fn`](../../std/ops/trait.fn), indicating that it can be called by shared reference. > Note: `move` closures may still implement [`Fn`](../../std/ops/trait.fn) or [`FnMut`](../../std/ops/trait.fnmut), even though they capture variables by move. This is because the traits implemented by a closure type are determined by what the closure does with captured values, not how it captures them. > > *Non-capturing closures* are closures that don't capture anything from their environment. They can be coerced to function pointers (e.g., `fn()`) with the matching signature. ``` #![allow(unused)] fn main() { let add = |x, y| x + y; let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); } ``` Other traits ------------ All closure types implement [`Sized`](../special-types-and-traits#sized). Additionally, closure types implement the following traits if allowed to do so by the types of the captures it stores: * [`Clone`](../special-types-and-traits#clone) * [`Copy`](../special-types-and-traits#copy) * [`Sync`](../special-types-and-traits#sync) * [`Send`](../special-types-and-traits#send) The rules for [`Send`](../special-types-and-traits#send) and [`Sync`](../special-types-and-traits#sync) match those for normal struct types, while [`Clone`](../special-types-and-traits#clone) and [`Copy`](../special-types-and-traits#copy) behave as if [derived](../attributes/derive). For [`Clone`](../special-types-and-traits#clone), the order of cloning of the captured variables is left unspecified. Because captures are often by reference, the following general rules arise: * A closure is [`Sync`](../special-types-and-traits#sync) if all captured variables are [`Sync`](../special-types-and-traits#sync). * A closure is [`Send`](../special-types-and-traits#send) if all variables captured by non-unique immutable reference are [`Sync`](../special-types-and-traits#sync), and all values captured by unique immutable or mutable reference, copy, or move are [`Send`](../special-types-and-traits#send). * A closure is [`Clone`](../special-types-and-traits#clone) or [`Copy`](../special-types-and-traits#copy) if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are [`Clone`](../special-types-and-traits#clone) or [`Copy`](../special-types-and-traits#copy), respectively.
programming_docs
rust Tuple types Tuple types =========== > **Syntax** > *TupleType* : > `(` `)` > | `(` ( [*Type*](../types#type-expressions) `,` )+ [*Type*](../types#type-expressions)? `)` > > *Tuple types* are a family of structural types[1](#1) for heterogeneous lists of other types. The syntax for a tuple type is a parenthesized, comma-separated list of types. 1-ary tuples require a comma after their element type to be disambiguated with a [parenthesized type](../types#parenthesized-types). A tuple type has a number of fields equal to the length of the list of types. This number of fields determines the *arity* of the tuple. A tuple with `n` fields is called an *n-ary tuple*. For example, a tuple with 2 fields is a 2-ary tuple. Fields of tuples are named using increasing numeric names matching their position in the list of types. The first field is `0`. The second field is `1`. And so on. The type of each field is the type of the same position in the tuple's list of types. For convenience and historical reasons, the tuple type with no fields (`()`) is often called *unit* or *the unit type*. Its one value is also called *unit* or *the unit value*. Some examples of tuple types: * `()` (unit) * `(f64, f64)` * `(String, i32)` * `(i32, String)` (different type from the previous example) * `(i32, f64, Vec<String>, Option<bool>)` Values of this type are constructed using a [tuple expression](../expressions/tuple-expr#tuple-expressions). Furthermore, various expressions will produce the unit value if there is no other meaningful value for it to evaluate to. Tuple fields can be accessed by either a [tuple index expression](../expressions/tuple-expr#tuple-indexing-expressions) or [pattern matching](../patterns#tuple-patterns). 1 Structural types are always equivalent if their internal types are equivalent. For a nominal version of tuples, see [tuple structs](struct). rust Function item types Function item types =================== When referred to, a function item, or the constructor of a tuple-like struct or enum variant, yields a zero-sized value of its *function item type*. That type explicitly identifies the function - its name, its type arguments, and its early-bound lifetime arguments (but not its late-bound lifetime arguments, which are only assigned when the function is called) - so the value does not need to contain an actual function pointer, and no indirection is needed when the function is called. There is no syntax that directly refers to a function item type, but the compiler will display the type as something like `fn(u32) -> i32 {fn_name}` in error messages. Because the function item type explicitly identifies the function, the item types of different functions - different items, or the same item with different generics - are distinct, and mixing them will create a type error: ``` #![allow(unused)] fn main() { fn foo<T>() { } let x = &mut foo::<i32>; *x = foo::<u32>; //~ ERROR mismatched types } ``` However, there is a [coercion](../type-coercions) from function items to [function pointers](function-pointer) with the same signature, which is triggered not only when a function item is used when a function pointer is directly expected, but also when different function item types with the same signature meet in different arms of the same `if` or `match`: ``` #![allow(unused)] fn main() { let want_i32 = false; fn foo<T>() { } // `foo_ptr_1` has function pointer type `fn()` here let foo_ptr_1: fn() = foo::<i32>; // ... and so does `foo_ptr_2` - this type-checks. let foo_ptr_2 = if want_i32 { foo::<i32> } else { foo::<u32> }; } ``` All function items implement [`Fn`](../../std/ops/trait.fn), [`FnMut`](../../std/ops/trait.fnmut), [`FnOnce`](../../std/ops/trait.fnonce), [`Copy`](../special-types-and-traits#copy), [`Clone`](../special-types-and-traits#clone), [`Send`](../special-types-and-traits#send), and [`Sync`](../special-types-and-traits#sync). rust Function pointer types Function pointer types ====================== > **Syntax** > *BareFunctionType* : > [*ForLifetimes*](../trait-bounds#higher-ranked-trait-bounds)? *FunctionTypeQualifiers* `fn` > `(` *FunctionParametersMaybeNamedVariadic*? `)` *BareFunctionReturnType*? > > *FunctionTypeQualifiers*: > `unsafe`? (`extern` [*Abi*](../items/functions)?)? > > *BareFunctionReturnType*: > `->` [*TypeNoBounds*](../types#type-expressions) > > *FunctionParametersMaybeNamedVariadic* : > *MaybeNamedFunctionParameters* | *MaybeNamedFunctionParametersVariadic* > > *MaybeNamedFunctionParameters* : > *MaybeNamedParam* ( `,` *MaybeNamedParam* )\* `,`? > > *MaybeNamedParam* : > [*OuterAttribute*](../attributes)\* ( ( [IDENTIFIER](../identifiers) | `_` ) `:` )? [*Type*](../types#type-expressions) > > *MaybeNamedFunctionParametersVariadic* : > ( *MaybeNamedParam* `,` )\* *MaybeNamedParam* `,` [*OuterAttribute*](../attributes)\* `...` > > Function pointer types, written using the `fn` keyword, refer to a function whose identity is not necessarily known at compile-time. They can be created via a coercion from both [function items](function-item) and non-capturing [closures](closure). The `unsafe` qualifier indicates that the type's value is an [unsafe function](../unsafe-functions), and the `extern` qualifier indicates it is an [extern function](../items/functions#extern-function-qualifier). Variadic parameters can only be specified with [`extern`](../items/external-blocks) function types with the `"C"` or `"cdecl"` calling convention. An example where `Binop` is defined as a function pointer type: ``` #![allow(unused)] fn main() { fn add(x: i32, y: i32) -> i32 { x + y } let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); } ``` Attributes on function pointer parameters ----------------------------------------- Attributes on function pointer parameters follow the same rules and restrictions as [regular function parameters](../items/functions#attributes-on-function-parameters). rust Textual types Textual types ============= The types `char` and `str` hold textual data. A value of type `char` is a [Unicode scalar value](http://www.unicode.org/glossary/#unicode_scalar_value) (i.e. a code point that is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range. It is immediate [Undefined Behavior](../behavior-considered-undefined) to create a `char` that falls outside this range. A `[char]` is effectively a UCS-4 / UTF-32 string of length 1. A value of type `str` is represented the same way as `[u8]`, it is a slice of 8-bit unsigned bytes. However, the Rust standard library makes extra assumptions about `str`: methods working on `str` assume and ensure that the data in there is valid UTF-8. Calling a `str` method with a non-UTF-8 buffer can cause [Undefined Behavior](../behavior-considered-undefined) now or in the future. Since `str` is a [dynamically sized type](../dynamically-sized-types), it can only be instantiated through a pointer type, such as `&str`. rust Inferred type Inferred type ============= > **Syntax** > *InferredType* : `_` > > The inferred type asks the compiler to infer the type if possible based on the surrounding information available. It cannot be used in item signatures. It is often used in generic arguments: ``` #![allow(unused)] fn main() { let x: Vec<_> = (0..10).collect(); } ``` rust Slice types Slice types =========== > **Syntax** > *SliceType* : > `[` [*Type*](../types#type-expressions) `]` > > A slice is a [dynamically sized type](../dynamically-sized-types) representing a 'view' into a sequence of elements of type `T`. The slice type is written as `[T]`. Slice types are generally used through pointer types. For example: * `&[T]`: a 'shared slice', often just called a 'slice'. It doesn't own the data it points to; it borrows it. * `&mut [T]`: a 'mutable slice'. It mutably borrows the data it points to. * `Box<[T]>`: a 'boxed slice' Examples: ``` #![allow(unused)] fn main() { // A heap-allocated array, coerced to a slice let boxed_array: Box<[i32]> = Box::new([1, 2, 3]); // A (shared) slice into an array let slice: &[i32] = &boxed_array[..]; } ``` All elements of slices are always initialized, and access to a slice is always bounds-checked in safe methods and operators. rust Enumerated types Enumerated types ================ An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted by the name of an [`enum` item](../items/enumerations). [1](#enumtype) An [`enum` item](../items/enumerations) declares both the type and a number of *variants*, each of which is independently named and has the syntax of a struct, tuple struct or unit-like struct. New instances of an `enum` can be constructed with a [struct expression](../expressions/struct-expr). Any `enum` value consumes as much memory as the largest variant for its corresponding `enum` type, as well as the size needed to store a discriminant. Enum types cannot be denoted *structurally* as types, but must be denoted by named reference to an [`enum` item](../items/enumerations). 1 The `enum` type is analogous to a `data` constructor declaration in ML, or a *pick ADT* in Limbo. rust Array types Array types =========== > **Syntax** > *ArrayType* : > `[` [*Type*](../types#type-expressions) `;` [*Expression*](../expressions) `]` > > An array is a fixed-size sequence of `N` elements of type `T`. The array type is written as `[T; N]`. The size is a [constant expression](../const_eval#constant-expressions) that evaluates to a [`usize`](numeric#machine-dependent-integer-types). Examples: ``` #![allow(unused)] fn main() { // A stack-allocated array let array: [i32; 3] = [1, 2, 3]; // A heap-allocated array, coerced to a slice let boxed_array: Box<[i32]> = Box::new([1, 2, 3]); } ``` All elements of arrays are always initialized, and access to an array is always bounds-checked in safe methods and operators. > Note: The [`Vec<T>`](../../std/vec/struct.vec) standard library type provides a heap-allocated resizable array type. > > rust Type parameters Type parameters =============== Within the body of an item that has type parameter declarations, the names of its type parameters are types: ``` #![allow(unused)] fn main() { fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> { if xs.is_empty() { return vec![]; } let first: A = xs[0].clone(); let mut rest: Vec<A> = to_vec(&xs[1..]); rest.insert(0, first); rest } } ``` Here, `first` has type `A`, referring to `to_vec`'s `A` type parameter; and `rest` has type `Vec<A>`, a vector with element type `A`. rust Boolean type Boolean type ============ ``` #![allow(unused)] fn main() { let b: bool = true; } ``` The *boolean type* or *bool* is a primitive data type that can take on one of two values, called *true* and *false*. Values of this type may be created using a [literal expression](../expressions/literal-expr) using the keywords `true` and `false` corresponding to the value of the same name. This type is a part of the [language prelude](../names/preludes#language-prelude) with the [name](../names) `bool`. An object with the boolean type has a [size and alignment](../type-layout#size-and-alignment) of 1 each. The value false has the bit pattern `0x00` and the value true has the bit pattern `0x01`. It is [undefined behavior](../behavior-considered-undefined) for an object with the boolean type to have any other bit pattern. The boolean type is the type of many operands in various [expressions](../expressions): * The condition operand in [if expressions](../expressions/if-expr#if-expressions) and [while expressions](../expressions/loop-expr#predicate-loops) * The operands in [lazy boolean operator expressions](../expressions/operator-expr#lazy-boolean-operators) > **Note**: The boolean type acts similarly to but is not an [enumerated type](enum). In practice, this mostly means that constructors are not associated to the type (e.g. `bool::true`). > > Like all primitives, the boolean type [implements](../items/implementations) the [traits](../items/traits) [`Clone`](../special-types-and-traits#clone), [`Copy`](../special-types-and-traits#copy), [`Sized`](../special-types-and-traits#sized), [`Send`](../special-types-and-traits#send), and [`Sync`](../special-types-and-traits#sync). > **Note**: See the [standard library docs](../../std/primitive.bool) for library operations. > > Operations on boolean values ---------------------------- When using certain operator expressions with a boolean type for its operands, they evaluate using the rules of [boolean logic](https://en.wikipedia.org/wiki/Boolean_algebra). ### Logical not | `b` | [`!b`](../expressions/operator-expr#negation-operators) | | --- | --- | | `true` | `false` | | `false` | `true` | ### Logical or | `a` | `b` | [`a | b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) | | --- | --- | --- | | `true` | `true` | `true` | | `true` | `false` | `true` | | `false` | `true` | `true` | | `false` | `false` | `false` | ### Logical and | `a` | `b` | [`a & b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) | | --- | --- | --- | | `true` | `true` | `true` | | `true` | `false` | `false` | | `false` | `true` | `false` | | `false` | `false` | `false` | ### Logical xor | `a` | `b` | [`a ^ b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) | | --- | --- | --- | | `true` | `true` | `false` | | `true` | `false` | `true` | | `false` | `true` | `true` | | `false` | `false` | `false` | ### Comparisons | `a` | `b` | [`a == b`](../expressions/operator-expr#comparison-operators) | | --- | --- | --- | | `true` | `true` | `true` | | `true` | `false` | `false` | | `false` | `true` | `false` | | `false` | `false` | `true` | | `a` | `b` | [`a > b`](../expressions/operator-expr#comparison-operators) | | --- | --- | --- | | `true` | `true` | `false` | | `true` | `false` | `true` | | `false` | `true` | `false` | | `false` | `false` | `false` | * `a != b` is the same as `!(a == b)` * `a >= b` is the same as `a == b | a > b` * `a < b` is the same as `!(a >= b)` * `a <= b` is the same as `a == b | a < b` rust Struct types Struct types ============ A `struct` *type* is a heterogeneous product of other types, called the *fields* of the type.[1](#structtype) New instances of a `struct` can be constructed with a [struct expression](../expressions/struct-expr). The memory layout of a `struct` is undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with the [`repr` attribute](../type-layout#representations). In either case, fields may be given in any order in a corresponding struct *expression*; the resulting `struct` value will always have the same memory layout. The fields of a `struct` may be qualified by [visibility modifiers](../visibility-and-privacy), to allow access to data in a struct outside a module. A *tuple struct* type is just like a struct type, except that the fields are anonymous. A *unit-like struct* type is like a struct type, except that it has no fields. The one value constructed by the associated [struct expression](../expressions/struct-expr) is the only value that inhabits such a type. 1 `struct` types are analogous to `struct` types in C, the *record* types of the ML family, or the *struct* types of the Lisp family. rust Name resolution Name resolution =============== > **Note**: This is a placeholder for future expansion. > > rust Namespaces Namespaces ========== A *namespace* is a logical grouping of declared [names](../names). Names are segregated into separate namespaces based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace. Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities. There are several different namespaces that each contain different kinds of entities. The usage of a name will look for the declaration of that name in different namespaces, based on the context, as described in the [name resolution](name-resolution) chapter. The following is a list of namespaces, with their corresponding entities: * Type Namespace + [Module declarations](../items/modules) + [External crate declarations](../items/extern-crates) + [External crate prelude](preludes#extern-prelude) items + [Struct](../items/structs), [union](../items/unions), [enum](../items/enumerations), enum variant declarations + [Trait item declarations](../items/traits) + [Type aliases](../items/type-aliases) + [Associated type declarations](../items/associated-items#associated-types) + Built-in types: [boolean](../types/boolean), [numeric](../types/numeric), and [textual](../types/textual) + [Generic type parameters](../items/generics) + [`Self` type](../paths#self-1) + [Tool attribute modules](../attributes#tool-attributes) * Value Namespace + [Function declarations](../items/functions) + [Constant item declarations](../items/constant-items) + [Static item declarations](../items/static-items) + [Struct constructors](../items/structs) + [Enum variant constructors](../items/enumerations) + [`Self` constructors](../paths#self-1) + [Generic const parameters](../items/generics#const-generics) + [Associated const declarations](../items/associated-items#associated-constants) + [Associated function declarations](../items/associated-items#associated-functions-and-methods) + Local bindings — [`let`](../statements#let-statements), [`if let`](../expressions/if-expr#if-let-expressions), [`while let`](../expressions/loop-expr#predicate-pattern-loops), [`for`](../expressions/loop-expr#iterator-loops), [`match`](../expressions/match-expr) arms, [function parameters](../items/functions#function-parameters), [closure parameters](../expressions/closure-expr) + Captured [closure](../expressions/closure-expr) variables * Macro Namespace + [`macro_rules` declarations](../macros-by-example) + [Built-in attributes](../attributes#built-in-attributes-index) + [Tool attributes](../attributes#tool-attributes) + [Function-like procedural macros](../procedural-macros#function-like-procedural-macros) + [Derive macros](../procedural-macros#derive-macros) + [Derive macro helpers](../procedural-macros#derive-macro-helper-attributes) + [Attribute macros](../procedural-macros#attribute-macros) * Lifetime Namespace + [Generic lifetime parameters](../items/generics) * Label Namespace + [Loop labels](../expressions/loop-expr#loop-labels) An example of how overlapping names in different namespaces can be used unambiguously: ``` #![allow(unused)] fn main() { // Foo introduces a type in the type namespace and a constructor in the value // namespace. struct Foo(u32); // The `Foo` macro is declared in the macro namespace. macro_rules! Foo { () => {}; } // `Foo` in the `f` parameter type refers to `Foo` in the type namespace. // `'Foo` introduces a new lifetime in the lifetime namespace. fn example<'Foo>(f: Foo) { // `Foo` refers to the `Foo` constructor in the value namespace. let ctor = Foo; // `Foo` refers to the `Foo` macro in the macro namespace. Foo!{} // `'Foo` introduces a label in the label namespace. 'Foo: loop { // `'Foo` refers to the `'Foo` lifetime parameter, and `Foo` // refers to the type namespace. let x: &'Foo Foo; // `'Foo` refers to the label. break 'Foo; } } } ``` Named entities without a namespace ---------------------------------- The following entities have explicit names, but the names are not a part of any specific namespace. ### Fields Even though struct, enum, and union fields are named, the named fields do not live in an explicit namespace. They can only be accessed via a [field expression](../expressions/field-expr), which only inspects the field names of the specific type being accessed. ### Use declarations A [use declaration](../items/use-declarations) has named aliases that it imports into scope, but the `use` item itself does not belong to a specific namespace. Instead, it can introduce aliases into multiple namespaces, depending on the item kind being imported. Sub-namespaces -------------- The macro namespace is split into two sub-namespaces: one for [bang-style macros](../macros) and one for [attributes](../attributes). When an attribute is resolved, any bang-style macros in scope will be ignored. And conversely resolving a bang-style macro will ignore attribute macros in scope. This prevents one style from shadowing another. For example, the [`cfg` attribute](../conditional-compilation#the-cfg-attribute) and the [`cfg` macro](../conditional-compilation#the-cfg-macro) are two different entities with the same name in the macro namespace, but they can still be used in their respective context. It is still an error for a [`use` import](../items/use-declarations) to shadow another macro, regardless of their sub-namespaces.
programming_docs
rust Preludes Preludes ======== A *prelude* is a collection of names that are automatically brought into scope of every module in a crate. These prelude names are not part of the module itself: they are implicitly queried during [name resolution](name-resolution). For example, even though something like [`Box`](../../std/boxed/struct.box) is in scope in every module, you cannot refer to it as `self::Box` because it is not a member of the current module. There are several different preludes: * [Standard library prelude](#standard-library-prelude) * [Extern prelude](#extern-prelude) * [Language prelude](#language-prelude) * [`macro_use` prelude](#macro_use-prelude) * [Tool prelude](#tool-prelude) Standard library prelude ------------------------ Each crate has a standard library prelude, which consists of the names from a single standard library module. The module used depends on the crate's edition, and on whether the [`no_std` attribute](#the-no_std-attribute) is applied to the crate: | Edition | `no_std` not applied | `no_std` applied | | --- | --- | --- | | 2015 | [`std::prelude::rust_2015`](../../std/prelude/rust_2015/index) | [`core::prelude::rust_2015`](https://doc.rust-lang.org/core/prelude/rust_2015/index.html) | | 2018 | [`std::prelude::rust_2018`](../../std/prelude/rust_2018/index) | [`core::prelude::rust_2018`](https://doc.rust-lang.org/core/prelude/rust_2018/index.html) | | 2021 | [`std::prelude::rust_2021`](../../std/prelude/rust_2021/index) | [`core::prelude::rust_2021`](https://doc.rust-lang.org/core/prelude/rust_2021/index.html) | > **Note**: > > [`std::prelude::rust_2015`](../../std/prelude/rust_2015/index) and [`std::prelude::rust_2018`](../../std/prelude/rust_2018/index) have the same contents as [`std::prelude::v1`](../../std/prelude/v1/index). > > [`core::prelude::rust_2015`](https://doc.rust-lang.org/core/prelude/rust_2015/index.html) and [`core::prelude::rust_2018`](https://doc.rust-lang.org/core/prelude/rust_2018/index.html) have the same contents as [`core::prelude::v1`](https://doc.rust-lang.org/core/prelude/v1/index.html). > > Extern prelude -------------- External crates imported with [`extern crate`](../items/extern-crates) in the root module or provided to the compiler (as with the `--extern` flag with `rustc`) are added to the *extern prelude*. If imported with an alias such as `extern crate orig_name as new_name`, then the symbol `new_name` is instead added to the prelude. The [`core`](https://doc.rust-lang.org/core/index.html) crate is always added to the extern prelude. The [`std`](../../std/index) crate is added as long as the [`no_std` attribute](#the-no_std-attribute) is not specified in the crate root. > **Edition Differences**: In the 2015 edition, crates in the extern prelude cannot be referenced via [use declarations](../items/use-declarations), so it is generally standard practice to include `extern crate` declarations to bring them into scope. > > Beginning in the 2018 edition, [use declarations](../items/use-declarations) can reference crates in the extern prelude, so it is considered unidiomatic to use `extern crate`. > > > **Note**: Additional crates that ship with `rustc`, such as [`alloc`](https://doc.rust-lang.org/alloc/index.html), and [`test`](https://doc.rust-lang.org/test/index.html), are not automatically included with the `--extern` flag when using Cargo. They must be brought into scope with an `extern crate` declaration, even in the 2018 edition. > > > ``` > #![allow(unused)] > fn main() { > extern crate alloc; > use alloc::rc::Rc; > } > > ``` > Cargo does bring in `proc_macro` to the extern prelude for proc-macro crates only. > > ### The `no_std` attribute By default, the standard library is automatically included in the crate root module. The [`std`](../../std/index) crate is added to the root, along with an implicit [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) pulling in all macros exported from `std` into the [`macro_use` prelude](#macro_use-prelude). Both [`core`](https://doc.rust-lang.org/core/index.html) and [`std`](../../std/index) are added to the [extern prelude](#extern-prelude). The *`no_std` [attribute](../attributes)* may be applied at the crate level to prevent the [`std`](../../std/index) crate from being automatically added into scope. It does three things: * Prevents `std` from being added to the [extern prelude](#extern-prelude). * Affects which module is used to make up the [standard library prelude](#standard-library-prelude) (as described above). * Injects the [`core`](https://doc.rust-lang.org/core/index.html) crate into the crate root instead of [`std`](../../std/index), and pulls in all macros exported from `core` in the [`macro_use` prelude](#macro_use-prelude). > **Note**: Using the core prelude over the standard prelude is useful when either the crate is targeting a platform that does not support the standard library or is purposefully not using the capabilities of the standard library. Those capabilities are mainly dynamic memory allocation (e.g. `Box` and `Vec`) and file and network capabilities (e.g. `std::fs` and `std::io`). > > Warning: Using `no_std` does not prevent the standard library from being linked in. It is still valid to put `extern crate std;` into the crate and dependencies can also link it in. Language prelude ---------------- The language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope. It includes the following: * [Type namespace](namespaces) + [Boolean type](../types/boolean) — `bool` + [Textual types](../types/textual) — `char` and `str` + [Integer types](../types/numeric#integer-types) — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128` + [Machine-dependent integer types](../types/numeric#machine-dependent-integer-types) — `usize` and `isize` + [floating-point types](../types/numeric#floating-point-types) — `f32` and `f64` * [Macro namespace](namespaces) + [Built-in attributes](../attributes#built-in-attributes-index) `macro_use` prelude -------------------- The `macro_use` prelude includes macros from external crates that were imported by the [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) applied to an [`extern crate`](../items/extern-crates). Tool prelude ------------ The tool prelude includes tool names for external tools in the [type namespace](namespaces). See the [tool attributes](../attributes#tool-attributes) section for more details. The `no_implicit_prelude` attribute ----------------------------------- The *`no_implicit_prelude` [attribute](../attributes)* may be applied at the crate level or on a module to indicate that it should not automatically bring the [standard library prelude](#standard-library-prelude), [extern prelude](#extern-prelude), or [tool prelude](#tool-prelude) into scope for that module or any of its descendants. This attribute does not affect the [language prelude](#language-prelude). > **Edition Differences**: In the 2015 edition, the `no_implicit_prelude` attribute does not affect the [`macro_use` prelude](#macro_use-prelude), and all macros exported from the standard library are still included in the `macro_use` prelude. Starting in the 2018 edition, it will remove the `macro_use` prelude. > > rust Type system attributes Type system attributes ====================== The following [attributes](../attributes) are used for changing how a type can be used. The `non_exhaustive` attribute ------------------------------ The *`non_exhaustive` attribute* indicates that a type or variant may have more fields or variants added in the future. It can be applied to [`struct`s](../items/structs), [`enum`s](../items/enumerations), and `enum` variants. The `non_exhaustive` attribute uses the [*MetaWord*](../attributes#meta-item-attribute-syntax) syntax and thus does not take any inputs. Within the defining crate, `non_exhaustive` has no effect. ``` #![allow(unused)] fn main() { #[non_exhaustive] pub struct Config { pub window_width: u16, pub window_height: u16, } #[non_exhaustive] pub enum Error { Message(String), Other, } pub enum Message { #[non_exhaustive] Send { from: u32, to: u32, contents: String }, #[non_exhaustive] Reaction(u32), #[non_exhaustive] Quit, } // Non-exhaustive structs can be constructed as normal within the defining crate. let config = Config { window_width: 640, window_height: 480 }; // Non-exhaustive structs can be matched on exhaustively within the defining crate. if let Config { window_width, window_height } = config { // ... } let error = Error::Other; let message = Message::Reaction(3); // Non-exhaustive enums can be matched on exhaustively within the defining crate. match error { Error::Message(ref s) => { }, Error::Other => { }, } match message { // Non-exhaustive variants can be matched on exhaustively within the defining crate. Message::Send { from, to, contents } => { }, Message::Reaction(id) => { }, Message::Quit => { }, } } ``` Outside of the defining crate, types annotated with `non_exhaustive` have limitations that preserve backwards compatibility when new fields or variants are added. Non-exhaustive types cannot be constructed outside of the defining crate: * Non-exhaustive variants ([`struct`](../items/structs) or [`enum` variant](../items/enumerations)) cannot be constructed with a [*StructExpression*](../expressions/struct-expr) (including with [functional update syntax](../expressions/struct-expr#functional-update-syntax)). * [`enum`](../items/enumerations) instances can be constructed. ``` // `Config`, `Error`, and `Message` are types defined in an upstream crate that have been // annotated as `#[non_exhaustive]`. use upstream::{Config, Error, Message}; // Cannot construct an instance of `Config`, if new fields were added in // a new version of `upstream` then this would fail to compile, so it is // disallowed. let config = Config { window_width: 640, window_height: 480 }; // Can construct an instance of `Error`, new variants being introduced would // not result in this failing to compile. let error = Error::Message("foo".to_string()); // Cannot construct an instance of `Message::Send` or `Message::Reaction`, // if new fields were added in a new version of `upstream` then this would // fail to compile, so it is disallowed. let message = Message::Send { from: 0, to: 1, contents: "foo".to_string(), }; let message = Message::Reaction(0); // Cannot construct an instance of `Message::Quit`, if this were converted to // a tuple-variant `upstream` then this would fail to compile. let message = Message::Quit; ``` There are limitations when matching on non-exhaustive types outside of the defining crate: * When pattern matching on a non-exhaustive variant ([`struct`](../items/structs) or [`enum` variant](../items/enumerations)), a [*StructPattern*](../patterns#struct-patterns) must be used which must include a `..`. Tuple variant constructor visibility is lowered to `min($vis, pub(crate))`. * When pattern matching on a non-exhaustive [`enum`](../items/enumerations), matching on a variant does not contribute towards the exhaustiveness of the arms. ``` // `Config`, `Error`, and `Message` are types defined in an upstream crate that have been // annotated as `#[non_exhaustive]`. use upstream::{Config, Error, Message}; // Cannot match on a non-exhaustive enum without including a wildcard arm. match error { Error::Message(ref s) => { }, Error::Other => { }, // would compile with: `_ => {},` } // Cannot match on a non-exhaustive struct without a wildcard. if let Ok(Config { window_width, window_height }) = config { // would compile with: `..` } match message { // Cannot match on a non-exhaustive struct enum variant without including a wildcard. Message::Send { from, to, contents } => { }, // Cannot match on a non-exhaustive tuple or unit enum variant. Message::Reaction(type) => { }, Message::Quit => { }, } ``` It's also not allowed to cast non-exhaustive types from foreign crates. ``` use othercrate::NonExhaustiveEnum; // Cannot cast a non-exhaustive enum outside of its defining crate. let _ = NonExhaustiveEnum::default() as u8; ``` Non-exhaustive types are always considered inhabited in downstream crates. rust Code generation attributes Code generation attributes ========================== The following [attributes](../attributes) are used for controlling code generation. Optimization hints ------------------ The `cold` and `inline` [attributes](../attributes) give suggestions to generate code in a way that may be faster than what it would do without the hint. The attributes are only hints, and may be ignored. Both attributes can be used on [functions](../items/functions). When applied to a function in a [trait](../items/traits), they apply only to that function when used as a default function for a trait implementation and not to all trait implementations. The attributes have no effect on a trait function without a body. ### The `inline` attribute The *`inline` [attribute](../attributes)* suggests that a copy of the attributed function should be placed in the caller, rather than generating code to call the function where it is defined. > ***Note***: The `rustc` compiler automatically inlines functions based on internal heuristics. Incorrectly inlining functions can make the program slower, so this attribute should be used with care. > > There are three ways to use the inline attribute: * `#[inline]` *suggests* performing an inline expansion. * `#[inline(always)]` *suggests* that an inline expansion should always be performed. * `#[inline(never)]` *suggests* that an inline expansion should never be performed. > ***Note***: `#[inline]` in every form is a hint, with no *requirements* on the language to place a copy of the attributed function in the caller. > > ### The `cold` attribute The *`cold` [attribute](../attributes)* suggests that the attributed function is unlikely to be called. The `no_builtins` attribute --------------------------- The *`no_builtins` [attribute](../attributes)* may be applied at the crate level to disable optimizing certain code patterns to invocations of library functions that are assumed to exist. The `target_feature` attribute ------------------------------ The *`target_feature` [attribute](../attributes)* may be applied to a function to enable code generation of that function for specific platform architecture features. It uses the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with a single key of `enable` whose value is a string of comma-separated feature names to enable. ``` #![allow(unused)] fn main() { #[cfg(target_feature = "avx2")] #[target_feature(enable = "avx2")] unsafe fn foo_avx2() {} } ``` Each [target architecture](../conditional-compilation#target_arch) has a set of features that may be enabled. It is an error to specify a feature for a target architecture that the crate is not being compiled for. It is [undefined behavior](../behavior-considered-undefined) to call a function that is compiled with a feature that is not supported on the current platform the code is running on, *except* if the platform explicitly documents this to be safe. Functions marked with `target_feature` are not inlined into a context that does not support the given features. The `#[inline(always)]` attribute may not be used with a `target_feature` attribute. ### Available features The following is a list of the available feature names. #### `x86` or `x86_64` Executing code with unsupported features is undefined behavior on this platform. Hence this platform requires that `#[target_feature]` is only applied to [`unsafe` functions](../unsafe-functions). | Feature | Implicitly Enables | Description | | --- | --- | --- | | `adx` | | [ADX](https://en.wikipedia.org/wiki/Intel_ADX) — Multi-Precision Add-Carry Instruction Extensions | | `aes` | `sse2` | [AES](https://en.wikipedia.org/wiki/AES_instruction_set) — Advanced Encryption Standard | | `avx` | `sse4.2` | [AVX](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) — Advanced Vector Extensions | | `avx2` | `avx` | [AVX2](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#AVX2) — Advanced Vector Extensions 2 | | `bmi1` | | [BMI1](https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets) — Bit Manipulation Instruction Sets | | `bmi2` | | [BMI2](https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets#BMI2) — Bit Manipulation Instruction Sets 2 | | `fma` | `avx` | [FMA3](https://en.wikipedia.org/wiki/FMA_instruction_set) — Three-operand fused multiply-add | | `fxsr` | | [`fxsave`](https://www.felixcloutier.com/x86/fxsave) and [`fxrstor`](https://www.felixcloutier.com/x86/fxrstor) — Save and restore x87 FPU, MMX Technology, and SSE State | | `lzcnt` | | [`lzcnt`](https://www.felixcloutier.com/x86/lzcnt) — Leading zeros count | | `pclmulqdq` | `sse2` | [`pclmulqdq`](https://www.felixcloutier.com/x86/pclmulqdq) — Packed carry-less multiplication quadword | | `popcnt` | | [`popcnt`](https://www.felixcloutier.com/x86/popcnt) — Count of bits set to 1 | | `rdrand` | | [`rdrand`](https://en.wikipedia.org/wiki/RdRand) — Read random number | | `rdseed` | | [`rdseed`](https://en.wikipedia.org/wiki/RdRand) — Read random seed | | `sha` | `sse2` | [SHA](https://en.wikipedia.org/wiki/Intel_SHA_extensions) — Secure Hash Algorithm | | `sse` | | [SSE](https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions) — Streaming SIMD Extensions | | `sse2` | `sse` | [SSE2](https://en.wikipedia.org/wiki/SSE2) — Streaming SIMD Extensions 2 | | `sse3` | `sse2` | [SSE3](https://en.wikipedia.org/wiki/SSE3) — Streaming SIMD Extensions 3 | | `sse4.1` | `ssse3` | [SSE4.1](https://en.wikipedia.org/wiki/SSE4#SSE4.1) — Streaming SIMD Extensions 4.1 | | `sse4.2` | `sse4.1` | [SSE4.2](https://en.wikipedia.org/wiki/SSE4#SSE4.2) — Streaming SIMD Extensions 4.2 | | `ssse3` | `sse3` | [SSSE3](https://en.wikipedia.org/wiki/SSSE3) — Supplemental Streaming SIMD Extensions 3 | | `xsave` | | [`xsave`](https://www.felixcloutier.com/x86/xsave) — Save processor extended states | | `xsavec` | | [`xsavec`](https://www.felixcloutier.com/x86/xsavec) — Save processor extended states with compaction | | `xsaveopt` | | [`xsaveopt`](https://www.felixcloutier.com/x86/xsaveopt) — Save processor extended states optimized | | `xsaves` | | [`xsaves`](https://www.felixcloutier.com/x86/xsaves) — Save processor extended states supervisor | #### `aarch64` This platform requires that `#[target_feature]` is only applied to [`unsafe` functions](../unsafe-functions). Further documentation on these features can be found in the [ARM Architecture Reference Manual](https://developer.arm.com/documentation/ddi0487/latest), or elsewhere on [developer.arm.com](https://developer.arm.com). > ***Note***: The following pairs of features should both be marked as enabled or disabled together if used: > > * `paca` and `pacg`, which LLVM currently implements as one feature. > > | Feature | Implicitly Enables | Feature Name | | --- | --- | --- | | `aes` | `neon` | FEAT\_AES - Advanced SIMD AES instructions | | `bf16` | | FEAT\_BF16 - BFloat16 instructions | | `bti` | | FEAT\_BTI - Branch Target Identification | | `crc` | | FEAT\_CRC - CRC32 checksum instructions | | `dit` | | FEAT\_DIT - Data Independent Timing instructions | | `dotprod` | | FEAT\_DotProd - Advanced SIMD Int8 dot product instructions | | `dpb` | | FEAT\_DPB - Data cache clean to point of persistence | | `dpb2` | | FEAT\_DPB2 - Data cache clean to point of deep persistence | | `f32mm` | `sve` | FEAT\_F32MM - SVE single-precision FP matrix multiply instruction | | `f64mm` | `sve` | FEAT\_F64MM - SVE double-precision FP matrix multiply instruction | | `fcma` | `neon` | FEAT\_FCMA - Floating point complex number support | | `fhm` | `fp16` | FEAT\_FHM - Half-precision FP FMLAL instructions | | `flagm` | | FEAT\_FlagM - Conditional flag manipulation | | `fp16` | `neon` | FEAT\_FP16 - Half-precision FP data processing | | `frintts` | | FEAT\_FRINTTS - Floating-point to int helper instructions | | `i8mm` | | FEAT\_I8MM - Int8 Matrix Multiplication | | `jsconv` | `neon` | FEAT\_JSCVT - JavaScript conversion instruction | | `lse` | | FEAT\_LSE - Large System Extension | | `lor` | | FEAT\_LOR - Limited Ordering Regions extension | | `mte` | | FEAT\_MTE - Memory Tagging Extension | | `neon` | | FEAT\_FP & FEAT\_AdvSIMD - Floating Point and Advanced SIMD extension | | `pan` | | FEAT\_PAN - Privileged Access-Never extension | | `paca` | | FEAT\_PAuth - Pointer Authentication (address authentication) | | `pacg` | | FEAT\_PAuth - Pointer Authentication (generic authentication) | | `pmuv3` | | FEAT\_PMUv3 - Performance Monitors extension (v3) | | `rand` | | FEAT\_RNG - Random Number Generator | | `ras` | | FEAT\_RAS - Reliability, Availability and Serviceability extension | | `rcpc` | | FEAT\_LRCPC - Release consistent Processor Consistent | | `rcpc2` | `rcpc` | FEAT\_LRCPC2 - RcPc with immediate offsets | | `rdm` | | FEAT\_RDM - Rounding Double Multiply accumulate | | `sb` | | FEAT\_SB - Speculation Barrier | | `sha2` | `neon` | FEAT\_SHA1 & FEAT\_SHA256 - Advanced SIMD SHA instructions | | `sha3` | `sha2` | FEAT\_SHA512 & FEAT\_SHA3 - Advanced SIMD SHA instructions | | `sm4` | `neon` | FEAT\_SM3 & FEAT\_SM4 - Advanced SIMD SM3/4 instructions | | `spe` | | FEAT\_SPE - Statistical Profiling Extension | | `ssbs` | | FEAT\_SSBS - Speculative Store Bypass Safe | | `sve` | `fp16` | FEAT\_SVE - Scalable Vector Extension | | `sve2` | `sve` | FEAT\_SVE2 - Scalable Vector Extension 2 | | `sve2-aes` | `sve2`, `aes` | FEAT\_SVE\_AES - SVE AES instructions | | `sve2-sm4` | `sve2`, `sm4` | FEAT\_SVE\_SM4 - SVE SM4 instructions | | `sve2-sha3` | `sve2`, `sha3` | FEAT\_SVE\_SHA3 - SVE SHA3 instructions | | `sve2-bitperm` | `sve2` | FEAT\_SVE\_BitPerm - SVE Bit Permute | | `tme` | | FEAT\_TME - Transactional Memory Extension | | `vh` | | FEAT\_VHE - Virtualization Host Extensions | #### `wasm32` or `wasm64` `#[target_feature]` may be used with both safe and [`unsafe` functions](../unsafe-functions) on Wasm platforms. It is impossible to cause undefined behavior via the `#[target_feature]` attribute because attempting to use instructions unsupported by the Wasm engine will fail at load time without the risk of being interpreted in a way different from what the compiler expected. | Feature | Description | | --- | --- | | `simd128` | [WebAssembly simd proposal](https://github.com/webassembly/simd) | ### Additional information See the [`target_feature` conditional compilation option](../conditional-compilation#target_feature) for selectively enabling or disabling compilation of code based on compile-time settings. Note that this option is not affected by the `target_feature` attribute, and is only driven by the features enabled for the entire crate. See the [`is_x86_feature_detected`](../../std/arch/macro.is_x86_feature_detected) or [`is_aarch64_feature_detected`](../../std/arch/macro.is_aarch64_feature_detected) macros in the standard library for runtime feature detection on these platforms. > Note: `rustc` has a default set of features enabled for each target and CPU. The CPU may be chosen with the [`-C target-cpu`](https://doc.rust-lang.org/rustc/codegen-options/index.html#target-cpu) flag. Individual features may be enabled or disabled for an entire crate with the [`-C target-feature`](https://doc.rust-lang.org/rustc/codegen-options/index.html#target-feature) flag. > > The `track_caller` attribute ---------------------------- The `track_caller` attribute may be applied to any function with [`"Rust"` ABI](../items/external-blocks#abi) with the exception of the entry point `fn main`. When applied to functions and methods in trait declarations, the attribute applies to all implementations. If the trait provides a default implementation with the attribute, then the attribute also applies to override implementations. When applied to a function in an `extern` block the attribute must also be applied to any linked implementations, otherwise undefined behavior results. When applied to a function which is made available to an `extern` block, the declaration in the `extern` block must also have the attribute, otherwise undefined behavior results. ### Behavior Applying the attribute to a function `f` allows code within `f` to get a hint of the [`Location`](https://doc.rust-lang.org/core/panic/struct.Location.html) of the "topmost" tracked call that led to `f`'s invocation. At the point of observation, an implementation behaves as if it walks up the stack from `f`'s frame to find the nearest frame of an *unattributed* function `outer`, and it returns the [`Location`](https://doc.rust-lang.org/core/panic/struct.Location.html) of the tracked call in `outer`. ``` #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } } ``` > Note: `core` provides [`core::panic::Location::caller`](https://doc.rust-lang.org/core/panic/struct.Location.html#method.caller) for observing caller locations. It wraps the [`core::intrinsics::caller_location`](https://doc.rust-lang.org/core/intrinsics/fn.caller_location.html) intrinsic implemented by `rustc`. > > > Note: because the resulting `Location` is a hint, an implementation may halt its walk up the stack early. See [Limitations](#limitations) for important caveats. > > #### Examples When `f` is called directly by `calls_f`, code in `f` observes its callsite within `calls_f`: ``` #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } fn calls_f() { f(); // <-- f() prints this location } } ``` When `f` is called by another attributed function `g` which is in turn called by `calls_g`, code in both `f` and `g` observes `g`'s callsite within `calls_g`: ``` #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } #[track_caller] fn g() { println!("{}", std::panic::Location::caller()); f(); } fn calls_g() { g(); // <-- g() prints this location twice, once itself and once from f() } } ``` When `g` is called by another attributed function `h` which is in turn called by `calls_h`, all code in `f`, `g`, and `h` observes `h`'s callsite within `calls_h`: ``` #![allow(unused)] fn main() { #[track_caller] fn f() { println!("{}", std::panic::Location::caller()); } #[track_caller] fn g() { println!("{}", std::panic::Location::caller()); f(); } #[track_caller] fn h() { println!("{}", std::panic::Location::caller()); g(); } fn calls_h() { h(); // <-- prints this location three times, once itself, once from g(), once from f() } } ``` And so on. ### Limitations This information is a hint and implementations are not required to preserve it. In particular, coercing a function with `#[track_caller]` to a function pointer creates a shim which appears to observers to have been called at the attributed function's definition site, losing actual caller information across virtual calls. A common example of this coercion is the creation of a trait object whose methods are attributed. > Note: The aforementioned shim for function pointers is necessary because `rustc` implements `track_caller` in a codegen context by appending an implicit parameter to the function ABI, but this would be unsound for an indirect call because the parameter is not a part of the function's type and a given function pointer type may or may not refer to a function with the attribute. The creation of a shim hides the implicit parameter from callers of the function pointer, preserving soundness. > >
programming_docs
rust Derive Derive ====== The *`derive` attribute* allows new [items](../items) to be automatically generated for data structures. It uses the [*MetaListPaths*](../attributes#meta-item-attribute-syntax) syntax to specify a list of traits to implement or paths to [derive macros](../procedural-macros#derive-macros) to process. For example, the following will create an [`impl` item](../items/implementations) for the [`PartialEq`](../../std/cmp/trait.partialeq) and [`Clone`](../../std/clone/trait.clone) traits for `Foo`, and the type parameter `T` will be given the `PartialEq` or `Clone` constraints for the appropriate `impl`: ``` #![allow(unused)] fn main() { #[derive(PartialEq, Clone)] struct Foo<T> { a: i32, b: T, } } ``` The generated `impl` for `PartialEq` is equivalent to ``` #![allow(unused)] fn main() { struct Foo<T> { a: i32, b: T } impl<T: PartialEq> PartialEq for Foo<T> { fn eq(&self, other: &Foo<T>) -> bool { self.a == other.a && self.b == other.b } fn ne(&self, other: &Foo<T>) -> bool { self.a != other.a || self.b != other.b } } } ``` You can implement `derive` for your own traits through [procedural macros](../procedural-macros#derive-macros). The `automatically_derived` attribute ------------------------------------- The *`automatically_derived` attribute* is automatically added to [implementations](../items/implementations) created by the `derive` attribute for built-in traits. It has no direct effect, but it may be used by tools and diagnostic lints to detect these automatically generated implementations. rust Diagnostic attributes Diagnostic attributes ===================== The following [attributes](../attributes) are used for controlling or generating diagnostic messages during compilation. Lint check attributes --------------------- A lint check names a potentially undesirable coding pattern, such as unreachable code or omitted documentation. The lint attributes `allow`, `warn`, `deny`, and `forbid` use the [*MetaListPaths*](../attributes#meta-item-attribute-syntax) syntax to specify a list of lint names to change the lint level for the entity to which the attribute applies. For any lint check `C`: * `allow(C)` overrides the check for `C` so that violations will go unreported, * `warn(C)` warns about violations of `C` but continues compilation. * `deny(C)` signals an error after encountering a violation of `C`, * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint level afterwards, > Note: The lint checks supported by `rustc` can be found via `rustc -W help`, along with their default settings and are documented in the [rustc book](https://doc.rust-lang.org/rustc/lints/index.html). > > ``` #![allow(unused)] fn main() { pub mod m1 { // Missing documentation is ignored here #[allow(missing_docs)] pub fn undocumented_one() -> i32 { 1 } // Missing documentation signals a warning here #[warn(missing_docs)] pub fn undocumented_too() -> i32 { 2 } // Missing documentation signals an error here #[deny(missing_docs)] pub fn undocumented_end() -> i32 { 3 } } } ``` Lint attributes can override the level specified from a previous attribute, as long as the level does not attempt to change a forbidden lint. Previous attributes are those from a higher level in the syntax tree, or from a previous attribute on the same entity as listed in left-to-right source order. This example shows how one can use `allow` and `warn` to toggle a particular check on and off: ``` #![allow(unused)] fn main() { #[warn(missing_docs)] pub mod m2{ #[allow(missing_docs)] pub mod nested { // Missing documentation is ignored here pub fn undocumented_one() -> i32 { 1 } // Missing documentation signals a warning here, // despite the allow above. #[warn(missing_docs)] pub fn undocumented_two() -> i32 { 2 } } // Missing documentation signals a warning here pub fn undocumented_too() -> i32 { 3 } } } ``` This example shows how one can use `forbid` to disallow uses of `allow` for that lint check: ``` #![allow(unused)] fn main() { #[forbid(missing_docs)] pub mod m3 { // Attempting to toggle warning signals an error here #[allow(missing_docs)] /// Returns 2. pub fn undocumented_too() -> i32 { 2 } } } ``` > Note: `rustc` allows setting lint levels on the [command-line](https://doc.rust-lang.org/rustc/lints/levels.html#via-compiler-flag), and also supports [setting caps](https://doc.rust-lang.org/rustc/lints/levels.html#capping-lints) on the lints that are reported. > > ### Lint groups Lints may be organized into named groups so that the level of related lints can be adjusted together. Using a named group is equivalent to listing out the lints within that group. ``` #![allow(unused)] fn main() { // This allows all lints in the "unused" group. #[allow(unused)] // This overrides the "unused_must_use" lint from the "unused" // group to deny. #[deny(unused_must_use)] fn example() { // This does not generate a warning because the "unused_variables" // lint is in the "unused" group. let x = 1; // This generates an error because the result is unused and // "unused_must_use" is marked as "deny". std::fs::remove_file("some_file"); // ERROR: unused `Result` that must be used } } ``` There is a special group named "warnings" which includes all lints at the "warn" level. The "warnings" group ignores attribute order and applies to all lints that would otherwise warn within the entity. ``` #![allow(unused)] fn main() { unsafe fn an_unsafe_fn() {} // The order of these two attributes does not matter. #[deny(warnings)] // The unsafe_code lint is normally "allow" by default. #[warn(unsafe_code)] fn example_err() { // This is an error because the `unsafe_code` warning has // been lifted to "deny". unsafe { an_unsafe_fn() } // ERROR: usage of `unsafe` block } } ``` ### Tool lint attributes Tool lints allows using scoped lints, to `allow`, `warn`, `deny` or `forbid` lints of certain tools. Tool lints only get checked when the associated tool is active. If a lint attribute, such as `allow`, references a nonexistent tool lint, the compiler will not warn about the nonexistent lint until you use the tool. Otherwise, they work just like regular lint attributes: ``` // set the entire `pedantic` clippy lint group to warn #![warn(clippy::pedantic)] // silence warnings from the `filter_map` clippy lint #![allow(clippy::filter_map)] fn main() { // ... } // silence the `cmp_nan` clippy lint just for this function #[allow(clippy::cmp_nan)] fn foo() { // ... } ``` > Note: `rustc` currently recognizes the tool lints for "[clippy](https://github.com/rust-lang/rust-clippy)" and "[rustdoc](https://doc.rust-lang.org/rustdoc/lints.html)". > > The `deprecated` attribute -------------------------- The *`deprecated` attribute* marks an item as deprecated. `rustc` will issue warnings on usage of `#[deprecated]` items. `rustdoc` will show item deprecation, including the `since` version and `note`, if available. The `deprecated` attribute has several forms: * `deprecated` — Issues a generic message. * `deprecated = "message"` — Includes the given string in the deprecation message. * [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with two optional fields: + `since` — Specifies a version number when the item was deprecated. `rustc` does not currently interpret the string, but external tools like [Clippy](https://github.com/rust-lang/rust-clippy) may check the validity of the value. + `note` — Specifies a string that should be included in the deprecation message. This is typically used to provide an explanation about the deprecation and preferred alternatives. The `deprecated` attribute may be applied to any [item](../items), [trait item](../items/traits), [enum variant](../items/enumerations), [struct field](../items/structs), [external block item](../items/external-blocks), or [macro definition](../macros-by-example). It cannot be applied to [trait implementation items](../items/implementations#trait-implementations). When applied to an item containing other items, such as a [module](../items/modules) or [implementation](../items/implementations), all child items inherit the deprecation attribute. Here is an example: ``` #![allow(unused)] fn main() { #[deprecated(since = "5.2", note = "foo was rarely used. Users should instead use bar")] pub fn foo() {} pub fn bar() {} } ``` The [RFC](https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md) contains motivations and more details. The `must_use` attribute ------------------------ The *`must_use` attribute* is used to issue a diagnostic warning when a value is not "used". It can be applied to user-defined composite types ([`struct`s](../items/structs), [`enum`s](../items/enumerations), and [`union`s](../items/unions)), [functions](../items/functions), and [traits](../items/traits). The `must_use` attribute may include a message by using the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax such as `#[must_use = "example message"]`. The message will be given alongside the warning. When used on user-defined composite types, if the [expression](../expressions) of an [expression statement](../statements#expression-statements) has that type, then the `unused_must_use` lint is violated. ``` #![allow(unused)] fn main() { #[must_use] struct MustUse { // some fields } impl MustUse { fn new() -> MustUse { MustUse {} } } // Violates the `unused_must_use` lint. MustUse::new(); } ``` When used on a function, if the [expression](../expressions) of an [expression statement](../statements#expression-statements) is a [call expression](../expressions/call-expr) to that function, then the `unused_must_use` lint is violated. ``` #![allow(unused)] fn main() { #[must_use] fn five() -> i32 { 5i32 } // Violates the unused_must_use lint. five(); } ``` When used on a [trait declaration](../items/traits), a [call expression](../expressions/call-expr) of an [expression statement](../statements#expression-statements) to a function that returns an [impl trait](../types/impl-trait) or a [dyn trait](../types/trait-object) of that trait violates the `unused_must_use` lint. ``` #![allow(unused)] fn main() { #[must_use] trait Critical {} impl Critical for i32 {} fn get_critical() -> impl Critical { 4i32 } // Violates the `unused_must_use` lint. get_critical(); } ``` When used on a function in a trait declaration, then the behavior also applies when the call expression is a function from an implementation of the trait. ``` #![allow(unused)] fn main() { trait Trait { #[must_use] fn use_me(&self) -> i32; } impl Trait for i32 { fn use_me(&self) -> i32 { 0i32 } } // Violates the `unused_must_use` lint. 5i32.use_me(); } ``` When used on a function in a trait implementation, the attribute does nothing. > Note: Trivial no-op expressions containing the value will not violate the lint. Examples include wrapping the value in a type that does not implement [`Drop`](../special-types-and-traits#drop) and then not using that type and being the final expression of a [block expression](../expressions/block-expr) that is not used. > > > ``` > #![allow(unused)] > fn main() { > #[must_use] > fn five() -> i32 { 5i32 } > > // None of these violate the unused_must_use lint. > (five(),); > Some(five()); > { five() }; > if true { five() } else { 0i32 }; > match true { > _ => five() > }; > } > > ``` > > Note: It is idiomatic to use a [let statement](../statements#let-statements) with a pattern of `_` when a must-used value is purposely discarded. > > > ``` > #![allow(unused)] > fn main() { > #[must_use] > fn five() -> i32 { 5i32 } > > // Does not violate the unused_must_use lint. > let _ = five(); > } > > ``` > rust Limits Limits ====== The following [attributes](../attributes) affect compile-time limits. The `recursion_limit` attribute ------------------------------- The *`recursion_limit` attribute* may be applied at the [crate](../crates-and-source-files) level to set the maximum depth for potentially infinitely-recursive compile-time operations like macro expansion or auto-dereference. It uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify the recursion depth. > Note: The default in `rustc` is 128. > > ``` #![allow(unused)] #![recursion_limit = "4"] fn main() { macro_rules! a { () => { a!(1); }; (1) => { a!(2); }; (2) => { a!(3); }; (3) => { a!(4); }; (4) => { }; } // This fails to expand because it requires a recursion depth greater than 4. a!{} } ``` ``` #![allow(unused)] #![recursion_limit = "1"] fn main() { // This fails because it requires two recursive steps to auto-dereference. (|_: &u8| {})(&&&1); } ``` The `type_length_limit` attribute --------------------------------- The *`type_length_limit` attribute* limits the maximum number of type substitutions made when constructing a concrete type during monomorphization. It is applied at the [crate](../crates-and-source-files) level, and uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to set the limit based on the number of type substitutions. > Note: The default in `rustc` is 1048576. > > ``` #![allow(unused)] #![type_length_limit = "4"] fn main() { fn f<T>(x: T) {} // This fails to compile because monomorphizing to // `f::<((((i32,), i32), i32), i32)>` requires more than 4 type elements. f(((((1,), 2), 3), 4)); } ``` rust Testing attributes Testing attributes ================== The following [attributes](../attributes) are used for specifying functions for performing tests. Compiling a crate in "test" mode enables building the test functions along with a test harness for executing the tests. Enabling the test mode also enables the [`test` conditional compilation option](../conditional-compilation#test). The `test` attribute -------------------- The *`test` attribute* marks a function to be executed as a test. These functions are only compiled when in test mode. Test functions must be free, monomorphic functions that take no arguments, and the return type must implement the [`Termination`](../../std/process/trait.termination) trait, for example: * `()` * `Result<T, E> where T: Termination, E: Debug` * `!` > Note: The test mode is enabled by passing the `--test` argument to `rustc` or using `cargo test`. > > The test harness calls the returned value's [`report`](../../std/process/trait.termination#tymethod.report) method, and classifies the test as passed or failed depending on whether the resulting [`ExitCode`](../../std/process/struct.exitcode) represents successful termination. In particular: * Tests that return `()` pass as long as they terminate and do not panic. * Tests that return a `Result<(), E>` pass as long as they return `Ok(())`. * Tests that return `ExitCode::SUCCESS` pass, and tests that return `ExitCode::FAILURE` fail. * Tests that do not terminate neither pass nor fail. ``` #![allow(unused)] fn main() { use std::io; fn setup_the_thing() -> io::Result<i32> { Ok(1) } fn do_the_thing(s: &i32) -> io::Result<()> { Ok(()) } #[test] fn test_the_thing() -> io::Result<()> { let state = setup_the_thing()?; // expected to succeed do_the_thing(&state)?; // expected to succeed Ok(()) } } ``` The `ignore` attribute ---------------------- A function annotated with the `test` attribute can also be annotated with the `ignore` attribute. The *`ignore` attribute* tells the test harness to not execute that function as a test. It will still be compiled when in test mode. The `ignore` attribute may optionally be written with the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify a reason why the test is ignored. ``` #![allow(unused)] fn main() { #[test] #[ignore = "not yet implemented"] fn mytest() { // … } } ``` > **Note**: The `rustc` test harness supports the `--include-ignored` flag to force ignored tests to be run. > > The `should_panic` attribute ---------------------------- A function annotated with the `test` attribute that returns `()` can also be annotated with the `should_panic` attribute. The *`should_panic` attribute* makes the test only pass if it actually panics. The `should_panic` attribute may optionally take an input string that must appear within the panic message. If the string is not found in the message, then the test will fail. The string may be passed using the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax or the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with an `expected` field. ``` #![allow(unused)] fn main() { #[test] #[should_panic(expected = "values don't match")] fn mytest() { assert_eq!(1, 2, "values don't match"); } } ``` rust match expressions `match` expressions ==================== > **Syntax** > *MatchExpression* : > `match` *Scrutinee* `{` > [*InnerAttribute*](../attributes)\* > *MatchArms*? > `}` > > *Scrutinee* : > [*Expression*](../expressions)*except struct expression* > > *MatchArms* : > ( *MatchArm* `=>` ( [*ExpressionWithoutBlock*](../expressions) `,` | [*ExpressionWithBlock*](../expressions) `,`? ) )\* > *MatchArm* `=>` [*Expression*](../expressions) `,`? > > *MatchArm* : > [*OuterAttribute*](../attributes)\* [*Pattern*](../patterns) *MatchArmGuard*? > > *MatchArmGuard* : > `if` [*Expression*](../expressions) > > A *`match` expression* branches on a pattern. The exact form of matching that occurs depends on the [pattern](../patterns). A `match` expression has a *[scrutinee](../glossary#scrutinee) expression*, which is the value to compare to the patterns. The scrutinee expression and the patterns must have the same type. A `match` behaves differently depending on whether or not the scrutinee expression is a [place expression or value expression](../expressions#place-expressions-and-value-expressions). If the scrutinee expression is a [value expression](../expressions#place-expressions-and-value-expressions), it is first evaluated into a temporary location, and the resulting value is sequentially compared to the patterns in the arms until a match is found. The first arm with a matching pattern is chosen as the branch target of the `match`, any variables bound by the pattern are assigned to local variables in the arm's block, and control enters the block. When the scrutinee expression is a [place expression](../expressions#place-expressions-and-value-expressions), the match does not allocate a temporary location; however, a by-value binding may copy or move from the memory location. When possible, it is preferable to match on place expressions, as the lifetime of these matches inherits the lifetime of the place expression rather than being restricted to the inside of the match. An example of a `match` expression: ``` #![allow(unused)] fn main() { let x = 1; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } } ``` Variables bound within the pattern are scoped to the match guard and the arm's expression. The [binding mode](../patterns#binding-modes) (move, copy, or reference) depends on the pattern. Multiple match patterns may be joined with the `|` operator. Each pattern will be tested in left-to-right sequence until a successful match is found. ``` #![allow(unused)] fn main() { let x = 9; let message = match x { 0 | 1 => "not many", 2 ..= 9 => "a few", _ => "lots" }; assert_eq!(message, "a few"); // Demonstration of pattern match order. struct S(i32, i32); match S(1, 2) { S(z @ 1, _) | S(_, z @ 2) => assert_eq!(z, 1), _ => panic!(), } } ``` > Note: The `2..=9` is a [Range Pattern](../patterns#range-patterns), not a [Range Expression](range-expr). Thus, only those types of ranges supported by range patterns can be used in match arms. > > Every binding in each `|` separated pattern must appear in all of the patterns in the arm. Every binding of the same name must have the same type, and have the same binding mode. Match guards ------------ Match arms can accept *match guards* to further refine the criteria for matching a case. Pattern guards appear after the pattern and consist of a `bool`-typed expression following the `if` keyword. When the pattern matches successfully, the pattern guard expression is executed. If the expression evaluates to true, the pattern is successfully matched against. Otherwise, the next pattern, including other matches with the `|` operator in the same arm, is tested. ``` #![allow(unused)] fn main() { let maybe_digit = Some(0); fn process_digit(i: i32) { } fn process_other(i: i32) { } let message = match maybe_digit { Some(x) if x < 10 => process_digit(x), Some(x) => process_other(x), None => panic!(), }; } ``` > Note: Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example: > > > ``` > #![allow(unused)] > fn main() { > use std::cell::Cell; > let i : Cell<i32> = Cell::new(0); > match 1 { > 1 | _ if { i.set(i.get() + 1); false } => {} > _ => {} > } > assert_eq!(i.get(), 2); > } > > ``` > A pattern guard may refer to the variables bound within the pattern they follow. Before evaluating the guard, a shared reference is taken to the part of the scrutinee the variable matches on. While evaluating the guard, this shared reference is then used when accessing the variable. Only when the guard evaluates to true is the value moved, or copied, from the scrutinee into the variable. This allows shared borrows to be used inside guards without moving out of the scrutinee in case guard fails to match. Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented. Attributes on match arms ------------------------ Outer attributes are allowed on match arms. The only attributes that have meaning on match arms are [`cfg`](../conditional-compilation) and the [lint check attributes](../attributes/diagnostics#lint-check-attributes). [Inner attributes](../attributes) are allowed directly after the opening brace of the match expression in the same expression contexts as [attributes on block expressions](block-expr#attributes-on-block-expressions).
programming_docs
rust Tuple and tuple indexing expressions Tuple and tuple indexing expressions ==================================== Tuple expressions ----------------- > **Syntax** > *TupleExpression* : > `(` *TupleElements*? `)` > > *TupleElements* : > ( [*Expression*](../expressions) `,` )+ [*Expression*](../expressions)? > > A *tuple expression* constructs [tuple values](../types/tuple). The syntax for tuple expressions is a parenthesized, comma separated list of expressions, called the *tuple initializer operands*. 1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with a [parenthetical expression](grouped-expr). Tuple expressions are a [value expression](../expressions#place-expressions-and-value-expressions) that evaluate into a newly constructed value of a tuple type. The number of tuple initializer operands is the arity of the constructed tuple. Tuple expressions without any tuple initializer operands produce the unit tuple. For other tuple expressions, the first written tuple initializer operand initializes the field `0` and subsequent operands initializes the next highest field. For example, in the tuple expression `('a', 'b', 'c')`, `'a'` initializes the value of the field `0`, `'b'` field `1`, and `'c'` field `2`. Examples of tuple expressions and their types: | Expression | Type | | --- | --- | | `()` | `()` (unit) | | `(0.0, 4.5)` | `(f64, f64)` | | `("x".to_string(), )` | `(String, )` | | `("a", 4usize, true)` | `(&'static str, usize, bool)` | Tuple indexing expressions -------------------------- > **Syntax** > *TupleIndexingExpression* : > [*Expression*](../expressions) `.` [TUPLE\_INDEX](../tokens#tuple-index) > > A *tuple indexing expression* accesses fields of [tuples](../types/tuple) and [tuple structs](../types/struct). The syntax for a tuple index expression is an expression, called the *tuple operand*, then a `.`, then finally a tuple index. The syntax for the *tuple index* is a [decimal literal](../tokens#integer-literals) with no leading zeros, underscores, or suffix. For example `0` and `2` are valid tuple indices but not `01`, `0_`, nor `0i32`. The type of the tuple operand must be a [tuple type](../types/tuple) or a [tuple struct](../types/struct). The tuple index must be a name of a field of the type of the tuple operand. Evaluation of tuple index expressions has no side effects beyond evaluation of its tuple operand. As a [place expression](../expressions#place-expressions-and-value-expressions), it evaluates to the location of the field of the tuple operand with the same name as the tuple index. Examples of tuple indexing expressions: ``` #![allow(unused)] fn main() { // Indexing a tuple let pair = ("a string", 2); assert_eq!(pair.1, 2); // Indexing a tuple struct struct Point(f32, f32); let point = Point(1.0, 0.0); assert_eq!(point.0, 1.0); assert_eq!(point.1, 0.0); } ``` > **Note**: Unlike field access expressions, tuple index expressions can be the function operand of a [call expression](call-expr) as it cannot be confused with a method call since method names cannot be numbers. > > > **Note**: Although arrays and slices also have elements, you must use an [array or slice indexing expression](array-expr#array-and-slice-indexing-expressions) or a [slice pattern](../patterns#slice-patterns) to access their elements. > > rust Operator expressions Operator expressions ==================== > **Syntax** > *OperatorExpression* : > [*BorrowExpression*](#borrow-operators) > | [*DereferenceExpression*](#the-dereference-operator) > | [*ErrorPropagationExpression*](#the-question-mark-operator) > | [*NegationExpression*](#negation-operators) > | [*ArithmeticOrLogicalExpression*](#arithmetic-and-logical-binary-operators) > | [*ComparisonExpression*](#comparison-operators) > | [*LazyBooleanExpression*](#lazy-boolean-operators) > | [*TypeCastExpression*](#type-cast-expressions) > | [*AssignmentExpression*](#assignment-expressions) > | [*CompoundAssignmentExpression*](#compound-assignment-expressions) > > Operators are defined for built in types by the Rust language. Many of the following operators can also be overloaded using traits in `std::ops` or `std::cmp`. Overflow -------- Integer operators will panic when they overflow when compiled in debug mode. The `-C debug-assertions` and `-C overflow-checks` compiler flags can be used to control this more directly. The following things are considered to be overflow: * When `+`, `*` or binary `-` create a value greater than the maximum value, or less than the minimum value that can be stored. * Applying unary `-` to the most negative value of any signed integer type, unless the operand is a [literal expression](literal-expr#integer-literal-expressions) (or a literal expression standing alone inside one or more [grouped expressions](grouped-expr)). * Using `/` or `%`, where the left-hand argument is the smallest integer of a signed integer type and the right-hand argument is `-1`. These checks occur even when `-C overflow-checks` is disabled, for legacy reasons. * Using `<<` or `>>` where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative. > **Note**: The exception for literal expressions behind unary `-` means that forms such as `-128_i8` or `let j: i8 = -(128)` never cause a panic and have the expected value of -128. > > In these cases, the literal expression already has the most negative value for its type (for example, `128_i8` has the value -128) because integer literals are truncated to their type per the description in [Integer literal expressions](literal-expr#integer-literal-expressions). > > Negation of these most negative values leaves the value unchanged due to two's complement overflow conventions. > > In `rustc`, these most negative expressions are also ignored by the `overflowing_literals` lint check. > > Borrow operators ---------------- > **Syntax** > *BorrowExpression* : > (`&`|`&&`) [*Expression*](../expressions) > | (`&`|`&&`) `mut` [*Expression*](../expressions) > > The `&` (shared borrow) and `&mut` (mutable borrow) operators are unary prefix operators. When applied to a [place expression](../expressions#place-expressions-and-value-expressions), this expressions produces a reference (pointer) to the location that the value refers to. The memory location is also placed into a borrowed state for the duration of the reference. For a shared borrow (`&`), this implies that the place may not be mutated, but it may be read or shared again. For a mutable borrow (`&mut`), the place may not be accessed in any way until the borrow expires. `&mut` evaluates its operand in a mutable place expression context. If the `&` or `&mut` operators are applied to a [value expression](../expressions#place-expressions-and-value-expressions), then a [temporary value](../expressions#temporaries) is created. These operators cannot be overloaded. ``` #![allow(unused)] fn main() { { // a temporary with value 7 is created that lasts for this scope. let shared_reference = &7; } let mut array = [-2, 3, 9]; { // Mutably borrows `array` for this scope. // `array` may only be used through `mutable_reference`. let mutable_reference = &mut array; } } ``` Even though `&&` is a single token ([the lazy 'and' operator](#lazy-boolean-operators)), when used in the context of borrow expressions it works as two borrows: ``` #![allow(unused)] fn main() { // same meanings: let a = && 10; let a = & & 10; // same meanings: let a = &&&& mut 10; let a = && && mut 10; let a = & & & & mut 10; } ``` ### Raw address-of operators Related to the borrow operators are the *raw address-of operators*, which do not have first-class syntax, but are exposed via the macros [`ptr::addr_of!(expr)`](../../std/ptr/macro.addr_of) and [`ptr::addr_of_mut!(expr)`](../../std/ptr/macro.addr_of_mut). The expression `expr` is evaluated in place expression context. `ptr::addr_of!(expr)` then creates a const raw pointer of type `*const T` to the given place, and `ptr::addr_of_mut!(expr)` creates a mutable raw pointer of type `*mut T`. The raw address-of operators must be used instead of a borrow operator whenever the place expression could evaluate to a place that is not properly aligned or does not store a valid value as determined by its type, or whenever creating a reference would introduce incorrect aliasing assumptions. In those situations, using a borrow operator would cause [undefined behavior](../behavior-considered-undefined) by creating an invalid reference, but a raw pointer may still be constructed using an address-of operator. The following is an example of creating a raw pointer to an unaligned place through a `packed` struct: ``` #![allow(unused)] fn main() { use std::ptr; #[repr(packed)] struct Packed { f1: u8, f2: u16, } let packed = Packed { f1: 1, f2: 2 }; // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior! let raw_f2 = ptr::addr_of!(packed.f2); assert_eq!(unsafe { raw_f2.read_unaligned() }, 2); } ``` The following is an example of creating a raw pointer to a place that does not contain a valid value: ``` #![allow(unused)] fn main() { use std::{ptr, mem::MaybeUninit}; struct Demo { field: bool, } let mut uninit = MaybeUninit::<Demo>::uninit(); // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`, // and thus be Undefined Behavior! let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) }; unsafe { f1_ptr.write(true); } let init = unsafe { uninit.assume_init() }; } ``` The dereference operator ------------------------ > **Syntax** > *DereferenceExpression* : > `*` [*Expression*](../expressions) > > The `*` (dereference) operator is also a unary prefix operator. When applied to a [pointer](../types/pointer) it denotes the pointed-to location. If the expression is of type `&mut T` or `*mut T`, and is either a local variable, a (nested) field of a local variable or is a mutable [place expression](../expressions#place-expressions-and-value-expressions), then the resulting memory location can be assigned to. Dereferencing a raw pointer requires `unsafe`. On non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an [immutable place expression context](../expressions#mutability) and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context. ``` #![allow(unused)] fn main() { let x = &7; assert_eq!(*x, 7); let y = &mut 9; *y = 11; assert_eq!(*y, 11); } ``` The question mark operator -------------------------- > **Syntax** > *ErrorPropagationExpression* : > [*Expression*](../expressions) `?` > > The question mark operator (`?`) unwraps valid values or returns erroneous values, propagating them to the calling function. It is a unary postfix operator that can only be applied to the types `Result<T, E>` and `Option<T>`. When applied to values of the `Result<T, E>` type, it propagates errors. If the value is `Err(e)`, then it will return `Err(From::from(e))` from the enclosing function or closure. If applied to `Ok(x)`, then it will unwrap the value to evaluate to `x`. ``` #![allow(unused)] fn main() { use std::num::ParseIntError; fn try_to_parse() -> Result<i32, ParseIntError> { let x: i32 = "123".parse()?; // x = 123 let y: i32 = "24a".parse()?; // returns an Err() immediately Ok(x + y) // Doesn't run. } let res = try_to_parse(); println!("{:?}", res); assert!(res.is_err()) } ``` When applied to values of the `Option<T>` type, it propagates `None`s. If the value is `None`, then it will return `None`. If applied to `Some(x)`, then it will unwrap the value to evaluate to `x`. ``` #![allow(unused)] fn main() { fn try_option_some() -> Option<u8> { let val = Some(1)?; Some(val) } assert_eq!(try_option_some(), Some(1)); fn try_option_none() -> Option<u8> { let val = None?; Some(val) } assert_eq!(try_option_none(), None); } ``` `?` cannot be overloaded. Negation operators ------------------ > **Syntax** > *NegationExpression* : > `-` [*Expression*](../expressions) > | `!` [*Expression*](../expressions) > > These are the last two unary operators. This table summarizes the behavior of them on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in [value expression context](../expressions#place-expressions-and-value-expressions) so are moved or copied. | Symbol | Integer | `bool` | Floating Point | Overloading Trait | | --- | --- | --- | --- | --- | | `-` | Negation\* | | Negation | `std::ops::Neg` | | `!` | Bitwise NOT | [Logical NOT](../types/boolean#logical-not) | | `std::ops::Not` | \* Only for signed integer types. Here are some example of these operators ``` #![allow(unused)] fn main() { let x = 6; assert_eq!(-x, -6); assert_eq!(!x, -7); assert_eq!(true, !false); } ``` Arithmetic and Logical Binary Operators --------------------------------------- > **Syntax** > *ArithmeticOrLogicalExpression* : > [*Expression*](../expressions) `+` [*Expression*](../expressions) > | [*Expression*](../expressions) `-` [*Expression*](../expressions) > | [*Expression*](../expressions) `*` [*Expression*](../expressions) > | [*Expression*](../expressions) `/` [*Expression*](../expressions) > | [*Expression*](../expressions) `%` [*Expression*](../expressions) > | [*Expression*](../expressions) `&` [*Expression*](../expressions) > | [*Expression*](../expressions) `|` [*Expression*](../expressions) > | [*Expression*](../expressions) `^` [*Expression*](../expressions) > | [*Expression*](../expressions) `<<` [*Expression*](../expressions) > | [*Expression*](../expressions) `>>` [*Expression*](../expressions) > > Binary operators expressions are all written with infix notation. This table summarizes the behavior of arithmetic and logical binary operators on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in [value expression context](../expressions#place-expressions-and-value-expressions) so are moved or copied. | Symbol | Integer | `bool` | Floating Point | Overloading Trait | Overloading Compound Assignment Trait | | --- | --- | --- | --- | --- | --- | | `+` | Addition | | Addition | `std::ops::Add` | `std::ops::AddAssign` | | `-` | Subtraction | | Subtraction | `std::ops::Sub` | `std::ops::SubAssign` | | `*` | Multiplication | | Multiplication | `std::ops::Mul` | `std::ops::MulAssign` | | `/` | Division\* | | Division | `std::ops::Div` | `std::ops::DivAssign` | | `%` | Remainder\*\* | | Remainder | `std::ops::Rem` | `std::ops::RemAssign` | | `&` | Bitwise AND | [Logical AND](../types/boolean#logical-and) | | `std::ops::BitAnd` | `std::ops::BitAndAssign` | | `|` | Bitwise OR | [Logical OR](../types/boolean#logical-or) | | `std::ops::BitOr` | `std::ops::BitOrAssign` | | `^` | Bitwise XOR | [Logical XOR](../types/boolean#logical-xor) | | `std::ops::BitXor` | `std::ops::BitXorAssign` | | `<<` | Left Shift | | | `std::ops::Shl` | `std::ops::ShlAssign` | | `>>` | Right Shift\*\*\* | | | `std::ops::Shr` | `std::ops::ShrAssign` | \* Integer division rounds towards zero. \*\* Rust uses a remainder defined with [truncating division](https://en.wikipedia.org/wiki/Modulo_operation#Variants_of_the_definition). Given `remainder = dividend % divisor`, the remainder will have the same sign as the dividend. \*\*\* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types. Here are examples of these operators being used. ``` #![allow(unused)] fn main() { assert_eq!(3 + 6, 9); assert_eq!(5.5 - 1.25, 4.25); assert_eq!(-5 * 14, -70); assert_eq!(14 / 3, 4); assert_eq!(100 % 7, 2); assert_eq!(0b1010 & 0b1100, 0b1000); assert_eq!(0b1010 | 0b1100, 0b1110); assert_eq!(0b1010 ^ 0b1100, 0b110); assert_eq!(13 << 3, 104); assert_eq!(-10 >> 2, -3); } ``` Comparison Operators -------------------- > **Syntax** > *ComparisonExpression* : > [*Expression*](../expressions) `==` [*Expression*](../expressions) > | [*Expression*](../expressions) `!=` [*Expression*](../expressions) > | [*Expression*](../expressions) `>` [*Expression*](../expressions) > | [*Expression*](../expressions) `<` [*Expression*](../expressions) > | [*Expression*](../expressions) `>=` [*Expression*](../expressions) > | [*Expression*](../expressions) `<=` [*Expression*](../expressions) > > Comparison operators are also defined both for primitive types and many types in the standard library. Parentheses are required when chaining comparison operators. For example, the expression `a == b == c` is invalid and may be written as `(a == b) == c`. Unlike arithmetic and logical operators, the traits for overloading these operators are used more generally to show how a type may be compared and will likely be assumed to define actual comparisons by functions that use these traits as bounds. Many functions and macros in the standard library can then use that assumption (although not to ensure safety). Unlike the arithmetic and logical operators above, these operators implicitly take shared borrows of their operands, evaluating them in [place expression context](../expressions#place-expressions-and-value-expressions): ``` #![allow(unused)] fn main() { let a = 1; let b = 1; a == b; // is equivalent to ::std::cmp::PartialEq::eq(&a, &b); } ``` This means that the operands don't have to be moved out of. | Symbol | Meaning | Overloading method | | --- | --- | --- | | `==` | Equal | `std::cmp::PartialEq::eq` | | `!=` | Not equal | `std::cmp::PartialEq::ne` | | `>` | Greater than | `std::cmp::PartialOrd::gt` | | `<` | Less than | `std::cmp::PartialOrd::lt` | | `>=` | Greater than or equal to | `std::cmp::PartialOrd::ge` | | `<=` | Less than or equal to | `std::cmp::PartialOrd::le` | Here are examples of the comparison operators being used. ``` #![allow(unused)] fn main() { assert!(123 == 123); assert!(23 != -12); assert!(12.5 > 12.2); assert!([1, 2, 3] < [1, 3, 4]); assert!('A' <= 'B'); assert!("World" >= "Hello"); } ``` Lazy boolean operators ---------------------- > **Syntax** > *LazyBooleanExpression* : > [*Expression*](../expressions) `||` [*Expression*](../expressions) > | [*Expression*](../expressions) `&&` [*Expression*](../expressions) > > The operators `||` and `&&` may be applied to operands of boolean type. The `||` operator denotes logical 'or', and the `&&` operator denotes logical 'and'. They differ from `|` and `&` in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression. That is, `||` only evaluates its right-hand operand when the left-hand operand evaluates to `false`, and `&&` only when it evaluates to `true`. ``` #![allow(unused)] fn main() { let x = false || true; // true let y = false && panic!(); // false, doesn't evaluate `panic!()` } ``` Type cast expressions --------------------- > **Syntax** > *TypeCastExpression* : > [*Expression*](../expressions) `as` [*TypeNoBounds*](../types#type-expressions) > > A type cast expression is denoted with the binary operator `as`. Executing an `as` expression casts the value on the left-hand side to the type on the right-hand side. An example of an `as` expression: ``` #![allow(unused)] fn main() { fn sum(values: &[f64]) -> f64 { 0.0 } fn len(values: &[f64]) -> i32 { 0 } fn average(values: &[f64]) -> f64 { let sum: f64 = sum(values); let size: f64 = len(values) as f64; sum / size } } ``` `as` can be used to explicitly perform [coercions](../type-coercions), as well as the following additional casts. Any cast that does not fit either a coercion rule or an entry in the table is a compiler error. Here `*T` means either `*const T` or `*mut T`. `m` stands for optional `mut` in reference types and `mut` or `const` in pointer types. | Type of `e` | `U` | Cast performed by `e as U` | | --- | --- | --- | | Integer or Float type | Integer or Float type | Numeric cast | | C-like enum | Integer type | Enum cast | | `bool` or `char` | Integer type | Primitive to integer cast | | `u8` | `char` | `u8` to `char` cast | | `*T` | `*V` where `V: Sized` \* | Pointer to pointer cast | | `*T` where `T: Sized` | Integer type | Pointer to address cast | | Integer type | `*V` where `V: Sized` | Address to pointer cast | | `&m₁ T` | `*m₂ T` \*\* | Reference to pointer cast | | `&m₁ [T; n]` | `*m₂ T` \*\* | Array to pointer cast | | [Function item](../types/function-item) | [Function pointer](../types/function-pointer) | Function item to function pointer cast | | [Function item](../types/function-item) | `*V` where `V: Sized` | Function item to pointer cast | | [Function item](../types/function-item) | Integer | Function item to address cast | | [Function pointer](../types/function-pointer) | `*V` where `V: Sized` | Function pointer to pointer cast | | [Function pointer](../types/function-pointer) | Integer | Function pointer to address cast | | Closure \*\*\* | Function pointer | Closure to function pointer cast | \* or `T` and `V` are compatible unsized types, e.g., both slices, both the same trait object. \*\* only when `m₁` is `mut` or `m₂` is `const`. Casting `mut` reference to `const` pointer is allowed. \*\*\* only for closures that do not capture (close over) any local variables ### Semantics #### Numeric cast * Casting between two integers of the same size (e.g. i32 -> u32) is a no-op (Rust uses 2's complement for negative values of fixed integers) * Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate * Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will + zero-extend if the source is unsigned + sign-extend if the source is signed * Casting from a float to an integer will round the float towards zero + `NaN` will return `0` + Values larger than the maximum integer value, including `INFINITY`, will saturate to the maximum value of the integer type. + Values smaller than the minimum integer value, including `NEG_INFINITY`, will saturate to the minimum value of the integer type. * Casting from an integer to float will produce the closest possible float \* + if necessary, rounding is according to `roundTiesToEven` mode \*\*\* + on overflow, infinity (of the same sign as the input) is produced + note: with the current set of numeric types, overflow can only happen on `u128 as f32` for values greater or equal to `f32::MAX + (0.5 ULP)` * Casting from an f32 to an f64 is perfect and lossless * Casting from an f64 to an f32 will produce the closest possible f32 \*\* + if necessary, rounding is according to `roundTiesToEven` mode \*\*\* + on overflow, infinity (of the same sign as the input) is produced \* if integer-to-float casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected. \*\* if f64-to-f32 casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected. \*\*\* as defined in IEEE 754-2008 §4.3.1: pick the nearest floating point number, preferring the one with an even least significant digit if exactly halfway between two floating point numbers. #### Enum cast Casts an enum to its discriminant, then uses a numeric cast if needed. #### Primitive to integer cast * `false` casts to `0`, `true` casts to `1` * `char` casts to the value of the code point, then uses a numeric cast if needed. #### `u8` to `char` cast Casts to the `char` with the corresponding code point. #### Pointer to address cast Casting from a raw pointer to an integer produces the machine address of the referenced memory. If the integer type is smaller than the pointer type, the address may be truncated; using `usize` avoids this. #### Address to pointer cast Casting from an integer to a raw pointer interprets the integer as a memory address and produces a pointer referencing that memory. Warning: This interacts with the Rust memory model, which is still under development. A pointer obtained from this cast may suffer additional restrictions even if it is bitwise equal to a valid pointer. Dereferencing such a pointer may be [undefined behavior](../behavior-considered-undefined) if aliasing rules are not followed. A trivial example of sound address arithmetic: ``` #![allow(unused)] fn main() { let mut values: [i32; 2] = [1, 2]; let p1: *mut i32 = values.as_mut_ptr(); let first_address = p1 as usize; let second_address = first_address + 4; // 4 == size_of::<i32>() let p2 = second_address as *mut i32; unsafe { *p2 += 1; } assert_eq!(values[1], 3); } ``` Assignment expressions ---------------------- > **Syntax** > *AssignmentExpression* : > [*Expression*](../expressions) `=` [*Expression*](../expressions) > > An *assignment expression* moves a value into a specified place. An assignment expression consists of a [mutable](../expressions#mutability) [assignee expression](../expressions#place-expressions-and-value-expressions), the *assignee operand*, followed by an equals sign (`=`) and a [value expression](../expressions#place-expressions-and-value-expressions), the *assigned value operand*. In its most basic form, an assignee expression is a [place expression](../expressions#place-expressions-and-value-expressions), and we discuss this case first. The more general case of destructuring assignment is discussed below, but this case always decomposes into sequential assignments to place expressions, which may be considered the more fundamental case. ### Basic assignments Evaluating assignment expressions begins by evaluating its operands. The assigned value operand is evaluated first, followed by the assignee expression. For destructuring assignment, subexpressions of the assignee expression are evaluated left-to-right. > **Note**: This is different than other expressions in that the right operand is evaluated before the left one. > > It then has the effect of first [dropping](../destructors) the value at the assigned place, unless the place is an uninitialized local variable or an uninitialized field of a local variable. Next it either [copies or moves](../expressions#moved-and-copied-types) the assigned value to the assigned place. An assignment expression always produces [the unit value](../types/tuple). Example: ``` #![allow(unused)] fn main() { let mut x = 0; let y = 0; x = y; } ``` ### Destructuring assignments Destructuring assignment is a counterpart to destructuring pattern matches for variable declaration, permitting assignment to complex values, such as tuples or structs. For instance, we may swap two mutable variables: ``` #![allow(unused)] fn main() { let (mut a, mut b) = (0, 1); // Swap `a` and `b` using destructuring assignment. (b, a) = (a, b); } ``` In contrast to destructuring declarations using `let`, patterns may not appear on the left-hand side of an assignment due to syntactic ambiguities. Instead, a group of expressions that correspond to patterns are designated to be [assignee expressions](../expressions#place-expressions-and-value-expressions), and permitted on the left-hand side of an assignment. Assignee expressions are then desugared to pattern matches followed by sequential assignment. The desugared patterns must be irrefutable: in particular, this means that only slice patterns whose length is known at compile-time, and the trivial slice `[..]`, are permitted for destructuring assignment. The desugaring method is straightforward, and is illustrated best by example. ``` #![allow(unused)] fn main() { struct Struct { x: u32, y: u32 } let (mut a, mut b) = (0, 0); (a, b) = (3, 4); [a, b] = [3, 4]; Struct { x: a, y: b } = Struct { x: 3, y: 4}; // desugars to: { let (_a, _b) = (3, 4); a = _a; b = _b; } { let [_a, _b] = [3, 4]; a = _a; b = _b; } { let Struct { x: _a, y: _b } = Struct { x: 3, y: 4}; a = _a; b = _b; } } ``` Identifiers are not forbidden from being used multiple times in a single assignee expression. [Underscore expressions](underscore-expr) and empty [range expressions](range-expr) may be used to ignore certain values, without binding them. Note that default binding modes do not apply for the desugared expression. Compound assignment expressions ------------------------------- > **Syntax** > *CompoundAssignmentExpression* : > [*Expression*](../expressions) `+=` [*Expression*](../expressions) > | [*Expression*](../expressions) `-=` [*Expression*](../expressions) > | [*Expression*](../expressions) `*=` [*Expression*](../expressions) > | [*Expression*](../expressions) `/=` [*Expression*](../expressions) > | [*Expression*](../expressions) `%=` [*Expression*](../expressions) > | [*Expression*](../expressions) `&=` [*Expression*](../expressions) > | [*Expression*](../expressions) `|=` [*Expression*](../expressions) > | [*Expression*](../expressions) `^=` [*Expression*](../expressions) > | [*Expression*](../expressions) `<<=` [*Expression*](../expressions) > | [*Expression*](../expressions) `>>=` [*Expression*](../expressions) > > *Compound assignment expressions* combine arithmetic and logical binary operators with assignment expressions. For example: ``` #![allow(unused)] fn main() { let mut x = 5; x += 1; assert!(x == 6); } ``` The syntax of compound assignment is a [mutable](../expressions#mutability) [place expression](../expressions#place-expressions-and-value-expressions), the *assigned operand*, then one of the operators followed by an `=` as a single token (no whitespace), and then a [value expression](../expressions#place-expressions-and-value-expressions), the *modifying operand*. Unlike other place operands, the assigned place operand must be a place expression. Attempting to use a value expression is a compiler error rather than promoting it to a temporary. Evaluation of compound assignment expressions depends on the types of the operators. If both types are primitives, then the modifying operand will be evaluated first followed by the assigned operand. It will then set the value of the assigned operand's place to the value of performing the operation of the operator with the values of the assigned operand and modifying operand. > **Note**: This is different than other expressions in that the right operand is evaluated before the left one. > > Otherwise, this expression is syntactic sugar for calling the function of the overloading compound assigment trait of the operator (see the table earlier in this chapter). A mutable borrow of the assigned operand is automatically taken. For example, the following expression statements in `example` are equivalent: ``` #![allow(unused)] fn main() { struct Addable; use std::ops::AddAssign; impl AddAssign<Addable> for Addable { /* */ fn add_assign(&mut self, other: Addable) {} } fn example() { let (mut a1, a2) = (Addable, Addable); a1 += a2; let (mut a1, a2) = (Addable, Addable); AddAssign::add_assign(&mut a1, a2); } } ``` Like assignment expressions, compound assignment expressions always produce [the unit value](../types/tuple). Warning: The evaluation order of operands swaps depending on the types of the operands: with primitive types the right-hand side will get evaluated first, while with non-primitive types the left-hand side will get evaluated first. Try not to write code that depends on the evaluation order of operands in compound assignment expressions. See [this test](https://github.com/rust-lang/rust/blob/1.58.0/src/test/ui/expr/compound-assignment/eval-order.rs) for an example of using this dependency.
programming_docs
rust _ expressions `_` expressions ================ > **Syntax** > *UnderscoreExpression* : > `_` > > Underscore expressions, denoted with the symbol `_`, are used to signify a placeholder in a destructuring assignment. They may only appear in the left-hand side of an assignment. An example of an `_` expression: ``` #![allow(unused)] fn main() { let p = (1, 2); let mut a = 0; (_, a) = p; } ``` rust Struct expressions Struct expressions ================== > **Syntax** > *StructExpression* : > *StructExprStruct* > | *StructExprTuple* > | *StructExprUnit* > > *StructExprStruct* : > [*PathInExpression*](../paths#paths-in-expressions) `{` (*StructExprFields* | *StructBase*)? `}` > > *StructExprFields* : > *StructExprField* (`,` *StructExprField*)\* (`,` *StructBase* | `,`?) > > *StructExprField* : > [*OuterAttribute*](../attributes) \* > ( > [IDENTIFIER](../identifiers) > | ([IDENTIFIER](../identifiers) | [TUPLE\_INDEX](../tokens#tuple-index)) `:` [*Expression*](../expressions) > ) > > *StructBase* : > `..` [*Expression*](../expressions) > > *StructExprTuple* : > [*PathInExpression*](../paths#paths-in-expressions) `(` > ( [*Expression*](../expressions) (`,` [*Expression*](../expressions))\* `,`? )? > `)` > > *StructExprUnit* : [*PathInExpression*](../paths#paths-in-expressions) > > A *struct expression* creates a struct, enum, or union value. It consists of a path to a [struct](../items/structs), [enum variant](../items/enumerations), or [union](../items/unions) item followed by the values for the fields of the item. There are three forms of struct expressions: struct, tuple, and unit. The following are examples of struct expressions: ``` #![allow(unused)] fn main() { struct Point { x: f64, y: f64 } struct NothingInMe { } struct TuplePoint(f64, f64); mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } } struct Cookie; fn some_fn<T>(t: T) {} Point {x: 10.0, y: 20.0}; NothingInMe {}; TuplePoint(10.0, 20.0); TuplePoint { 0: 10.0, 1: 20.0 }; // Results in the same value as the above line let u = game::User {name: "Joe", age: 35, score: 100_000}; some_fn::<Cookie>(Cookie); } ``` Field struct expression ----------------------- A struct expression with fields enclosed in curly braces allows you to specify the value for each individual field in any order. The field name is separated from its value with a colon. A value of a [union](../items/unions) type can only be created using this syntax, and it must specify exactly one field. Functional update syntax ------------------------ A struct expression that constructs a value of a struct type can terminate with the syntax `..` followed by an expression to denote a functional update. The expression following `..` (the base) must have the same struct type as the new struct type being formed. The entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression. As with all struct expressions, all of the fields of the struct must be [visible](../visibility-and-privacy), even those not explicitly named. ``` #![allow(unused)] fn main() { struct Point3d { x: i32, y: i32, z: i32 } let mut base = Point3d {x: 1, y: 2, z: 3}; let y_ref = &mut base.y; Point3d {y: 0, z: 10, .. base}; // OK, only base.x is accessed drop(y_ref); } ``` Struct expressions with curly braces can't be used directly in a [loop](loop-expr) or [if](if-expr#if-expressions) expression's head, or in the [scrutinee](../glossary#scrutinee) of an [if let](if-expr#if-let-expressions) or [match](match-expr) expression. However, struct expressions can be in used in these situations if they are within another expression, for example inside [parentheses](grouped-expr). The field names can be decimal integer values to specify indices for constructing tuple structs. This can be used with base structs to fill out the remaining indices not specified: ``` #![allow(unused)] fn main() { struct Color(u8, u8, u8); let c1 = Color(0, 0, 0); // Typical way of creating a tuple struct. let c2 = Color{0: 255, 1: 127, 2: 0}; // Specifying fields by index. let c3 = Color{1: 0, ..c2}; // Fill out all other fields using a base struct. } ``` ### Struct field init shorthand When initializing a data structure (struct, enum, union) with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`. This allows a compact syntax with less duplication. For example: ``` #![allow(unused)] fn main() { struct Point3d { x: i32, y: i32, z: i32 } let x = 0; let y_value = 0; let z = 0; Point3d { x: x, y: y_value, z: z }; Point3d { x, y: y_value, z }; } ``` Tuple struct expression ----------------------- A struct expression with fields enclosed in parentheses constructs a tuple struct. Though it is listed here as a specific expression for completeness, it is equivalent to a [call expression](call-expr) to the tuple struct's constructor. For example: ``` #![allow(unused)] fn main() { struct Position(i32, i32, i32); Position(0, 0, 0); // Typical way of creating a tuple struct. let c = Position; // `c` is a function that takes 3 arguments. let pos = c(8, 6, 7); // Creates a `Position` value. } ``` Unit struct expression ---------------------- A unit struct expression is just the path to a unit struct item. This refers to the unit struct's implicit constant of its value. The unit struct value can also be constructed with a fieldless struct expression. For example: ``` #![allow(unused)] fn main() { struct Gamma; let a = Gamma; // Gamma unit value. let b = Gamma{}; // Exact same value as `a`. } ``` rust Grouped expressions Grouped expressions =================== > **Syntax** > *GroupedExpression* : > `(` [*Expression*](../expressions) `)` > > A *parenthesized expression* wraps a single expression, evaluating to that expression. The syntax for a parenthesized expression is a `(`, then an expression, called the *enclosed operand*, and then a `)`. Parenthesized expressions evaluate to the value of the enclosed operand. Unlike other expressions, parenthesized expressions are both [place expressions and value expressions](../expressions#place-expressions-and-value-expressions). When the enclosed operand is a place expression, it is a place expression and when the enclosed operand is a value expression, it is a value expression. Parentheses can be used to explicitly modify the precedence order of subexpressions within an expression. An example of a parenthesized expression: ``` #![allow(unused)] fn main() { let x: i32 = 2 + 3 * 4; let y: i32 = (2 + 3) * 4; assert_eq!(x, 14); assert_eq!(y, 20); } ``` An example of a necessary use of parentheses is when calling a function pointer that is a member of a struct: ``` #![allow(unused)] fn main() { struct A { f: fn() -> &'static str } impl A { fn f(&self) -> &'static str { "The method f" } } let a = A{f: || "The field f"}; assert_eq!( a.f (), "The method f"); assert_eq!((a.f)(), "The field f"); } ``` rust Array and array index expressions Array and array index expressions ================================= Array expressions ----------------- > **Syntax** > *ArrayExpression* : > `[` *ArrayElements*? `]` > > *ArrayElements* : > [*Expression*](../expressions) ( `,` [*Expression*](../expressions) )\* `,`? > | [*Expression*](../expressions) `;` [*Expression*](../expressions) > > *Array expressions* construct [arrays](../types/array). Array expressions come in two forms. The first form lists out every value in the array. The syntax for this form is a comma-separated list of expressions of uniform type enclosed in square brackets. This produces an array containing each of these values in the order they are written. The syntax for the second form is two expressions separated by a semicolon (`;`) enclosed in square brackets. The expression before the `;` is called the *repeat operand*. The expression after the `;` is called the *length operand*. It must have type `usize` and be a [constant expression](../const_eval#constant-expressions), such as a [literal](../tokens#literals) or a [constant item](../items/constant-items). An array expression of this form creates an array with the length of the value of the length operand with each element being a copy of the repeat operand. That is, `[a; b]` creates an array containing `b` copies of the value of `a`. If the length operand has a value greater than 1 then this requires that the type of the repeat operand is [`Copy`](../special-types-and-traits#copy) or that it must be a [path](path-expr) to a constant item. When the repeat operand is a constant item, it is evaluated the length operand's value times. If that value is `0`, then the constant item is not evaluated at all. For expressions that are not a constant item, it is evaluated exactly once, and then the result is copied the length operand's value times. ``` #![allow(unused)] fn main() { [1, 2, 3, 4]; ["a", "b", "c", "d"]; [0; 128]; // array with 128 zeros [0u8, 0u8, 0u8, 0u8,]; [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array const EMPTY: Vec<i32> = Vec::new(); [EMPTY; 2]; } ``` Array and slice indexing expressions ------------------------------------ > **Syntax** > *IndexExpression* : > [*Expression*](../expressions) `[` [*Expression*](../expressions) `]` > > [Array](../types/array) and [slice](../types/slice)-typed values can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them. When the array is mutable, the resulting [memory location](../expressions#place-expressions-and-value-expressions) can be assigned to. For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation. Indices are zero-based for arrays and slices. Array access is a [constant expression](../const_eval#constant-expressions), so bounds can be checked at compile-time with a constant index value. Otherwise a check will be performed at run-time that will put the thread in a *panicked state* if it fails. ``` #![allow(unused)] fn main() { // lint is deny by default. #![warn(unconditional_panic)] ([1, 2, 3, 4])[2]; // Evaluates to 3 let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; b[1][2]; // multidimensional array indexing let x = (["a", "b"])[10]; // warning: index out of bounds let n = 10; let y = (["a", "b"])[n]; // panics let arr = ["a", "b"]; arr[10]; // warning: index out of bounds } ``` The array index expression can be implemented for types other than arrays and slices by implementing the [Index](../../std/ops/trait.index) and [IndexMut](../../std/ops/trait.indexmut) traits. rust Method-call expressions Method-call expressions ======================= > **Syntax** > *MethodCallExpression* : > [*Expression*](../expressions) `.` [*PathExprSegment*](../paths#paths-in-expressions) `(`[*CallParams*](call-expr)? `)` > > A *method call* consists of an expression (the *receiver*) followed by a single dot, an expression path segment, and a parenthesized expression-list. Method calls are resolved to associated [methods](../items/associated-items#methods) on specific traits, either statically dispatching to a method if the exact `self`-type of the left-hand-side is known, or dynamically dispatching if the left-hand-side expression is an indirect [trait object](../types/trait-object). ``` #![allow(unused)] fn main() { let pi: Result<f32, _> = "3.14".parse(); let log_pi = pi.unwrap_or(1.0).log(2.72); assert!(1.14 < log_pi && log_pi < 1.15) } ``` When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method. This requires a more complex lookup process than for other functions, since there may be a number of possible methods to call. The following procedure is used: The first step is to build a list of candidate receiver types. Obtain these by repeatedly [dereferencing](operator-expr#the-dereference-operator) the receiver expression's type, adding each type encountered to the list, then finally attempting an [unsized coercion](../type-coercions#unsized-coercions) at the end, and adding the result type if that is successful. Then, for each candidate `T`, add `&T` and `&mut T` to the list immediately after `T`. For instance, if the receiver has type `Box<[i32;2]>`, then the candidate types will be `Box<[i32;2]>`, `&Box<[i32;2]>`, `&mut Box<[i32;2]>`, `[i32; 2]` (by dereferencing), `&[i32; 2]`, `&mut [i32; 2]`, `[i32]` (by unsized coercion), `&[i32]`, and finally `&mut [i32]`. Then, for each candidate type `T`, search for a [visible](../visibility-and-privacy) method with a receiver of that type in the following places: 1. `T`'s inherent methods (methods implemented directly on `T`). 2. Any of the methods provided by a [visible](../visibility-and-privacy) trait implemented by `T`. If `T` is a type parameter, methods provided by trait bounds on `T` are looked up first. Then all remaining methods in scope are looked up. > Note: the lookup is done for each type in order, which can occasionally lead to surprising results. The below code will print "In trait impl!", because `&self` methods are looked up first, the trait method is found before the struct's `&mut self` method is found. > > > ``` > struct Foo {} > > trait Bar { > fn bar(&self); > } > > impl Foo { > fn bar(&mut self) { > println!("In struct impl!") > } > } > > impl Bar for Foo { > fn bar(&self) { > println!("In trait impl!") > } > } > > fn main() { > let mut f = Foo{}; > f.bar(); > } > > ``` > If this results in multiple possible candidates, then it is an error, and the receiver must be [converted](call-expr#disambiguating-function-calls) to an appropriate receiver type to make the method call. This process does not take into account the mutability or lifetime of the receiver, or whether a method is `unsafe`. Once a method is looked up, if it can't be called for one (or more) of those reasons, the result is a compiler error. If a step is reached where there is more than one possible method, such as where generic methods or traits are considered the same, then it is a compiler error. These cases require a [disambiguating function call syntax](call-expr#disambiguating-function-calls) for method and function invocation. > **Edition Differences**: Before the 2021 edition, during the search for visible methods, if the candidate receiver type is an [array type](../types/array), methods provided by the standard library [`IntoIterator`](../../std/iter/trait.intoiterator) trait are ignored. > > The edition used for this purpose is determined by the token representing the method name. > > This special case may be removed in the future. > > ***Warning:*** For [trait objects](../types/trait-object), if there is an inherent method of the same name as a trait method, it will give a compiler error when trying to call the method in a method call expression. Instead, you can call the method using [disambiguating function call syntax](call-expr#disambiguating-function-calls), in which case it calls the trait method, not the inherent method. There is no way to call the inherent method. Just don't define inherent methods on trait objects with the same name as a trait method and you'll be fine. rust Literal expressions Literal expressions =================== > **Syntax** > *LiteralExpression* : > [CHAR\_LITERAL](../tokens#character-literals) > | [STRING\_LITERAL](../tokens#string-literals) > | [RAW\_STRING\_LITERAL](../tokens#raw-string-literals) > | [BYTE\_LITERAL](../tokens#byte-literals) > | [BYTE\_STRING\_LITERAL](../tokens#byte-string-literals) > | [RAW\_BYTE\_STRING\_LITERAL](../tokens#raw-byte-string-literals) > | [INTEGER\_LITERAL](../tokens#integer-literals)[1](#out-of-range) > | [FLOAT\_LITERAL](../tokens#floating-point-literals) > | `true` | `false` > > > 1 A value ≥ 2128 is not allowed. > > A *literal expression* is an expression consisting of a single token, rather than a sequence of tokens, that immediately and directly denotes the value it evaluates to, rather than referring to it by name or some other evaluation rule. A literal is a form of [constant expression](../const_eval#constant-expressions), so is evaluated (primarily) at compile time. Each of the lexical [literal](../tokens#literals) forms described earlier can make up a literal expression, as can the keywords `true` and `false`. ``` #![allow(unused)] fn main() { "hello"; // string type '5'; // character type 5; // integer type } ``` Character literal expressions ----------------------------- A character literal expression consists of a single [CHAR\_LITERAL](../tokens#character-literals) token. > **Note**: This section is incomplete. > > String literal expressions -------------------------- A string literal expression consists of a single [STRING\_LITERAL](../tokens#string-literals) or [RAW\_STRING\_LITERAL](../tokens#raw-string-literals) token. > **Note**: This section is incomplete. > > Byte literal expressions ------------------------ A byte literal expression consists of a single [BYTE\_LITERAL](../tokens#byte-literals) token. > **Note**: This section is incomplete. > > Byte string literal expressions ------------------------------- A string literal expression consists of a single [BYTE\_STRING\_LITERAL](../tokens#byte-string-literals) or [RAW\_BYTE\_STRING\_LITERAL](../tokens#raw-byte-string-literals) token. > **Note**: This section is incomplete. > > Integer literal expressions --------------------------- An integer literal expression consists of a single [INTEGER\_LITERAL](../tokens#integer-literals) token. If the token has a [suffix](../tokens#suffixes), the suffix will be the name of one of the [primitive integer types](../types/numeric): `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type. If the token has no suffix, the expression's type is determined by type inference: * If an integer type can be *uniquely* determined from the surrounding program context, the expression has that type. * If the program context under-constrains the type, it defaults to the signed 32-bit integer `i32`. * If the program context over-constrains the type, it is considered a static type error. Examples of integer literal expressions: ``` #![allow(unused)] fn main() { 123; // type i32 123i32; // type i32 123u32; // type u32 123_u32; // type u32 let a: u64 = 123; // type u64 0xff; // type i32 0xff_u8; // type u8 0o70; // type i32 0o70_i16; // type i16 0b1111_1111_1001_0000; // type i32 0b1111_1111_1001_0000i64; // type i64 0usize; // type usize } ``` The value of the expression is determined from the string representation of the token as follows: * An integer radix is chosen by inspecting the first two characters of the string, as follows: + `0b` indicates radix 2 + `0o` indicates radix 8 + `0x` indicates radix 16 + otherwise the radix is 10. * If the radix is not 10, the first two characters are removed from the string. * Any underscores are removed from the string. * The string is converted to a `u128` value as if by [`u128::from_str_radix`](https://doc.rust-lang.org/core/primitive.u128.html#method.from_str_radix) with the chosen radix. If the value does not fit in `u128`, the expression is rejected by the parser. * The `u128` value is converted to the expression's type via a [numeric cast](operator-expr#numeric-cast). > **Note**: The final cast will truncate the value of the literal if it does not fit in the expression's type. `rustc` includes a [lint check](../attributes/diagnostics#lint-check-attributes) named `overflowing_literals`, defaulting to `deny`, which rejects expressions where this occurs. > > > **Note**: `-1i8`, for example, is an application of the [negation operator](operator-expr#negation-operators) to the literal expression `1i8`, not a single integer literal expression. See [Overflow](operator-expr#overflow) for notes on representing the most negative value for a signed type. > > Floating-point literal expressions ---------------------------------- A floating-point literal expression consists of a single [FLOAT\_LITERAL](../tokens#floating-point-literals) token. If the token has a [suffix](../tokens#suffixes), the suffix will be the name of one of the [primitive floating-point types](../types/numeric#floating-point-types): `f32` or `f64`, and the expression has that type. If the token has no suffix, the expression's type is determined by type inference: * If a floating-point type can be *uniquely* determined from the surrounding program context, the expression has that type. * If the program context under-constrains the type, it defaults to `f64`. * If the program context over-constrains the type, it is considered a static type error. Examples of floating-point literal expressions: ``` #![allow(unused)] fn main() { 123.0f64; // type f64 0.1f64; // type f64 0.1f32; // type f32 12E+99_f64; // type f64 5f32; // type f32 let x: f64 = 2.; // type f64 } ``` The value of the expression is determined from the string representation of the token as follows: * Any underscores are removed from the string. * The string is converted to the expression's type as if by [`f32::from_str`](https://doc.rust-lang.org/core/primitive.f32.html#method.from_str) or [`f64::from_str`](https://doc.rust-lang.org/core/primitive.f64.html#method.from_str). > **Note**: `-1.0`, for example, is an application of the [negation operator](operator-expr#negation-operators) to the literal expression `1.0`, not a single floating-point literal expression. > > > **Note**: `inf` and `NaN` are not literal tokens. The [`f32::INFINITY`](https://doc.rust-lang.org/core/primitive.f32.html#associatedconstant.INFINITY), [`f64::INFINITY`](https://doc.rust-lang.org/core/primitive.f64.html#associatedconstant.INFINITY), [`f32::NAN`](https://doc.rust-lang.org/core/primitive.f32.html#associatedconstant.NAN), and [`f64::NAN`](https://doc.rust-lang.org/core/primitive.f64.html#associatedconstant.NAN) constants can be used instead of literal expressions. In `rustc`, a literal large enough to be evaluated as infinite will trigger the `overflowing_literals` lint check. > > Boolean literal expressions --------------------------- A boolean literal expression consists of one of the keywords `true` or `false`. The expression's type is the primitive [boolean type](../types/boolean), and its value is: * true if the keyword is `true` * false if the keyword is `false`
programming_docs
rust Loops Loops ===== > **Syntax** > *LoopExpression* : > [*LoopLabel*](#loop-labels)? ( > [*InfiniteLoopExpression*](#infinite-loops) > | [*PredicateLoopExpression*](#predicate-loops) > | [*PredicatePatternLoopExpression*](#predicate-pattern-loops) > | [*IteratorLoopExpression*](#iterator-loops) > ) > > Rust supports four loop expressions: * A [`loop` expression](#infinite-loops) denotes an infinite loop. * A [`while` expression](#predicate-loops) loops until a predicate is false. * A [`while let` expression](#predicate-pattern-loops) tests a pattern. * A [`for` expression](#iterator-loops) extracts values from an iterator, looping until the iterator is empty. All four types of loop support [`break` expressions](#break-expressions), [`continue` expressions](#continue-expressions), and [labels](#loop-labels). Only `loop` supports [evaluation to non-trivial values](#break-and-loop-values). Infinite loops -------------- > **Syntax** > *InfiniteLoopExpression* : > `loop` [*BlockExpression*](block-expr) > > A `loop` expression repeats execution of its body continuously: `loop { println!("I live."); }`. A `loop` expression without an associated `break` expression is diverging and has type [`!`](../types/never). A `loop` expression containing associated [`break` expression(s)](#break-expressions) may terminate, and must have type compatible with the value of the `break` expression(s). Predicate loops --------------- > **Syntax** > *PredicateLoopExpression* : > `while` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr) > > A `while` loop begins by evaluating the [boolean](../types/boolean) loop conditional operand. If the loop conditional operand evaluates to `true`, the loop body block executes, then control returns to the loop conditional operand. If the loop conditional expression evaluates to `false`, the `while` expression completes. An example: ``` #![allow(unused)] fn main() { let mut i = 0; while i < 10 { println!("hello"); i = i + 1; } } ``` Predicate pattern loops ----------------------- > **Syntax** > [*PredicatePatternLoopExpression*](#predicate-pattern-loops) : > `while` `let` [*Pattern*](../patterns) `=` [*Scrutinee*](match-expr)*except lazy boolean operator expression* [*BlockExpression*](block-expr) > > A `while let` loop is semantically similar to a `while` loop but in place of a condition expression it expects the keyword `let` followed by a pattern, an `=`, a [scrutinee](../glossary#scrutinee) expression and a block expression. If the value of the scrutinee matches the pattern, the loop body block executes then control returns to the pattern matching statement. Otherwise, the while expression completes. ``` #![allow(unused)] fn main() { let mut x = vec![1, 2, 3]; while let Some(y) = x.pop() { println!("y = {}", y); } while let _ = 5 { println!("Irrefutable patterns are always true"); break; } } ``` A `while let` loop is equivalent to a `loop` expression containing a [`match` expression](match-expr) as follows. ``` 'label: while let PATS = EXPR { /* loop body */ } ``` is equivalent to ``` 'label: loop { match EXPR { PATS => { /* loop body */ }, _ => break, } } ``` Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions: ``` #![allow(unused)] fn main() { let mut vals = vec![2, 3, 1, 2, 2]; while let Some(v @ 1) | Some(v @ 2) = vals.pop() { // Prints 2, 2, then 1 println!("{}", v); } } ``` As is the case in [`if let` expressions](if-expr#if-let-expressions), the scrutinee cannot be a [lazy boolean operator expression](operator-expr#lazy-boolean-operators). Iterator loops -------------- > **Syntax** > *IteratorLoopExpression* : > `for` [*Pattern*](../patterns) `in` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr) > > A `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`. If the iterator yields a value, that value is matched against the irrefutable pattern, the body of the loop is executed, and then control returns to the head of the `for` loop. If the iterator is empty, the `for` expression completes. An example of a `for` loop over the contents of an array: ``` #![allow(unused)] fn main() { let v = &["apples", "cake", "coffee"]; for text in v { println!("I like {}.", text); } } ``` An example of a for loop over a series of integers: ``` #![allow(unused)] fn main() { let mut sum = 0; for n in 1..11 { sum += n; } assert_eq!(sum, 55); } ``` A `for` loop is equivalent to a `loop` expression containing a [`match` expression](match-expr) as follows: ``` 'label: for PATTERN in iter_expr { /* loop body */ } ``` is equivalent to ``` { let result = match IntoIterator::into_iter(iter_expr) { mut iter => 'label: loop { let mut next; match Iterator::next(&mut iter) { Option::Some(val) => next = val, Option::None => break, }; let PATTERN = next; let () = { /* loop body */ }; }, }; result } ``` `IntoIterator`, `Iterator`, and `Option` are always the standard library items here, not whatever those names resolve to in the current scope. The variable names `next`, `iter`, and `val` are for exposition only, they do not actually have names the user can type. > **Note**: that the outer `match` is used to ensure that any [temporary values](../expressions#temporaries) in `iter_expr` don't get dropped before the loop is finished. `next` is declared before being assigned because it results in types being inferred correctly more often. > > Loop labels ----------- > **Syntax** > *LoopLabel* : > [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels) `:` > > A loop expression may optionally have a *label*. The label is written as a lifetime preceding the loop expression, as in `'foo: loop { break 'foo; }`, `'bar: while false {}`, `'humbug: for _ in 0..0 {}`. If a label is present, then labeled `break` and `continue` expressions nested within this loop may exit out of this loop or return control to its head. See [break expressions](#break-expressions) and [continue expressions](#continue-expressions). `break` expressions -------------------- > **Syntax** > *BreakExpression* : > `break` [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels)? [*Expression*](../expressions)? > > When `break` is encountered, execution of the associated loop body is immediately terminated, for example: ``` #![allow(unused)] fn main() { let mut last = 0; for x in 1..100 { if x > 12 { break; } last = x; } assert_eq!(last, 12); } ``` A `break` expression is normally associated with the innermost `loop`, `for` or `while` loop enclosing the `break` expression, but a [label](#loop-labels) can be used to specify which enclosing loop is affected. Example: ``` #![allow(unused)] fn main() { 'outer: loop { while true { break 'outer; } } } ``` A `break` expression is only permitted in the body of a loop, and has one of the forms `break`, `break 'label` or ([see below](#break-and-loop-values)) `break EXPR` or `break 'label EXPR`. `continue` expressions ----------------------- > **Syntax** > *ContinueExpression* : > `continue` [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels)? > > When `continue` is encountered, the current iteration of the associated loop body is immediately terminated, returning control to the loop *head*. In the case of a `while` loop, the head is the conditional expression controlling the loop. In the case of a `for` loop, the head is the call-expression controlling the loop. Like `break`, `continue` is normally associated with the innermost enclosing loop, but `continue 'label` may be used to specify the loop affected. A `continue` expression is only permitted in the body of a loop. `break` and loop values ------------------------ When associated with a `loop`, a break expression may be used to return a value from that loop, via one of the forms `break EXPR` or `break 'label EXPR`, where `EXPR` is an expression whose result is returned from the `loop`. For example: ``` #![allow(unused)] fn main() { let (mut a, mut b) = (1, 1); let result = loop { if b > 10 { break b; } let c = a + b; a = b; b = c; }; // first number in Fibonacci sequence over 10: assert_eq!(result, 13); } ``` In the case a `loop` has an associated `break`, it is not considered diverging, and the `loop` must have a type compatible with each `break` expression. `break` without an expression is considered identical to `break` with expression `()`. rust return expressions `return` expressions ===================== > **Syntax** > *ReturnExpression* : > `return` [*Expression*](../expressions)? > > Return expressions are denoted with the keyword `return`. Evaluating a `return` expression moves its argument into the designated output location for the current function call, destroys the current function activation frame, and transfers control to the caller frame. An example of a `return` expression: ``` #![allow(unused)] fn main() { fn max(a: i32, b: i32) -> i32 { if a > b { return a; } return b; } } ``` rust Closure expressions Closure expressions =================== > **Syntax** > *ClosureExpression* : > `move`? > ( `||` | `|` *ClosureParameters*? `|` ) > ([*Expression*](../expressions) | `->` [*TypeNoBounds*](../types#type-expressions) [*BlockExpression*](block-expr)) > > *ClosureParameters* : > *ClosureParam* (`,` *ClosureParam*)\* `,`? > > *ClosureParam* : > [*OuterAttribute*](../attributes)\* [*PatternNoTopAlt*](../patterns) ( `:` [*Type*](../types#type-expressions) )? > > A *closure expression*, also know as a lambda expression or a lambda, defines a [closure type](../types/closure) and evaluates to a value of that type. The syntax for a closure expression is an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns](../patterns), called the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, called the *return type*, and then an expression, called the *closure body operand*. The optional type after each pattern is a type annotation for the pattern. If there is a return type, the closure body must be a [block](block-expr). A closure expression denotes a function that maps a list of parameters onto the expression that follows the parameters. Just like a [`let` binding](../statements#let-statements), the closure parameters are irrefutable [patterns](../patterns), whose type annotation is optional and will be inferred from context if not given. Each closure expression has a unique, anonymous type. Significantly, closure expressions *capture their environment*, which regular [function definitions](../items/functions) do not. Without the `move` keyword, the closure expression [infers how it captures each variable from its environment](../types/closure#capture-modes), preferring to capture by shared reference, effectively borrowing all outer variables mentioned inside the closure's body. If needed the compiler will infer that instead mutable references should be taken, or that the values should be moved or copied (depending on their type) from the environment. A closure can be forced to capture its environment by copying or moving values by prefixing it with the `move` keyword. This is often used to ensure that the closure's lifetime is `'static`. Closure trait implementations ----------------------------- Which traits the closure type implement depends on how variables are captured and the types of the captured variables. See the [call traits and coercions](../types/closure#call-traits-and-coercions) chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`. The closure type implements [`Send`](../special-types-and-traits#send) and [`Sync`](../special-types-and-traits#sync) if the type of every captured variable also implements the trait. Example ------- In this example, we define a function `ten_times` that takes a higher-order function argument, and we then call it with a closure expression as an argument, followed by a closure expression that moves values from its environment. ``` #![allow(unused)] fn main() { fn ten_times<F>(f: F) where F: Fn(i32) { for index in 0..10 { f(index); } } ten_times(|j| println!("hello, {}", j)); // With type annotations ten_times(|j: i32| -> () { println!("hello, {}", j) }); let word = "konnichiwa".to_owned(); ten_times(move |j| println!("{}, {}", word, j)); } ``` Attributes on closure parameters -------------------------------- Attributes on closure parameters follow the same rules and restrictions as [regular function parameters](../items/functions#attributes-on-function-parameters). rust Path expressions Path expressions ================ > **Syntax** > *PathExpression* : > [*PathInExpression*](../paths#paths-in-expressions) > | [*QualifiedPathInExpression*](../paths#qualified-paths) > > A [path](../paths) used as an expression context denotes either a local variable or an item. Path expressions that resolve to local or static variables are [place expressions](../expressions#place-expressions-and-value-expressions), other paths are [value expressions](../expressions#place-expressions-and-value-expressions). Using a [`static mut`](../items/static-items#mutable-statics) variable requires an [`unsafe` block](block-expr#unsafe-blocks). ``` #![allow(unused)] fn main() { mod globals { pub static STATIC_VAR: i32 = 5; pub static mut STATIC_MUT_VAR: i32 = 7; } let local_var = 3; local_var; globals::STATIC_VAR; unsafe { globals::STATIC_MUT_VAR }; let some_constructor = Some::<i32>; let push_integer = Vec::<i32>::push; let slice_reverse = <[i32]>::reverse; } ``` rust Await expressions Await expressions ================= > **Syntax** > *AwaitExpression* : > [*Expression*](../expressions) `.` `await` > > An `await` expression is a syntactic construct for suspending a computation provided by an implementation of `std::future::IntoFuture` until the given future is ready to produce a value. The syntax for an await expression is an expression with a type that implements the [`IntoFuture`](../../std/future/trait.intofuture) trait, called the *future operand*, then the token `.`, and then the `await` keyword. Await expressions are legal only within an [async context](block-expr#async-context), like an [`async fn`](../items/functions#async-functions) or an [`async` block](block-expr#async-blocks). More specifically, an await expression has the following effect. 1. Create a future by calling [`IntoFuture::into_future`](../../std/future/trait.intofuture#tymethod.into_future) on the future operand. 2. Evaluate the future to a [future](../../std/future/trait.future) `tmp`; 3. Pin `tmp` using [`Pin::new_unchecked`](../../std/pin/struct.pin#method.new_unchecked); 4. This pinned future is then polled by calling the [`Future::poll`](../../std/future/trait.future#tymethod.poll) method and passing it the current [task context](#task-context); 5. If the call to `poll` returns [`Poll::Pending`](../../std/task/enum.poll#variant.Pending), then the future returns `Poll::Pending`, suspending its state so that, when the surrounding async context is re-polled,execution returns to step 3; 6. Otherwise the call to `poll` must have returned [`Poll::Ready`](../../std/task/enum.poll#variant.Ready), in which case the value contained in the [`Poll::Ready`](../../std/task/enum.poll#variant.Ready) variant is used as the result of the `await` expression itself. > **Edition differences**: Await expressions are only available beginning with Rust 2018. > > Task context ------------ The task context refers to the [`Context`](../../std/task/struct.context) which was supplied to the current [async context](block-expr#async-context) when the async context itself was polled. Because `await` expressions are only legal in an async context, there must be some task context available. Approximate desugaring ---------------------- Effectively, an await expression is roughly equivalent to the following non-normative desugaring: ``` match operand.into_future() { mut pinned => loop { let mut pin = unsafe { Pin::new_unchecked(&mut pinned) }; match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) { Poll::Ready(r) => break r, Poll::Pending => yield Poll::Pending, } } } ``` where the `yield` pseudo-code returns `Poll::Pending` and, when re-invoked, resumes execution from that point. The variable `current_context` refers to the context taken from the async environment. rust Call expressions Call expressions ================ > **Syntax** > *CallExpression* : > [*Expression*](../expressions) `(` *CallParams*? `)` > > *CallParams* : > [*Expression*](../expressions) ( `,` [*Expression*](../expressions) )\* `,`? > > A *call expression* calls a function. The syntax of a call expression is an expression, called the *function operand*, followed by a parenthesized comma-separated list of expression, called the *argument operands*. If the function eventually returns, then the expression completes. For [non-function types](../types/function-item), the expression `f(...)` uses the method on one of the [`std::ops::Fn`](../../std/ops/trait.fn), [`std::ops::FnMut`](../../std/ops/trait.fnmut) or [`std::ops::FnOnce`](../../std/ops/trait.fnonce) traits, which differ in whether they take the type by reference, mutable reference, or take ownership respectively. An automatic borrow will be taken if needed. The function operand will also be [automatically dereferenced](field-expr#automatic-dereferencing) as required. Some examples of call expressions: ``` #![allow(unused)] fn main() { fn add(x: i32, y: i32) -> i32 { 0 } let three: i32 = add(1i32, 2i32); let name: &'static str = (|| "Rust")(); } ``` Disambiguating Function Calls ----------------------------- All function calls are sugar for a more explicit [fully-qualified syntax](../paths#qualified-paths). Function calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items. > **Note**: In the past, the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", have been used in documentation, issues, RFCs, and other community writings. However, these terms lack descriptive power and potentially confuse the issue at hand. We mention them here for searchability's sake. > > Several situations often occur which result in ambiguities about the receiver or referent of method or associated function calls. These situations may include: * Multiple in-scope traits define methods with the same name for the same types * Auto-`deref` is undesirable; for example, distinguishing between methods on a smart pointer itself and the pointer's referent * Methods which take no arguments, like [`default()`](../../std/default/trait.default#tymethod.default), and return properties of a type, like [`size_of()`](../../std/mem/fn.size_of) To resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits. For example, ``` trait Pretty { fn print(&self); } trait Ugly { fn print(&self); } struct Foo; impl Pretty for Foo { fn print(&self) {} } struct Bar; impl Pretty for Bar { fn print(&self) {} } impl Ugly for Bar { fn print(&self) {} } fn main() { let f = Foo; let b = Bar; // we can do this because we only have one item called `print` for `Foo`s f.print(); // more explicit, and, in the case of `Foo`, not necessary Foo::print(&f); // if you're not into the whole brevity thing <Foo as Pretty>::print(&f); // b.print(); // Error: multiple 'print' found // Bar::print(&b); // Still an error: multiple `print` found // necessary because of in-scope items defining `print` <Bar as Pretty>::print(&b); } ``` Refer to [RFC 132](https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md) for further details and motivations.
programming_docs
rust Block expressions Block expressions ================= > **Syntax** > *BlockExpression* : > `{` > [*InnerAttribute*](../attributes)\* > *Statements*? > `}` > > *Statements* : > [*Statement*](../statements)+ > | [*Statement*](../statements)+ [*ExpressionWithoutBlock*](../expressions) > | [*ExpressionWithoutBlock*](../expressions) > > A *block expression*, or *block*, is a control flow expression and anonymous namespace scope for items and variable declarations. As a control flow expression, a block sequentially executes its component non-item declaration statements and then its final optional expression. As an anonymous namespace scope, item declarations are only in scope inside the block itself and variables declared by `let` statements are in scope from the next statement until the end of the block. The syntax for a block is `{`, then any [inner attributes](../attributes), then any number of [statements](../statements), then an optional expression, called the final operand, and finally a `}`. Statements are usually required to be followed by a semicolon, with two exceptions: 1. Item declaration statements do not need to be followed by a semicolon. 2. Expression statements usually require a following semicolon except if its outer expression is a flow control expression. Furthermore, extra semicolons between statements are allowed, but these semicolons do not affect semantics. When evaluating a block expression, each statement, except for item declaration statements, is executed sequentially. Then the final operand is executed, if given. The type of a block is the type of the final operand, or `()` if the final operand is omitted. ``` #![allow(unused)] fn main() { fn fn_call() {} let _: () = { fn_call(); }; let five: i32 = { fn_call(); 5 }; assert_eq!(5, five); } ``` > Note: As a control flow expression, if a block expression is the outer expression of an expression statement, the expected type is `()` unless it is followed immediately by a semicolon. > > Blocks are always [value expressions](../expressions#place-expressions-and-value-expressions) and evaluate the last operand in value expression context. > **Note**: This can be used to force moving a value if really needed. For example, the following example fails on the call to `consume_self` because the struct was moved out of `s` in the block expression. > > > ``` > #![allow(unused)] > fn main() { > struct Struct; > > impl Struct { > fn consume_self(self) {} > fn borrow_self(&self) {} > } > > fn move_by_block_expression() { > let s = Struct; > > // Move the value out of `s` in the block expression. > (&{ s }).borrow_self(); > > // Fails to execute because `s` is moved out of. > s.consume_self(); > } > } > > ``` > `async` blocks --------------- > **Syntax** > *AsyncBlockExpression* : > `async` `move`? *BlockExpression* > > An *async block* is a variant of a block expression which evaluates to a future. The final expression of the block, if present, determines the result value of the future. Executing an async block is similar to executing a closure expression: its immediate effect is to produce and return an anonymous type. Whereas closures return a type that implements one or more of the [`std::ops::Fn`](../../std/ops/trait.fn) traits, however, the type returned for an async block implements the [`std::future::Future`](../../std/future/trait.future) trait. The actual data format for this type is unspecified. > **Note:** The future type that rustc generates is roughly equivalent to an enum with one variant per `await` point, where each variant stores the data needed to resume from its corresponding point. > > > **Edition differences**: Async blocks are only available beginning with Rust 2018. > > ### Capture modes Async blocks capture variables from their environment using the same [capture modes](../types/closure#capture-modes) as closures. Like closures, when written `async { .. }` the capture mode for each variable will be inferred from the content of the block. `async move { .. }` blocks however will move all referenced variables into the resulting future. ### Async context Because async blocks construct a future, they define an **async context** which can in turn contain [`await` expressions](await-expr). Async contexts are established by async blocks as well as the bodies of async functions, whose semantics are defined in terms of async blocks. ### Control-flow operators Async blocks act like a function boundary, much like closures. Therefore, the `?` operator and `return` expressions both affect the output of the future, not the enclosing function or other context. That is, `return <expr>` from within a closure will return the result of `<expr>` as the output of the future. Similarly, if `<expr>?` propagates an error, that error is propagated as the result of the future. Finally, the `break` and `continue` keywords cannot be used to branch out from an async block. Therefore the following is illegal: ``` #![allow(unused)] fn main() { loop { async move { break; // This would break out of the loop. } } } ``` `unsafe` blocks ---------------- > **Syntax** > *UnsafeBlockExpression* : > `unsafe` *BlockExpression* > > *See [`unsafe` block](../unsafe-blocks) for more information on when to use `unsafe`* A block of code can be prefixed with the `unsafe` keyword to permit [unsafe operations](../unsafety). Examples: ``` #![allow(unused)] fn main() { unsafe { let b = [13u8, 17u8]; let a = &b[0] as *const u8; assert_eq!(*a, 13); assert_eq!(*a.offset(1), 17); } unsafe fn an_unsafe_fn() -> i32 { 10 } let a = unsafe { an_unsafe_fn() }; } ``` Attributes on block expressions ------------------------------- [Inner attributes](../attributes) are allowed directly after the opening brace of a block expression in the following situations: * [Function](../items/functions) and [method](../items/associated-items#methods) bodies. * Loop bodies ([`loop`](loop-expr#infinite-loops), [`while`](loop-expr#predicate-loops), [`while let`](loop-expr#predicate-pattern-loops), and [`for`](loop-expr#iterator-loops)). * Block expressions used as a [statement](../statements). * Block expressions as elements of [array expressions](array-expr), [tuple expressions](tuple-expr), [call expressions](call-expr), and tuple-style [struct](struct-expr) expressions. * A block expression as the tail expression of another block expression. The attributes that have meaning on a block expression are [`cfg`](../conditional-compilation) and [the lint check attributes](../attributes/diagnostics#lint-check-attributes). For example, this function returns `true` on unix platforms and `false` on other platforms. ``` #![allow(unused)] fn main() { fn is_unix_platform() -> bool { #[cfg(unix)] { true } #[cfg(not(unix))] { false } } } ``` rust if and if let expressions `if` and `if let` expressions ============================== `if` expressions ----------------- > **Syntax** > *IfExpression* : > `if` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr) > (`else` ( [*BlockExpression*](block-expr) | *IfExpression* | *IfLetExpression* ) )? > > An `if` expression is a conditional branch in program control. The syntax of an `if` expression is a condition operand, followed by a consequent block, any number of `else if` conditions and blocks, and an optional trailing `else` block. The condition operands must have the [boolean type](../types/boolean). If a condition operand evaluates to `true`, the consequent block is executed and any subsequent `else if` or `else` block is skipped. If a condition operand evaluates to `false`, the consequent block is skipped and any subsequent `else if` condition is evaluated. If all `if` and `else if` conditions evaluate to `false` then any `else` block is executed. An if expression evaluates to the same value as the executed block, or `()` if no block is evaluated. An `if` expression must have the same type in all situations. ``` #![allow(unused)] fn main() { let x = 3; if x == 4 { println!("x is four"); } else if x == 3 { println!("x is three"); } else { println!("x is something else"); } let y = if 12 * 15 > 150 { "Bigger" } else { "Smaller" }; assert_eq!(y, "Bigger"); } ``` `if let` expressions --------------------- > **Syntax** > *IfLetExpression* : > `if` `let` [*Pattern*](../patterns) `=` [*Scrutinee*](match-expr)*except lazy boolean operator expression* [*BlockExpression*](block-expr) > (`else` ( [*BlockExpression*](block-expr) | *IfExpression* | *IfLetExpression* ) )? > > An `if let` expression is semantically similar to an `if` expression but in place of a condition operand it expects the keyword `let` followed by a pattern, an `=` and a [scrutinee](../glossary#scrutinee) operand. If the value of the scrutinee matches the pattern, the corresponding block will execute. Otherwise, flow proceeds to the following `else` block if it exists. Like `if` expressions, `if let` expressions have a value determined by the block that is evaluated. ``` #![allow(unused)] fn main() { let dish = ("Ham", "Eggs"); // this body will be skipped because the pattern is refuted if let ("Bacon", b) = dish { println!("Bacon is served with {}", b); } else { // This block is evaluated instead. println!("No bacon will be served"); } // this body will execute if let ("Ham", b) = dish { println!("Ham is served with {}", b); } if let _ = 5 { println!("Irrefutable patterns are always true"); } } ``` `if` and `if let` expressions can be intermixed: ``` #![allow(unused)] fn main() { let x = Some(3); let a = if let Some(1) = x { 1 } else if x == Some(2) { 2 } else if let Some(y) = x { y } else { -1 }; assert_eq!(a, 3); } ``` An `if let` expression is equivalent to a [`match` expression](match-expr) as follows: ``` if let PATS = EXPR { /* body */ } else { /*else */ } ``` is equivalent to ``` match EXPR { PATS => { /* body */ }, _ => { /* else */ }, // () if there is no else } ``` Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions: ``` #![allow(unused)] fn main() { enum E { X(u8), Y(u8), Z(u8), } let v = E::Y(12); if let E::X(n) | E::Y(n) = v { assert_eq!(n, 12); } } ``` The expression cannot be a [lazy boolean operator expression](operator-expr#lazy-boolean-operators). Use of a lazy boolean operator is ambiguous with a planned feature change of the language (the implementation of if-let chains - see [eRFC 2947](https://github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md#rollout-plan-and-transitioning-to-rust-2018)). When lazy boolean operator expression is desired, this can be achieved by using parenthesis as below: ``` // Before... if let PAT = EXPR && EXPR { .. } // After... if let PAT = ( EXPR && EXPR ) { .. } // Before... if let PAT = EXPR || EXPR { .. } // After... if let PAT = ( EXPR || EXPR ) { .. } ``` rust Range expressions Range expressions ================= > **Syntax** > *RangeExpression* : > *RangeExpr* > | *RangeFromExpr* > | *RangeToExpr* > | *RangeFullExpr* > | *RangeInclusiveExpr* > | *RangeToInclusiveExpr* > > *RangeExpr* : > [*Expression*](../expressions) `..` [*Expression*](../expressions) > > *RangeFromExpr* : > [*Expression*](../expressions) `..` > > *RangeToExpr* : > `..` [*Expression*](../expressions) > > *RangeFullExpr* : > `..` > > *RangeInclusiveExpr* : > [*Expression*](../expressions) `..=` [*Expression*](../expressions) > > *RangeToInclusiveExpr* : > `..=` [*Expression*](../expressions) > > The `..` and `..=` operators will construct an object of one of the `std::ops::Range` (or `core::ops::Range`) variants, according to the following table: | Production | Syntax | Type | Range | | --- | --- | --- | --- | | *RangeExpr* | start`..`end | [std::ops::Range](../../std/ops/struct.range) | start ≤ x < end | | *RangeFromExpr* | start`..` | [std::ops::RangeFrom](../../std/ops/struct.rangefrom) | start ≤ x | | *RangeToExpr* | `..`end | [std::ops::RangeTo](../../std/ops/struct.rangeto) | x < end | | *RangeFullExpr* | `..` | [std::ops::RangeFull](../../std/ops/struct.rangefull) | - | | *RangeInclusiveExpr* | start`..=`end | [std::ops::RangeInclusive](../../std/ops/struct.rangeinclusive) | start ≤ x ≤ end | | *RangeToInclusiveExpr* | `..=`end | [std::ops::RangeToInclusive](../../std/ops/struct.rangetoinclusive) | x ≤ end | Examples: ``` #![allow(unused)] fn main() { 1..2; // std::ops::Range 3..; // std::ops::RangeFrom ..4; // std::ops::RangeTo ..; // std::ops::RangeFull 5..=6; // std::ops::RangeInclusive ..=7; // std::ops::RangeToInclusive } ``` The following expressions are equivalent. ``` #![allow(unused)] fn main() { let x = std::ops::Range {start: 0, end: 10}; let y = 0..10; assert_eq!(x, y); } ``` Ranges can be used in `for` loops: ``` #![allow(unused)] fn main() { for i in 1..11 { println!("{}", i); } } ``` rust Field access expressions Field access expressions ======================== > **Syntax** > *FieldExpression* : > [*Expression*](../expressions) `.` [IDENTIFIER](../identifiers) > > A *field expression* is a [place expression](../expressions#place-expressions-and-value-expressions) that evaluates to the location of a field of a [struct](../items/structs) or [union](../items/unions). When the operand is [mutable](../expressions#mutability), the field expression is also mutable. The syntax for a field expression is an expression, called the *container operand*, then a `.`, and finally an [identifier](../identifiers). Field expressions cannot be followed by a parenthetical comma-separated list of expressions, as that is instead parsed as a [method call expression](method-call-expr). That is, they cannot be the function operand of a [call expression](call-expr). > **Note**: Wrap the field expression in a [parenthesized expression](grouped-expr) to use it in a call expression. > > > ``` > #![allow(unused)] > fn main() { > struct HoldsCallable<F: Fn()> { callable: F } > let holds_callable = HoldsCallable { callable: || () }; > > // Invalid: Parsed as calling the method "callable" > // holds_callable.callable(); > > // Valid > (holds_callable.callable)(); > } > > ``` > Examples: ``` mystruct.myfield; foo().x; (Struct {a: 10, b: 20}).a; (mystruct.function_field)() // Call expression containing a field expression ``` Automatic dereferencing ----------------------- If the type of the container operand implements [`Deref`](../special-types-and-traits#deref-and-derefmut) or [`DerefMut`](../special-types-and-traits#deref-and-derefmut) depending on whether the operand is [mutable](../expressions#mutability), it is *automatically dereferenced* as many times as necessary to make the field access possible. This processes is also called *autoderef* for short. Borrowing --------- The fields of a struct or a reference to a struct are treated as separate entities when borrowing. If the struct does not implement [`Drop`](../special-types-and-traits#drop) and is stored in a local variable, this also applies to moving out of each of its fields. This also does not apply if automatic dereferencing is done though user-defined types other than [`Box`](../special-types-and-traits#boxt). ``` #![allow(unused)] fn main() { struct A { f1: String, f2: String, f3: String } let mut x: A; x = A { f1: "f1".to_string(), f2: "f2".to_string(), f3: "f3".to_string() }; let a: &mut String = &mut x.f1; // x.f1 borrowed mutably let b: &String = &x.f2; // x.f2 borrowed immutably let c: &String = &x.f2; // Can borrow again let d: String = x.f3; // Move out of x.f3 } ``` rust Static items Static items ============ > **Syntax** > *StaticItem* : > `static` `mut`? [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions) ( `=` [*Expression*](../expressions) )? `;` > > A *static item* is similar to a [constant](constant-items), except that it represents a precise memory location in the program. All references to the static refer to the same memory location. Static items have the `static` lifetime, which outlives all other lifetimes in a Rust program. Static items do not call [`drop`](../destructors) at the end of the program. The static initializer is a [constant expression](../const_eval#constant-expressions) evaluated at compile time. Static initializers may refer to other statics. Non-`mut` static items that contain a type that is not [interior mutable](../interior-mutability) may be placed in read-only memory. All access to a static is safe, but there are a number of restrictions on statics: * The type must have the `Sync` trait bound to allow thread-safe access. * Constants cannot refer to statics. The initializer expression must be omitted in an [external block](external-blocks), and must be provided for free static items. Statics & generics ------------------ A static item defined in a generic scope (for example in a blanket or default implementation) will result in exactly one static item being defined, as if the static definition was pulled out of the current scope into the module. There will *not* be one item per monomorphization. This code: ``` use std::sync::atomic::{AtomicUsize, Ordering}; trait Tr { fn default_impl() { static COUNTER: AtomicUsize = AtomicUsize::new(0); println!("default_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed)); } fn blanket_impl(); } struct Ty1 {} struct Ty2 {} impl<T> Tr for T { fn blanket_impl() { static COUNTER: AtomicUsize = AtomicUsize::new(0); println!("blanket_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed)); } } fn main() { <Ty1 as Tr>::default_impl(); <Ty2 as Tr>::default_impl(); <Ty1 as Tr>::blanket_impl(); <Ty2 as Tr>::blanket_impl(); } ``` prints ``` default_impl: counter was 0 default_impl: counter was 1 blanket_impl: counter was 0 blanket_impl: counter was 1 ``` Mutable statics --------------- If a static item is declared with the `mut` keyword, then it is allowed to be modified by the program. One of Rust's goals is to make concurrency bugs hard to run into, and this is obviously a very large source of race conditions or other bugs. For this reason, an `unsafe` block is required when either reading or writing a mutable static variable. Care should be taken to ensure that modifications to a mutable static are safe with respect to other threads running in the same process. Mutable statics are still very useful, however. They can be used with C libraries and can also be bound from C libraries in an `extern` block. ``` #![allow(unused)] fn main() { fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 } static mut LEVELS: u32 = 0; // This violates the idea of no shared state, and this doesn't internally // protect against races, so this function is `unsafe` unsafe fn bump_levels_unsafe1() -> u32 { let ret = LEVELS; LEVELS += 1; return ret; } // Assuming that we have an atomic_add function which returns the old value, // this function is "safe" but the meaning of the return value may not be what // callers expect, so it's still marked as `unsafe` unsafe fn bump_levels_unsafe2() -> u32 { return atomic_add(&mut LEVELS, 1); } } ``` Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the `Sync` trait. Using Statics or Consts ----------------------- It can be confusing whether or not you should use a constant item or a static item. Constants should, in general, be preferred over statics unless one of the following are true: * Large amounts of data are being stored * The single-address property of statics is required. * Interior mutability is required.
programming_docs
rust Structs Structs ======= > **Syntax** > *Struct* : > *StructStruct* > | *TupleStruct* > > *StructStruct* : > `struct` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? ( `{` *StructFields*? `}` | `;` ) > > *TupleStruct* : > `struct` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? `(` *TupleFields*? `)` [*WhereClause*](generics#where-clauses)? `;` > > *StructFields* : > *StructField* (`,` *StructField*)\* `,`? > > *StructField* : > [*OuterAttribute*](../attributes)\* > [*Visibility*](../visibility-and-privacy)? > [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions) > > *TupleFields* : > *TupleField* (`,` *TupleField*)\* `,`? > > *TupleField* : > [*OuterAttribute*](../attributes)\* > [*Visibility*](../visibility-and-privacy)? > [*Type*](../types#type-expressions) > > A *struct* is a nominal [struct type](../types/struct) defined with the keyword `struct`. An example of a `struct` item and its use: ``` #![allow(unused)] fn main() { struct Point {x: i32, y: i32} let p = Point {x: 10, y: 11}; let px: i32 = p.x; } ``` A *tuple struct* is a nominal [tuple type](../types/tuple), also defined with the keyword `struct`. For example: ``` #![allow(unused)] fn main() { struct Point(i32, i32); let p = Point(10, 11); let px: i32 = match p { Point(x, _) => x }; } ``` A *unit-like struct* is a struct without any fields, defined by leaving off the list of fields entirely. Such a struct implicitly defines a constant of its type with the same name. For example: ``` #![allow(unused)] fn main() { struct Cookie; let c = [Cookie, Cookie {}, Cookie, Cookie {}]; } ``` is equivalent to ``` #![allow(unused)] fn main() { struct Cookie {} const Cookie: Cookie = Cookie {}; let c = [Cookie, Cookie {}, Cookie, Cookie {}]; } ``` The precise memory layout of a struct is not specified. One can specify a particular layout using the [`repr` attribute](../type-layout#representations). rust Generic parameters Generic parameters ================== > **Syntax** > *GenericParams* : > `<` `>` > | `<` (*GenericParam* `,`)\* *GenericParam* `,`? `>` > > *GenericParam* : > [*OuterAttribute*](../attributes)\* ( *LifetimeParam* | *TypeParam* | *ConstParam* ) > > *LifetimeParam* : > [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels) ( `:` [*LifetimeBounds*](../trait-bounds) )? > > *TypeParam* : > [IDENTIFIER](../identifiers)( `:` [*TypeParamBounds*](../trait-bounds)? )? ( `=` [*Type*](../types#type-expressions) )? > > *ConstParam*: > `const` [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions) ( `=` *[Block](../expressions/block-expr)* | [IDENTIFIER](../identifiers) | -?[LITERAL](../expressions/literal-expr) )? > > [Functions](functions), [type aliases](type-aliases), <structs>, <enumerations>, <unions>, <traits>, and <implementations> may be *parameterized* by types, constants, and lifetimes. These parameters are listed in angle brackets (`<...>`), usually immediately after the name of the item and before its definition. For implementations, which don't have a name, they come directly after `impl`. The order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed. Some examples of items with type, const, and lifetime parameters: ``` #![allow(unused)] fn main() { fn foo<'a, T>() {} trait A<U> {} struct Ref<'a, T> where T: 'a { r: &'a T } struct InnerArray<T, const N: usize>([T; N]); struct EitherOrderWorks<const N: bool, U>(U); } ``` Generic parameters are in scope within the item definition where they are declared. They are not in scope for items declared within the body of a function as described in [item declarations](../statements#item-declarations). [References](../types/pointer#shared-references-), [raw pointers](../types/pointer#raw-pointers-const-and-mut), [arrays](../types/array), [slices](../types/slice), [tuples](../types/tuple), and [function pointers](../types/function-pointer) have lifetime or type parameters as well, but are not referred to with path syntax. ### Const generics *Const generic parameters* allow items to be generic over constant values. The const identifier introduces a name for the constant parameter, and all instances of the item must be instantiated with a value of the given type. The only allowed types of const parameters are `u8`, `u16`, `u32`, `u64`, `u128`, `usize` `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`. Const parameters can be used anywhere a [const item](constant-items) can be used, with the exception that when used in a [type](../types) or [array repeat expression](../expressions/array-expr), it must be standalone (as described below). That is, they are allowed in the following places: 1. As an applied const to any type which forms a part of the signature of the item in question. 2. As part of a const expression used to define an [associated const](associated-items#associated-constants), or as a parameter to an [associated type](associated-items#associated-types). 3. As a value in any runtime expression in the body of any functions in the item. 4. As a parameter to any type used in the body of any functions in the item. 5. As a part of the type of any fields in the item. ``` #![allow(unused)] fn main() { // Examples where const generic parameters can be used. // Used in the signature of the item itself. fn foo<const N: usize>(arr: [i32; N]) { // Used as a type within a function body. let x: [i32; N]; // Used as an expression. println!("{}", N * 2); } // Used as a field of a struct. struct Foo<const N: usize>([i32; N]); impl<const N: usize> Foo<N> { // Used as an associated constant. const CONST: usize = N * 4; } trait Trait { type Output; } impl<const N: usize> Trait for Foo<N> { // Used as an associated type. type Output = [i32; N]; } } ``` ``` #![allow(unused)] fn main() { // Examples where const generic parameters cannot be used. fn foo<const N: usize>() { // Cannot use in item definitions within a function body. const BAD_CONST: [usize; N] = [1; N]; static BAD_STATIC: [usize; N] = [1; N]; fn inner(bad_arg: [usize; N]) { let bad_value = N * 2; } type BadAlias = [usize; N]; struct BadStruct([usize; N]); } } ``` As a further restriction, const parameters may only appear as a standalone argument inside of a [type](../types) or [array repeat expression](../expressions/array-expr). In those contexts, they may only be used as a single segment [path expression](../expressions/path-expr), possibly inside a [block](../expressions/block-expr) (such as `N` or `{N}`). That is, they cannot be combined with other expressions. ``` #![allow(unused)] fn main() { // Examples where const parameters may not be used. // Not allowed to combine in other expressions in types, such as the // arithmetic expression in the return type here. fn bad_function<const N: usize>() -> [u8; {N + 1}] { // Similarly not allowed for array repeat expressions. [1; {N + 1}] } } ``` A const argument in a [path](../paths) specifies the const value to use for that item. The argument must be a [const expression](../const_eval#constant-expressions) of the type ascribed to the const parameter. The const expression must be a [block expression](../expressions/block-expr) (surrounded with braces) unless it is a single path segment (an [IDENTIFIER](../identifiers)) or a [literal](../expressions/literal-expr) (with a possibly leading `-` token). > **Note**: This syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type. > > ``` #![allow(unused)] fn main() { fn double<const N: i32>() { println!("doubled: {}", N * 2); } const SOME_CONST: i32 = 12; fn example() { // Example usage of a const argument. double::<9>(); double::<-123>(); double::<{7 + 8}>(); double::<SOME_CONST>(); double::<{ SOME_CONST + 5 }>(); } } ``` When there is ambiguity if a generic argument could be resolved as either a type or const argument, it is always resolved as a type. Placing the argument in a block expression can force it to be interpreted as a const argument. ``` #![allow(unused)] fn main() { type N = u32; struct Foo<const N: usize>; // The following is an error, because `N` is interpreted as the type alias `N`. fn foo<const N: usize>() -> Foo<N> { todo!() } // ERROR // Can be fixed by wrapping in braces to force it to be interpreted as the `N` // const parameter: fn bar<const N: usize>() -> Foo<{ N }> { todo!() } // ok } ``` Unlike type and lifetime parameters, const parameters can be declared without being used inside of a parameterized item, with the exception of implementations as described in [generic implementations](implementations#generic-implementations): ``` #![allow(unused)] fn main() { // ok struct Foo<const N: usize>; enum Bar<const M: usize> { A, B } // ERROR: unused parameter struct Baz<T>; struct Biz<'a>; struct Unconstrained; impl<const N: usize> Unconstrained {} } ``` When resolving a trait bound obligation, the exhaustiveness of all implementations of const parameters is not considered when determining if the bound is satisfied. For example, in the following, even though all possible const values for the `bool` type are implemented, it is still an error that the trait bound is not satisfied: ``` #![allow(unused)] fn main() { struct Foo<const B: bool>; trait Bar {} impl Bar for Foo<true> {} impl Bar for Foo<false> {} fn needs_bar(_: impl Bar) {} fn generic<const B: bool>() { let v = Foo::<B>; needs_bar(v); // ERROR: trait bound `Foo<B>: Bar` is not satisfied } } ``` Where clauses ------------- > **Syntax** > *WhereClause* : > `where` ( *WhereClauseItem* `,` )\* *WhereClauseItem* ? > > *WhereClauseItem* : > *LifetimeWhereClauseItem* > | *TypeBoundWhereClauseItem* > > *LifetimeWhereClauseItem* : > [*Lifetime*](../trait-bounds) `:` [*LifetimeBounds*](../trait-bounds) > > *TypeBoundWhereClauseItem* : > [*ForLifetimes*](../trait-bounds#higher-ranked-trait-bounds)? [*Type*](../types#type-expressions) `:` [*TypeParamBounds*](../trait-bounds)? > > *Where clauses* provide another way to specify bounds on type and lifetime parameters as well as a way to specify bounds on types that aren't type parameters. The `for` keyword can be used to introduce [higher-ranked lifetimes](../trait-bounds#higher-ranked-trait-bounds). It only allows [*LifetimeParam*](#generic-parameters) parameters. ``` #![allow(unused)] fn main() { struct A<T> where T: Iterator, // Could use A<T: Iterator> instead T::Item: Copy, // Bound on an associated type String: PartialEq<T>, // Bound on `String`, using the type parameter i32: Default, // Allowed, but not useful { f: T, } } ``` Attributes ---------- Generic lifetime and type parameters allow [attributes](../attributes) on them. There are no built-in attributes that do anything in this position, although custom derive attributes may give meaning to it. This example shows using a custom derive attribute to modify the meaning of a generic parameter. ``` // Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as // an attribute it understands. #[derive(MyFlexibleClone)] struct Foo<#[my_flexible_clone(unbounded)] H> { a: *const H } ``` rust External blocks External blocks =============== > **Syntax** > *ExternBlock* : > `unsafe`? `extern` [*Abi*](functions)? `{` > [*InnerAttribute*](../attributes)\* > *ExternalItem*\* > `}` > > *ExternalItem* : > [*OuterAttribute*](../attributes)\* ( > [*MacroInvocationSemi*](../macros#macro-invocation) > | ( [*Visibility*](../visibility-and-privacy)? ( [*StaticItem*](static-items) | [*Function*](functions) ) ) > ) > > External blocks provide *declarations* of items that are not *defined* in the current crate and are the basis of Rust's foreign function interface. These are akin to unchecked imports. Two kinds of item *declarations* are allowed in external blocks: <functions> and [statics](static-items). Calling functions or accessing statics that are declared in external blocks is only allowed in an `unsafe` context. The `unsafe` keyword is syntactically allowed to appear before the `extern` keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the `unsafe` keyword, before removing it from the token stream. Functions --------- Functions within external blocks are declared in the same way as other Rust functions, with the exception that they must not have a body and are instead terminated by a semicolon. Patterns are not allowed in parameters, only [IDENTIFIER](../identifiers) or `_` may be used. Function qualifiers (`const`, `async`, `unsafe`, and `extern`) are not allowed. Functions within external blocks may be called by Rust code, just like functions defined in Rust. The Rust compiler automatically translates between the Rust ABI and the foreign ABI. A function declared in an extern block is implicitly `unsafe`. When coerced to a function pointer, a function declared in an extern block has type `unsafe extern "abi" for<'l1, ..., 'lm> fn(A1, ..., An) -> R`, where `'l1`, ... `'lm` are its lifetime parameters, `A1`, ..., `An` are the declared types of its parameters and `R` is the declared return type. Statics ------- Statics within external blocks are declared in the same way as [statics](static-items) outside of external blocks, except that they do not have an expression initializing their value. It is `unsafe` to access a static item declared in an extern block, whether or not it's mutable, because there is nothing guaranteeing that the bit pattern at the static's memory is valid for the type it is declared with, since some arbitrary (e.g. C) code is in charge of initializing the static. Extern statics can be either immutable or mutable just like [statics](static-items) outside of external blocks. An immutable static *must* be initialized before any Rust code is executed. It is not enough for the static to be initialized before Rust code reads from it. ABI --- By default external blocks assume that the library they are calling uses the standard C ABI on the specific platform. Other ABIs may be specified using an `abi` string, as shown here: ``` #![allow(unused)] fn main() { // Interface to the Windows API extern "stdcall" { } } ``` There are three ABI strings which are cross-platform, and which all compilers are guaranteed to support: * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any Rust code. * `extern "C"` -- This is the same as `extern fn foo()`; whatever the default your C compiler supports. * `extern "system"` -- Usually the same as `extern "C"`, except on Win32, in which case it's `"stdcall"`, or what you should use to link to the Windows API itself There are also some platform-specific ABI strings: * `extern "cdecl"` -- The default for x86\_32 C code. * `extern "stdcall"` -- The default for the Win32 API on x86\_32. * `extern "win64"` -- The default for C code on x86\_64 Windows. * `extern "sysv64"` -- The default for C code on non-Windows x86\_64. * `extern "aapcs"` -- The default for ARM. * `extern "fastcall"` -- The `fastcall` ABI -- corresponds to MSVC's `__fastcall` and GCC and clang's `__attribute__((fastcall))` * `extern "vectorcall"` -- The `vectorcall` ABI -- corresponds to MSVC's `__vectorcall` and clang's `__attribute__((vectorcall))` Variadic functions ------------------ Functions within external blocks may be variadic by specifying `...` as the last argument. There must be at least one parameter before the variadic parameter. The variadic parameter may optionally be specified with an identifier. ``` #![allow(unused)] fn main() { extern "C" { fn foo(x: i32, ...); fn with_name(format: *const u8, args: ...); } } ``` Attributes on extern blocks --------------------------- The following [attributes](../attributes) control the behavior of external blocks. ### The `link` attribute The *`link` attribute* specifies the name of a native library that the compiler should link with for the items within an `extern` block. It uses the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify its inputs. The `name` key is the name of the native library to link. The `kind` key is an optional value which specifies the kind of library with the following possible values: * `dylib` — Indicates a dynamic library. This is the default if `kind` is not specified. * `static` — Indicates a static library. * `framework` — Indicates a macOS framework. This is only valid for macOS targets. The `name` key must be included if `kind` is specified. The optional `modifiers` argument is a way to specify linking modifiers for the library to link. Modifiers are specified as a comma-delimited string with each modifier prefixed with either a `+` or `-` to indicate that the modifier is enabled or disabled, respectively. Specifying multiple `modifiers` arguments in a single `link` attribute, or multiple identical modifiers in the same `modifiers` argument is not currently supported. Example: `#[link(name = "mylib", kind = "static", modifiers = "+whole-archive")`. The `wasm_import_module` key may be used to specify the [WebAssembly module](https://webassembly.github.io/spec/core/syntax/modules.html) name for the items within an `extern` block when importing symbols from the host environment. The default module name is `env` if `wasm_import_module` is not specified. ``` #[link(name = "crypto")] extern { // … } #[link(name = "CoreFoundation", kind = "framework")] extern { // … } #[link(wasm_import_module = "foo")] extern { // … } ``` It is valid to add the `link` attribute on an empty extern block. You can use this to satisfy the linking requirements of extern blocks elsewhere in your code (including upstream crates) instead of adding the attribute to each extern block. #### Linking modifiers: `bundle` This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error. When building a rlib or staticlib `+bundle` means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary. When building a rlib `-bundle` means that the native static library is registered as a dependency of that rlib "by name", and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking. When building a staticlib `-bundle` means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary. This modifier has no effect when building other targets like executables or dynamic libraries. The default for this modifier is `+bundle`. More implementation details about this modifier can be found in [`bundle` documentation for rustc](https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-bundle). #### Linking modifiers: `whole-archive` This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error. `+whole-archive` means that the static library is linked as a whole archive without throwing any object files away. The default for this modifier is `-whole-archive`. More implementation details about this modifier can be found in [`whole-archive` documentation for rustc](https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-whole-archive). ### The `link_name` attribute The `link_name` attribute may be specified on declarations inside an `extern` block to indicate the symbol to import for the given function or static. It uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify the name of the symbol. ``` #![allow(unused)] fn main() { extern { #[link_name = "actual_symbol_name"] fn name_in_rust(); } } ``` ### Attributes on function parameters Attributes on extern function parameters follow the same rules and restrictions as [regular function parameters](functions#attributes-on-function-parameters).
programming_docs
rust Functions Functions ========= > **Syntax** > *Function* : > *FunctionQualifiers* `fn` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? > `(` *FunctionParameters*? `)` > *FunctionReturnType*? [*WhereClause*](generics#where-clauses)? > ( [*BlockExpression*](../expressions/block-expr) | `;` ) > > *FunctionQualifiers* : > `const`? `async`[1](#async-edition)? `unsafe`? (`extern` *Abi*?)? > > *Abi* : > [STRING\_LITERAL](../tokens#string-literals) | [RAW\_STRING\_LITERAL](../tokens#raw-string-literals) > > *FunctionParameters* : > *SelfParam* `,`? > | (*SelfParam* `,`)? *FunctionParam* (`,` *FunctionParam*)\* `,`? > > *SelfParam* : > [*OuterAttribute*](../attributes)\* ( *ShorthandSelf* | *TypedSelf* ) > > *ShorthandSelf* : > (`&` | `&` [*Lifetime*](../trait-bounds))? `mut`? `self` > > *TypedSelf* : > `mut`? `self` `:` [*Type*](../types#type-expressions) > > *FunctionParam* : > [*OuterAttribute*](../attributes)\* ( *FunctionParamPattern* | `...` | [*Type*](../types#type-expressions) [2](#fn-param-2015) ) > > *FunctionParamPattern* : > [*PatternNoTopAlt*](../patterns) `:` ( [*Type*](../types#type-expressions) | `...` ) > > *FunctionReturnType* : > `->` [*Type*](../types#type-expressions) > > > 1 The `async` qualifier is not allowed in the 2015 edition. > > > 2 Function parameters with only a type are only allowed in an associated function of a [trait item](traits) in the 2015 edition. > > A *function* consists of a [block](../expressions/block-expr), along with a name, a set of parameters, and an output type. Other than a name, all these are optional. Functions are declared with the keyword `fn`. Functions may declare a set of *input* [*variables*](../variables) as parameters, through which the caller passes arguments into the function, and the *output* [*type*](../types#type-expressions) of the value the function will return to its caller on completion. If the output type is not explicitly stated, it is the [unit type](../types/tuple). When referred to, a *function* yields a first-class *value* of the corresponding zero-sized [*function item type*](../types/function-item), which when called evaluates to a direct call to the function. For example, this is a simple function: ``` #![allow(unused)] fn main() { fn answer_to_life_the_universe_and_everything() -> i32 { return 42; } } ``` Function parameters ------------------- As with `let` bindings, function parameters are irrefutable [patterns](../patterns), so any pattern that is valid in a let binding is also valid as a parameter: ``` #![allow(unused)] fn main() { fn first((value, _): (i32, i32)) -> i32 { value } } ``` If the first parameter is a *SelfParam*, this indicates that the function is a [method](associated-items#methods). Functions with a self parameter may only appear as an [associated function](associated-items#associated-functions-and-methods) in a [trait](traits) or [implementation](implementations). A parameter with the `...` token indicates a [variadic function](external-blocks#variadic-functions), and may only be used as the last parameter of an [external block](external-blocks) function. The variadic parameter may have an optional identifier, such as `args: ...`. Function body ------------- The block of a function is conceptually wrapped in a block that binds the argument patterns and then `return`s the value of the function's block. This means that the tail expression of the block, if evaluated, ends up being returned to the caller. As usual, an explicit return expression within the body of the function will short-cut that implicit return, if reached. For example, the function above behaves as if it was written as: ``` // argument_0 is the actual first argument passed from the caller let (value, _) = argument_0; return { value }; ``` Functions without a body block are terminated with a semicolon. This form may only appear in a [trait](traits) or [external block](external-blocks). Generic functions ----------------- A *generic function* allows one or more *parameterized types* to appear in its signature. Each type parameter must be explicitly declared in an angle-bracket-enclosed and comma-separated list, following the function name. ``` #![allow(unused)] fn main() { // foo is generic over A and B fn foo<A, B>(x: A, y: B) { } } ``` Inside the function signature and body, the name of the type parameter can be used as a type name. [Trait](traits) bounds can be specified for type parameters to allow methods with that trait to be called on values of that type. This is specified using the `where` syntax: ``` #![allow(unused)] fn main() { use std::fmt::Debug; fn foo<T>(x: T) where T: Debug { } } ``` When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `foo` function here: ``` #![allow(unused)] fn main() { use std::fmt::Debug; fn foo<T>(x: &[T]) where T: Debug { // details elided } foo(&[1, 2]); } ``` will instantiate type parameter `T` with `i32`. The type parameters can also be explicitly supplied in a trailing [path](../paths) component after the function name. This might be necessary if there is not sufficient context to determine the type parameters. For example, `mem::size_of::<u32>() == 4`. Extern function qualifier ------------------------- The `extern` function qualifier allows providing function *definitions* that can be called with a particular ABI: ``` extern "ABI" fn foo() { /* ... */ } ``` These are often used in combination with [external block](external-blocks) items which provide function *declarations* that can be used to call functions without providing their *definition*: ``` extern "ABI" { fn foo(); /* no body */ } unsafe { foo() } ``` When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items, the ABI `"Rust"` is assigned. For example: ``` #![allow(unused)] fn main() { fn foo() {} } ``` is equivalent to: ``` #![allow(unused)] fn main() { extern "Rust" fn foo() {} } ``` Functions can be called by foreign code, and using an ABI that differs from Rust allows, for example, to provide functions that can be called from other programming languages like C: ``` #![allow(unused)] fn main() { // Declares a function with the "C" ABI extern "C" fn new_i32() -> i32 { 0 } // Declares a function with the "stdcall" ABI #[cfg(target_arch = "x86_64")] extern "stdcall" fn new_i32_stdcall() -> i32 { 0 } } ``` Just as with [external block](external-blocks), when the `extern` keyword is used and the `"ABI"` is omitted, the ABI used defaults to `"C"`. That is, this: ``` #![allow(unused)] fn main() { extern fn new_i32() -> i32 { 0 } let fptr: extern fn() -> i32 = new_i32; } ``` is equivalent to: ``` #![allow(unused)] fn main() { extern "C" fn new_i32() -> i32 { 0 } let fptr: extern "C" fn() -> i32 = new_i32; } ``` Functions with an ABI that differs from `"Rust"` do not support unwinding in the exact same way that Rust does. Therefore, unwinding past the end of functions with such ABIs causes the process to abort. > **Note**: The LLVM backend of the `rustc` implementation aborts the process by executing an illegal instruction. > > Const functions --------------- Functions qualified with the `const` keyword are [const functions](../const_eval#const-functions), as are [tuple struct](structs) and [tuple variant](enumerations) constructors. *Const functions* can be called from within [const contexts](../const_eval#const-context). Const functions may use the [`extern`](#extern-function-qualifier) function qualifier, but only with the `"Rust"` and `"C"` ABIs. Const functions are not allowed to be [async](#async-functions). Async functions --------------- Functions may be qualified as async, and this can also be combined with the `unsafe` qualifier: ``` #![allow(unused)] fn main() { async fn regular_example() { } async unsafe fn unsafe_example() { } } ``` Async functions do no work when called: instead, they capture their arguments into a future. When polled, that future will execute the function's body. An async function is roughly equivalent to a function that returns [`impl Future`](../types/impl-trait) and with an [`async move` block](../expressions/block-expr#async-blocks) as its body: ``` #![allow(unused)] fn main() { // Source async fn example(x: &str) -> usize { x.len() } } ``` is roughly equivalent to: ``` #![allow(unused)] fn main() { use std::future::Future; // Desugared fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a { async move { x.len() } } } ``` The actual desugaring is more complex: * The return type in the desugaring is assumed to capture all lifetime parameters from the `async fn` declaration. This can be seen in the desugared example above, which explicitly outlives, and hence captures, `'a`. * The [`async move` block](../expressions/block-expr#async-blocks) in the body captures all function parameters, including those that are unused or bound to a `_` pattern. This ensures that function parameters are dropped in the same order as they would be if the function were not async, except that the drop occurs when the returned future has been fully awaited. For more information on the effect of async, see [`async` blocks](../expressions/block-expr#async-blocks). > **Edition differences**: Async functions are only available beginning with Rust 2018. > > ### Combining `async` and `unsafe` It is legal to declare a function that is both async and unsafe. The resulting function is unsafe to call and (like any async function) returns a future. This future is just an ordinary future and thus an `unsafe` context is not required to "await" it: ``` #![allow(unused)] fn main() { // Returns a future that, when awaited, dereferences `x`. // // Soundness condition: `x` must be safe to dereference until // the resulting future is complete. async unsafe fn unsafe_example(x: *const i32) -> i32 { *x } async fn safe_example() { // An `unsafe` block is required to invoke the function initially: let p = 22; let future = unsafe { unsafe_example(&p) }; // But no `unsafe` block required here. This will // read the value of `p`: let q = future.await; } } ``` Note that this behavior is a consequence of the desugaring to a function that returns an `impl Future` -- in this case, the function we desugar to is an `unsafe` function, but the return value remains the same. Unsafe is used on an async function in precisely the same way that it is used on other functions: it indicates that the function imposes some additional obligations on its caller to ensure soundness. As in any other unsafe function, these conditions may extend beyond the initial call itself -- in the snippet above, for example, the `unsafe_example` function took a pointer `x` as argument, and then (when awaited) dereferenced that pointer. This implies that `x` would have to be valid until the future is finished executing, and it is the caller's responsibility to ensure that. Attributes on functions ----------------------- [Outer attributes](../attributes) are allowed on functions. [Inner attributes](../attributes) are allowed directly after the `{` inside its [block](../expressions/block-expr). This example shows an inner attribute on a function. The function is documented with just the word "Example". ``` #![allow(unused)] fn main() { fn documented() { #![doc = "Example"] } } ``` > Note: Except for lints, it is idiomatic to only use outer attributes on function items. > > The attributes that have meaning on a function are [`cfg`](../conditional-compilation#the-cfg-attribute), [`cfg_attr`](../conditional-compilation#the-cfg_attr-attribute), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), [`export_name`](../abi#the-export_name-attribute), [`link_section`](../abi#the-link_section-attribute), [`no_mangle`](../abi#the-no_mangle-attribute), [the lint check attributes](../attributes/diagnostics#lint-check-attributes), [`must_use`](../attributes/diagnostics#the-must_use-attribute), [the procedural macro attributes](../procedural-macros), [the testing attributes](../attributes/testing), and [the optimization hint attributes](../attributes/codegen#optimization-hints). Functions also accept attributes macros. Attributes on function parameters --------------------------------- [Outer attributes](../attributes) are allowed on function parameters and the permitted [built-in attributes](../attributes#built-in-attributes-index) are restricted to `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, and `forbid`. ``` #![allow(unused)] fn main() { fn len( #[cfg(windows)] slice: &[u16], #[cfg(not(windows))] slice: &[u8], ) -> usize { slice.len() } } ``` Inert helper attributes used by procedural macro attributes applied to items are also allowed but be careful to not include these inert attributes in your final `TokenStream`. For example, the following code defines an inert `some_inert_attribute` attribute that is not formally defined anywhere and the `some_proc_macro_attribute` procedural macro is responsible for detecting its presence and removing it from the output token stream. ``` #[some_proc_macro_attribute] fn foo_oof(#[some_inert_attribute] arg: u8) { } ``` rust Modules Modules ======= > **Syntax:** > *Module* : > `unsafe`? `mod` [IDENTIFIER](../identifiers) `;` > | `unsafe`? `mod` [IDENTIFIER](../identifiers) `{` > [*InnerAttribute*](../attributes)\* > [*Item*](../items)\* > `}` > > A module is a container for zero or more [items](../items). A *module item* is a module, surrounded in braces, named, and prefixed with the keyword `mod`. A module item introduces a new, named module into the tree of modules making up a crate. Modules can nest arbitrarily. An example of a module: ``` #![allow(unused)] fn main() { mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ unimplemented!(); } fn cos(f: f64) -> f64 { /* ... */ unimplemented!(); } fn tan(f: f64) -> f64 { /* ... */ unimplemented!(); } } } ``` Modules and types share the same namespace. Declaring a named type with the same name as a module in scope is forbidden: that is, a type definition, trait, struct, enumeration, union, type parameter or crate can't shadow the name of a module in scope, or vice versa. Items brought into scope with `use` also have this restriction. The `unsafe` keyword is syntactically allowed to appear before the `mod` keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the `unsafe` keyword, before removing it from the token stream. Module Source Filenames ----------------------- A module without a body is loaded from an external file. When the module does not have a `path` attribute, the path to the file mirrors the logical [module path](../paths). Ancestor module path components are directories, and the module's contents are in a file with the name of the module plus the `.rs` extension. For example, the following module structure can have this corresponding filesystem structure: | Module Path | Filesystem Path | File Contents | | --- | --- | --- | | `crate` | `lib.rs` | `mod util;` | | `crate::util` | `util.rs` | `mod config;` | | `crate::util::config` | `util/config.rs` | | Module filenames may also be the name of the module as a directory with the contents in a file named `mod.rs` within that directory. The above example can alternately be expressed with `crate::util`'s contents in a file named `util/mod.rs`. It is not allowed to have both `util.rs` and `util/mod.rs`. > **Note**: Prior to `rustc` 1.30, using `mod.rs` files was the way to load a module with nested children. It is encouraged to use the new naming convention as it is more consistent, and avoids having many files named `mod.rs` within a project. > > ### The `path` attribute The directories and files used for loading external file modules can be influenced with the `path` attribute. For `path` attributes on modules not inside inline module blocks, the file path is relative to the directory the source file is located. For example, the following code snippet would use the paths shown based on where it is located: ``` #[path = "foo.rs"] mod c; ``` | Source File | `c`'s File Location | `c`'s Module Path | | --- | --- | --- | | `src/a/b.rs` | `src/a/foo.rs` | `crate::a::b::c` | | `src/a/mod.rs` | `src/a/foo.rs` | `crate::a::c` | For `path` attributes inside inline module blocks, the relative location of the file path depends on the kind of source file the `path` attribute is located in. "mod-rs" source files are root modules (such as `lib.rs` or `main.rs`) and modules with files named `mod.rs`. "non-mod-rs" source files are all other module files. Paths for `path` attributes inside inline module blocks in a mod-rs file are relative to the directory of the mod-rs file including the inline module components as directories. For non-mod-rs files, it is the same except the path starts with a directory with the name of the non-mod-rs module. For example, the following code snippet would use the paths shown based on where it is located: ``` mod inline { #[path = "other.rs"] mod inner; } ``` | Source File | `inner`'s File Location | `inner`'s Module Path | | --- | --- | --- | | `src/a/b.rs` | `src/a/b/inline/other.rs` | `crate::a::b::inline::inner` | | `src/a/mod.rs` | `src/a/inline/other.rs` | `crate::a::inline::inner` | An example of combining the above rules of `path` attributes on inline modules and nested modules within (applies to both mod-rs and non-mod-rs files): ``` #[path = "thread_files"] mod thread { // Load the `local_data` module from `thread_files/tls.rs` relative to // this source file's directory. #[path = "tls.rs"] mod local_data; } ``` Attributes on Modules --------------------- Modules, like all items, accept outer attributes. They also accept inner attributes: either after `{` for a module with a body, or at the beginning of the source file, after the optional BOM and shebang. The built-in attributes that have meaning on a module are [`cfg`](../conditional-compilation), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), [the lint check attributes](../attributes/diagnostics#lint-check-attributes), [`path`](#the-path-attribute), and [`no_implicit_prelude`](../names/preludes#the-no_implicit_prelude-attribute). Modules also accept macro attributes. rust Constant items Constant items ============== > **Syntax** > *ConstantItem* : > `const` ( [IDENTIFIER](../identifiers) | `_` ) `:` [*Type*](../types#type-expressions) ( `=` [*Expression*](../expressions) )? `;` > > A *constant item* is an optionally named *[constant value](../const_eval#constant-expressions)* which is not associated with a specific memory location in the program. Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes usage of constants from external crates, and non-[`Copy`](../special-types-and-traits#copy) types. References to the same constant are not necessarily guaranteed to refer to the same memory address. Constants must be explicitly typed. The type must have a `'static` lifetime: any references in the initializer must have `'static` lifetimes. Constants may refer to the address of other constants, in which case the address will have elided lifetimes where applicable, otherwise – in most cases – defaulting to the `static` lifetime. (See [static lifetime elision](../lifetime-elision#static-lifetime-elision).) The compiler is, however, still at liberty to translate the constant many times, so the address referred to may not be stable. ``` #![allow(unused)] fn main() { const BIT1: u32 = 1 << 0; const BIT2: u32 = 1 << 1; const BITS: [u32; 2] = [BIT1, BIT2]; const STRING: &'static str = "bitstring"; struct BitsNStrings<'a> { mybits: [u32; 2], mystring: &'a str, } const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings { mybits: BITS, mystring: STRING, }; } ``` The constant expression may only be omitted in a [trait definition](traits). Constants with Destructors -------------------------- Constants can contain destructors. Destructors are run when the value goes out of scope. ``` #![allow(unused)] fn main() { struct TypeWithDestructor(i32); impl Drop for TypeWithDestructor { fn drop(&mut self) { println!("Dropped. Held {}.", self.0); } } const ZERO_WITH_DESTRUCTOR: TypeWithDestructor = TypeWithDestructor(0); fn create_and_drop_zero_with_destructor() { let x = ZERO_WITH_DESTRUCTOR; // x gets dropped at end of function, calling drop. // prints "Dropped. Held 0.". } } ``` Unnamed constant ---------------- Unlike an [associated constant](associated-items#associated-constants), a [free](../glossary#free-item) constant may be unnamed by using an underscore instead of the name. For example: ``` #![allow(unused)] fn main() { const _: () = { struct _SameNameTwice; }; // OK although it is the same name as above: const _: () = { struct _SameNameTwice; }; } ``` As with [underscore imports](use-declarations#underscore-imports), macros may safely emit the same unnamed constant in the same scope more than once. For example, the following should not produce an error: ``` #![allow(unused)] fn main() { macro_rules! m { ($item: item) => { $item $item } } m!(const _: () = ();); // This expands to: // const _: () = (); // const _: () = (); } ```
programming_docs
rust Unions Unions ====== > **Syntax** > *Union* : > `union` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? `{`[*StructFields*](structs) `}` > > A union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`. ``` #![allow(unused)] fn main() { #[repr(C)] union MyUnion { f1: u32, f2: f32, } } ``` The key property of unions is that all fields of a union share common storage. As a result, writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field. Union field types are restricted to the following subset of types: * `Copy` types * References (`&T` and `&mut T` for arbitrary `T`) * `ManuallyDrop<T>` (for arbitrary `T`) * Tuples and arrays containing only allowed union field types This restriction ensures, in particular, that union fields never need to be dropped. Like for structs and enums, it is possible to `impl Drop` for a union to manually define what happens when it gets dropped. Initialization of a union ------------------------- A value of a union type can be created using the same syntax that is used for struct types, except that it must specify exactly one field: ``` #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; } ``` The expression above creates a value of type `MyUnion` and initializes the storage using field `f1`. The union can be accessed using the same syntax as struct fields: ``` #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; let f = unsafe { u.f1 }; } ``` Reading and writing union fields -------------------------------- Unions have no notion of an "active field". Instead, every union access just interprets the storage at the type of the field used for the access. Reading a union field reads the bits of the union at the field's type. Fields might have a non-zero offset (except when [the C representation](../type-layout#reprc-unions) is used); in that case the bits starting at the offset of the fields are read. It is the programmer's responsibility to make sure that the data is valid at the field's type. Failing to do so results in [undefined behavior](../behavior-considered-undefined). For example, reading the value `3` through of a field of the [boolean type](../types/boolean) is undefined behavior. Effectively, writing to and then reading from a union with [the C representation](../type-layout#reprc-unions) is analogous to a [`transmute`](../../std/mem/fn.transmute) from the type used for writing to the type used for reading. Consequently, all reads of union fields have to be placed in `unsafe` blocks: ``` #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } let u = MyUnion { f1: 1 }; unsafe { let f = u.f1; } } ``` Commonly, code using unions will provide safe wrappers around unsafe union field accesses. In contrast, writes to union fields are safe, since they just overwrite arbitrary data, but cannot cause undefined behavior. (Note that union field types can never have drop glue, so a union field write will never implicitly drop anything.) Pattern matching on unions -------------------------- Another way to access union fields is to use pattern matching. Pattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field. Since pattern matching is like reading the union with a particular field, it has to be placed in `unsafe` blocks as well. ``` #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } fn f(u: MyUnion) { unsafe { match u { MyUnion { f1: 10 } => { println!("ten"); } MyUnion { f2 } => { println!("{}", f2); } } } } } ``` Pattern matching may match a union as a field of a larger structure. In particular, when using a Rust union to implement a C tagged union via FFI, this allows matching on the tag and the corresponding field simultaneously: ``` #![allow(unused)] fn main() { #[repr(u32)] enum Tag { I, F } #[repr(C)] union U { i: i32, f: f32, } #[repr(C)] struct Value { tag: Tag, u: U, } fn is_zero(v: Value) -> bool { unsafe { match v { Value { tag: Tag::I, u: U { i: 0 } } => true, Value { tag: Tag::F, u: U { f: num } } if num == 0.0 => true, _ => false, } } } } ``` References to union fields -------------------------- Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields. Borrow checking rules have to be adjusted to account for this fact. As a result, if one field of a union is borrowed, all its remaining fields are borrowed as well for the same lifetime. ``` #![allow(unused)] fn main() { union MyUnion { f1: u32, f2: f32 } // ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time fn test() { let mut u = MyUnion { f1: 1 }; unsafe { let b1 = &mut u.f1; // ---- first mutable borrow occurs here (via `u.f1`) let b2 = &mut u.f2; // ^^^^ second mutable borrow occurs here (via `u.f2`) *b1 = 5; } // - first borrow ends here assert_eq!(unsafe { u.f1 }, 5); } } ``` As you could see, in many aspects (except for layouts, safety, and ownership) unions behave exactly like structs, largely as a consequence of inheriting their syntactic shape from structs. This is also true for many unmentioned aspects of Rust language (such as privacy, name resolution, type inference, generics, trait implementations, inherent implementations, coherence, pattern checking, etc etc etc). rust Associated Items Associated Items ================ > **Syntax** > *AssociatedItem* : > [*OuterAttribute*](../attributes)\* ( > [*MacroInvocationSemi*](../macros#macro-invocation) > | ( [*Visibility*](../visibility-and-privacy)? ( [*TypeAlias*](type-aliases) | [*ConstantItem*](constant-items) | [*Function*](functions) ) ) > ) > > *Associated Items* are the items declared in <traits> or defined in <implementations>. They are called this because they are defined on an associate type — the type in the implementation. They are a subset of the kinds of items you can declare in a module. Specifically, there are [associated functions](#associated-functions-and-methods) (including methods), [associated types](#associated-types), and [associated constants](#associated-constants). Associated items are useful when the associated item logically is related to the associating item. For example, the `is_some` method on `Option` is intrinsically related to Options, so should be associated. Every associated item kind comes in two varieties: definitions that contain the actual implementation and declarations that declare signatures for definitions. It is the declarations that make up the contract of traits and what is available on generic types. Associated functions and methods -------------------------------- *Associated functions* are <functions> associated with a type. An *associated function declaration* declares a signature for an associated function definition. It is written as a function item, except the function body is replaced with a `;`. The identifier is the name of the function. The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's. An *associated function definition* defines a function associated with another type. It is written the same as a [function item](../types/function-item). An example of a common associated function is a `new` function that returns a value of the type the associated function is associated with. ``` struct Struct { field: i32 } impl Struct { fn new() -> Struct { Struct { field: 0i32 } } } fn main () { let _struct = Struct::new(); } ``` When the associated function is declared on a trait, the function can also be called with a [path](../paths) that is a path to the trait appended by the name of the trait. When this happens, it is substituted for `<_ as Trait>::function_name`. ``` #![allow(unused)] fn main() { trait Num { fn from_i32(n: i32) -> Self; } impl Num for f64 { fn from_i32(n: i32) -> f64 { n as f64 } } // These 4 are all equivalent in this case. let _: f64 = Num::from_i32(42); let _: f64 = <_ as Num>::from_i32(42); let _: f64 = <f64 as Num>::from_i32(42); let _: f64 = f64::from_i32(42); } ``` ### Methods Associated functions whose first parameter is named `self` are called *methods* and may be invoked using the [method call operator](../expressions/method-call-expr), for example, `x.foo()`, as well as the usual function call notation. If the type of the `self` parameter is specified, it is limited to types resolving to one generated by the following grammar (where `'lt` denotes some arbitrary lifetime): ``` P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P> S = Self | P ``` The `Self` terminal in this grammar denotes a type resolving to the implementing type. This can also include the contextual type alias `Self`, other type aliases, or associated type projections resolving to the implementing type. ``` #![allow(unused)] fn main() { use std::rc::Rc; use std::sync::Arc; use std::pin::Pin; // Examples of methods implemented on struct `Example`. struct Example; type Alias = Example; trait Trait { type Output; } impl Trait for Example { type Output = Example; } impl Example { fn by_value(self: Self) {} fn by_ref(self: &Self) {} fn by_ref_mut(self: &mut Self) {} fn by_box(self: Box<Self>) {} fn by_rc(self: Rc<Self>) {} fn by_arc(self: Arc<Self>) {} fn by_pin(self: Pin<&Self>) {} fn explicit_type(self: Arc<Example>) {} fn with_lifetime<'a>(self: &'a Self) {} fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {} fn via_projection(self: <Example as Trait>::Output) {} } } ``` Shorthand syntax can be used without specifying a type, which have the following equivalents: | Shorthand | Equivalent | | --- | --- | | `self` | `self: Self` | | `&'lifetime self` | `self: &'lifetime Self` | | `&'lifetime mut self` | `self: &'lifetime mut Self` | > **Note**: Lifetimes can be, and usually are, elided with this shorthand. > > If the `self` parameter is prefixed with `mut`, it becomes a mutable variable, similar to regular parameters using a `mut` [identifier pattern](../patterns#identifier-patterns). For example: ``` #![allow(unused)] fn main() { trait Changer: Sized { fn change(mut self) {} fn modify(mut self: Box<Self>) {} } } ``` As an example of methods on a trait, consider the following: ``` #![allow(unused)] fn main() { type Surface = i32; type BoundingBox = i32; trait Shape { fn draw(&self, surface: Surface); fn bounding_box(&self) -> BoundingBox; } } ``` This defines a trait with two methods. All values that have <implementations> of this trait while the trait is in scope can have their `draw` and `bounding_box` methods called. ``` #![allow(unused)] fn main() { type Surface = i32; type BoundingBox = i32; trait Shape { fn draw(&self, surface: Surface); fn bounding_box(&self) -> BoundingBox; } struct Circle { // ... } impl Shape for Circle { // ... fn draw(&self, _: Surface) {} fn bounding_box(&self) -> BoundingBox { 0i32 } } impl Circle { fn new() -> Circle { Circle{} } } let circle_shape = Circle::new(); let bounding_box = circle_shape.bounding_box(); } ``` > **Edition Differences**: In the 2015 edition, it is possible to declare trait methods with anonymous parameters (e.g. `fn foo(u8)`). This is deprecated and an error as of the 2018 edition. All parameters must have an argument name. > > #### Attributes on method parameters Attributes on method parameters follow the same rules and restrictions as [regular function parameters](functions#attributes-on-function-parameters). Associated Types ---------------- *Associated types* are [type aliases](type-aliases) associated with another type. Associated types cannot be defined in [inherent implementations](implementations#inherent-implementations) nor can they be given a default implementation in traits. An *associated type declaration* declares a signature for associated type definitions. It is written as `type`, then an [identifier](../identifiers), and finally an optional list of trait bounds. The identifier is the name of the declared type alias. The optional trait bounds must be fulfilled by the implementations of the type alias. There is an implicit [`Sized`](../special-types-and-traits#sized) bound on associated types that can be relaxed using the special `?Sized` bound. An *associated type definition* defines a type alias on another type. It is written as `type`, then an [identifier](../identifiers), then an `=`, and finally a [type](../types#type-expressions). If a type `Item` has an associated type `Assoc` from a trait `Trait`, then `<Item as Trait>::Assoc` is a type that is an alias of the type specified in the associated type definition. Furthermore, if `Item` is a type parameter, then `Item::Assoc` can be used in type parameters. Associated types must not include [generic parameters](generics) or [where clauses](generics#where-clauses). ``` trait AssociatedType { // Associated type declaration type Assoc; } struct Struct; struct OtherStruct; impl AssociatedType for Struct { // Associated type definition type Assoc = OtherStruct; } impl OtherStruct { fn new() -> OtherStruct { OtherStruct } } fn main() { // Usage of the associated type to refer to OtherStruct as <Struct as AssociatedType>::Assoc let _other_struct: OtherStruct = <Struct as AssociatedType>::Assoc::new(); } ``` ### Associated Types Container Example Consider the following example of a `Container` trait. Notice that the type is available for use in the method signatures: ``` #![allow(unused)] fn main() { trait Container { type E; fn empty() -> Self; fn insert(&mut self, elem: Self::E); } } ``` In order for a type to implement this trait, it must not only provide implementations for every method, but it must specify the type `E`. Here's an implementation of `Container` for the standard library type `Vec`: ``` #![allow(unused)] fn main() { trait Container { type E; fn empty() -> Self; fn insert(&mut self, elem: Self::E); } impl<T> Container for Vec<T> { type E = T; fn empty() -> Vec<T> { Vec::new() } fn insert(&mut self, x: T) { self.push(x); } } } ``` Associated Constants -------------------- *Associated constants* are [constants](constant-items) associated with a type. An *associated constant declaration* declares a signature for associated constant definitions. It is written as `const`, then an identifier, then `:`, then a type, finished by a `;`. The identifier is the name of the constant used in the path. The type is the type that the definition has to implement. An *associated constant definition* defines a constant associated with a type. It is written the same as a [constant item](constant-items). Associated constant definitions undergo [constant evaluation](../const_eval) only when referenced. Further, definitions that include [generic parameters](generics) are evaluated after monomorphization. ``` struct Struct; struct GenericStruct<const ID: i32>; impl Struct { // Definition not immediately evaluated const PANIC: () = panic!("compile-time panic"); } impl<const ID: i32> GenericStruct<ID> { // Definition not immediately evaluated const NON_ZERO: () = if ID == 0 { panic!("contradiction") }; } fn main() { // Referencing Struct::PANIC causes compilation error let _ = Struct::PANIC; // Fine, ID is not 0 let _ = GenericStruct::<1>::NON_ZERO; // Compilation error from evaluating NON_ZERO with ID=0 let _ = GenericStruct::<0>::NON_ZERO; } ``` ### Associated Constants Examples A basic example: ``` trait ConstantId { const ID: i32; } struct Struct; impl ConstantId for Struct { const ID: i32 = 1; } fn main() { assert_eq!(1, Struct::ID); } ``` Using default values: ``` trait ConstantIdDefault { const ID: i32 = 1; } struct Struct; struct OtherStruct; impl ConstantIdDefault for Struct {} impl ConstantIdDefault for OtherStruct { const ID: i32 = 5; } fn main() { assert_eq!(1, Struct::ID); assert_eq!(5, OtherStruct::ID); } ``` rust Extern crate declarations Extern crate declarations ========================= > **Syntax:** > *ExternCrate* : > `extern` `crate` *CrateRef* *AsClause*? `;` > > *CrateRef* : > [IDENTIFIER](../identifiers) | `self` > > *AsClause* : > `as` ( [IDENTIFIER](../identifiers) | `_` ) > > An *`extern crate` declaration* specifies a dependency on an external crate. The external crate is then bound into the declaring scope as the [identifier](../identifiers) provided in the `extern crate` declaration. Additionally, if the `extern crate` appears in the crate root, then the crate name is also added to the [extern prelude](../names/preludes#extern-prelude), making it automatically in scope in all modules. The `as` clause can be used to bind the imported crate to a different name. The external crate is resolved to a specific `soname` at compile time, and a runtime linkage requirement to that `soname` is passed to the linker for loading at runtime. The `soname` is resolved at compile time by scanning the compiler's library path and matching the optional `crateid` provided against the `crateid` attributes that were declared on the external crate when it was compiled. If no `crateid` is provided, a default `name` attribute is assumed, equal to the [identifier](../identifiers) given in the `extern crate` declaration. The `self` crate may be imported which creates a binding to the current crate. In this case the `as` clause must be used to specify the name to bind it to. Three examples of `extern crate` declarations: ``` extern crate pcre; extern crate std; // equivalent to: extern crate std as std; extern crate std as ruststd; // linking to 'std' under another name ``` When naming Rust crates, hyphens are disallowed. However, Cargo packages may make use of them. In such case, when `Cargo.toml` doesn't specify a crate name, Cargo will transparently replace `-` with `_` (Refer to [RFC 940](https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md) for more details). Here is an example: ``` // Importing the Cargo package hello-world extern crate hello_world; // hyphen replaced with an underscore ``` Extern Prelude -------------- This section has been moved to [Preludes — Extern Prelude](../names/preludes#extern-prelude). Underscore Imports ------------------ An external crate dependency can be declared without binding its name in scope by using an underscore with the form `extern crate foo as _`. This may be useful for crates that only need to be linked, but are never referenced, and will avoid being reported as unused. The [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) works as usual and imports the macro names into the [`macro_use` prelude](../names/preludes#macro_use-prelude). The `no_link` attribute ----------------------- The *`no_link` attribute* may be specified on an `extern crate` item to prevent linking the crate into the output. This is commonly used to load a crate to access only its macros. rust Enumerations Enumerations ============ > **Syntax** > *Enumeration* : > `enum` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? `{` *EnumItems*? `}` > > *EnumItems* : > *EnumItem* ( `,` *EnumItem* )\* `,`? > > *EnumItem* : > *OuterAttribute*\* [*Visibility*](../visibility-and-privacy)? > [IDENTIFIER](../identifiers) ( *EnumItemTuple* | *EnumItemStruct* | *EnumItemDiscriminant* )? > > *EnumItemTuple* : > `(` [*TupleFields*](structs)? `)` > > *EnumItemStruct* : > `{` [*StructFields*](structs)? `}` > > *EnumItemDiscriminant* : > `=` [*Expression*](../expressions) > > An *enumeration*, also referred to as an *enum*, is a simultaneous definition of a nominal [enumerated type](../types/enum) as well as a set of *constructors*, that can be used to create or pattern-match values of the corresponding enumerated type. Enumerations are declared with the keyword `enum`. An example of an `enum` item and its use: ``` #![allow(unused)] fn main() { enum Animal { Dog, Cat, } let mut a: Animal = Animal::Dog; a = Animal::Cat; } ``` Enum constructors can have either named or unnamed fields: ``` #![allow(unused)] fn main() { enum Animal { Dog(String, f64), Cat { name: String, weight: f64 }, } let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2); a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 }; } ``` In this example, `Cat` is a *struct-like enum variant*, whereas `Dog` is simply called an enum variant. Each enum instance has a *discriminant* which is an integer associated to it that is used to determine which variant it holds. An opaque reference to this discriminant can be obtained with the [`mem::discriminant`](../../std/mem/fn.discriminant) function. Custom Discriminant Values for Fieldless Enumerations ----------------------------------------------------- If there is no data attached to *any* of the variants of an enumeration, then the discriminant can be directly chosen and accessed. These enumerations can be cast to integer types with the `as` operator by a [numeric cast](../expressions/operator-expr#semantics). The enumeration can optionally specify which integer each discriminant gets by following the variant name with `=` followed by a [constant expression](../const_eval#constant-expressions). If the first variant in the declaration is unspecified, then it is set to zero. For every other unspecified discriminant, it is set to one higher than the previous variant in the declaration. ``` #![allow(unused)] fn main() { enum Foo { Bar, // 0 Baz = 123, // 123 Quux, // 124 } let baz_discriminant = Foo::Baz as u32; assert_eq!(baz_discriminant, 123); } ``` Under the [default representation](../type-layout#the-default-representation), the specified discriminant is interpreted as an `isize` value although the compiler is allowed to use a smaller type in the actual memory layout. The size and thus acceptable values can be changed by using a [primitive representation](../type-layout#primitive-representations) or the [`C` representation](../type-layout#the-c-representation). It is an error when two variants share the same discriminant. ``` #![allow(unused)] fn main() { enum SharedDiscriminantError { SharedA = 1, SharedB = 1 } enum SharedDiscriminantError2 { Zero, // 0 One, // 1 OneToo = 1 // 1 (collision with previous!) } } ``` It is also an error to have an unspecified discriminant where the previous discriminant is the maximum value for the size of the discriminant. ``` #![allow(unused)] fn main() { #[repr(u8)] enum OverflowingDiscriminantError { Max = 255, MaxPlusOne // Would be 256, but that overflows the enum. } #[repr(u8)] enum OverflowingDiscriminantError2 { MaxMinusOne = 254, // 254 Max, // 255 MaxPlusOne // Would be 256, but that overflows the enum. } } ``` Zero-variant Enums ------------------ Enums with zero variants are known as *zero-variant enums*. As they have no valid values, they cannot be instantiated. ``` #![allow(unused)] fn main() { enum ZeroVariants {} } ``` Zero-variant enums are equivalent to the [never type](../types/never), but they cannot be coerced into other types. ``` #![allow(unused)] fn main() { enum ZeroVariants {} let x: ZeroVariants = panic!(); let y: u32 = x; // mismatched type error } ``` Variant visibility ------------------ Enum variants syntactically allow a [*Visibility*](../visibility-and-privacy) annotation, but this is rejected when the enum is validated. This allows items to be parsed with a unified syntax across different contexts where they are used. ``` #![allow(unused)] fn main() { macro_rules! mac_variant { ($vis:vis $name:ident) => { enum $name { $vis Unit, $vis Tuple(u8, u16), $vis Struct { f: u8 }, } } } // Empty `vis` is allowed. mac_variant! { E } // This is allowed, since it is removed before being validated. #[cfg(FALSE)] enum E { pub U, pub(crate) T(u8), pub(super) T { f: String } } } ```
programming_docs
rust Implementations Implementations =============== > **Syntax** > *Implementation* : > *InherentImpl* | *TraitImpl* > > *InherentImpl* : > `impl` [*GenericParams*](generics)? [*Type*](../types#type-expressions) [*WhereClause*](generics#where-clauses)? `{` > [*InnerAttribute*](../attributes)\* > [*AssociatedItem*](associated-items)\* > `}` > > *TraitImpl* : > `unsafe`? `impl` [*GenericParams*](generics)? `!`? [*TypePath*](../paths#paths-in-types) `for` [*Type*](../types#type-expressions) > [*WhereClause*](generics#where-clauses)? > `{` > [*InnerAttribute*](../attributes)\* > [*AssociatedItem*](associated-items)\* > `}` > > An *implementation* is an item that associates items with an *implementing type*. Implementations are defined with the keyword `impl` and contain functions that belong to an instance of the type that is being implemented or to the type statically. There are two types of implementations: * inherent implementations * [trait](traits) implementations Inherent Implementations ------------------------ An inherent implementation is defined as the sequence of the `impl` keyword, generic type declarations, a path to a nominal type, a where clause, and a bracketed set of associable items. The nominal type is called the *implementing type* and the associable items are the *associated items* to the implementing type. Inherent implementations associate the contained items to the implementing type. Inherent implementations can contain [associated functions](associated-items#associated-functions-and-methods) (including [methods](associated-items#methods)) and [associated constants](associated-items#associated-constants). They cannot contain associated type aliases. The [path](../paths) to an associated item is any path to the implementing type, followed by the associated item's identifier as the final path component. A type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition. ``` pub mod color { pub struct Color(pub u8, pub u8, pub u8); impl Color { pub const WHITE: Color = Color(255, 255, 255); } } mod values { use super::color::Color; impl Color { pub fn red() -> Color { Color(255, 0, 0) } } } pub use self::color::Color; fn main() { // Actual path to the implementing type and impl in the same module. color::Color::WHITE; // Impl blocks in different modules are still accessed through a path to the type. color::Color::red(); // Re-exported paths to the implementing type also work. Color::red(); // Does not work, because use in `values` is not pub. // values::Color::red(); } ``` Trait Implementations --------------------- A *trait implementation* is defined like an inherent implementation except that the optional generic type declarations are followed by a [trait](traits), followed by the keyword `for`, followed by a path to a nominal type. The trait is known as the *implemented trait*. The implementing type implements the implemented trait. A trait implementation must define all non-default associated items declared by the implemented trait, may redefine default associated items defined by the implemented trait, and cannot define any other items. The path to the associated items is `<` followed by a path to the implementing type followed by `as` followed by a path to the trait followed by `>` as a path component followed by the associated item's path component. [Unsafe traits](traits#unsafe-traits) require the trait implementation to begin with the `unsafe` keyword. ``` #![allow(unused)] fn main() { #[derive(Copy, Clone)] struct Point {x: f64, y: f64}; type Surface = i32; struct BoundingBox {x: f64, y: f64, width: f64, height: f64}; trait Shape { fn draw(&self, s: Surface); fn bounding_box(&self) -> BoundingBox; } fn do_draw_circle(s: Surface, c: Circle) { } struct Circle { radius: f64, center: Point, } impl Copy for Circle {} impl Clone for Circle { fn clone(&self) -> Circle { *self } } impl Shape for Circle { fn draw(&self, s: Surface) { do_draw_circle(s, *self); } fn bounding_box(&self) -> BoundingBox { let r = self.radius; BoundingBox { x: self.center.x - r, y: self.center.y - r, width: 2.0 * r, height: 2.0 * r, } } } } ``` ### Trait Implementation Coherence A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances. Two trait implementations overlap when there is a non-empty intersection of the traits the implementation is for, the implementations can be instantiated with the same type. #### Orphan rules Given `impl<P1..=Pn> Trait<T1..=Tn> for T0`, an `impl` is valid only if at least one of the following is true: * `Trait` is a [local trait](../glossary#local-trait) * All of + At least one of the types `T0..=Tn` must be a [local type](../glossary#local-type). Let `Ti` be the first such type. + No [uncovered type](../glossary#uncovered-type) parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`) Only the appearance of *uncovered* type parameters is restricted. Note that for the purposes of coherence, [fundamental types](../glossary#fundamental-type-constructors) are special. The `T` in `Box<T>` is not considered covered, and `Box<LocalType>` is considered local. Generic Implementations ----------------------- An implementation can take [generic parameters](generics), which can be used in the rest of the implementation. Implementation parameters are written directly after the `impl` keyword. ``` #![allow(unused)] fn main() { trait Seq<T> { fn dummy(&self, _: T) { } } impl<T> Seq<T> for Vec<T> { /* ... */ } impl Seq<bool> for u32 { /* Treat the integer as a sequence of bits */ } } ``` Generic parameters *constrain* an implementation if the parameter appears at least once in one of: * The implemented trait, if it has one * The implementing type * As an [associated type](associated-items#associated-types) in the [bounds](../trait-bounds) of a type that contains another parameter that constrains the implementation Type and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type. Examples of constraining situations: ``` #![allow(unused)] fn main() { trait Trait{} trait GenericTrait<T> {} trait HasAssocType { type Ty; } struct Struct; struct GenericStruct<T>(T); struct ConstGenericStruct<const N: usize>([(); N]); // T constrains by being an argument to GenericTrait. impl<T> GenericTrait<T> for i32 { /* ... */ } // T constrains by being an arguement to GenericStruct impl<T> Trait for GenericStruct<T> { /* ... */ } // Likewise, N constrains by being an argument to ConstGenericStruct impl<const N: usize> Trait for ConstGenericStruct<N> { /* ... */ } // T constrains by being in an associated type in a bound for type `U` which is // itself a generic parameter constraining the trait. impl<T, U> GenericTrait<U> for u32 where U: HasAssocType<Ty = T> { /* ... */ } // Like previous, except the type is `(U, isize)`. `U` appears inside the type // that includes `T`, and is not the type itself. impl<T, U> GenericStruct<U> where (U, isize): HasAssocType<Ty = T> { /* ... */ } } ``` Examples of non-constraining situations: ``` #![allow(unused)] fn main() { // The rest of these are errors, since they have type or const parameters that // do not constrain. // T does not constrain since it does not appear at all. impl<T> Struct { /* ... */ } // N does not constrain for the same reason. impl<const N: usize> Struct { /* ... */ } // Usage of T inside the implementation does not constrain the impl. impl<T> Struct { fn uses_t(t: &T) { /* ... */ } } // T is used as an associated type in the bounds for U, but U does not constrain. impl<T, U> Struct where U: HasAssocType<Ty = T> { /* ... */ } // T is used in the bounds, but not as an associated type, so it does not constrain. impl<T, U> GenericTrait<U> for u32 where U: GenericTrait<T> {} } ``` Example of an allowed unconstraining lifetime parameter: ``` #![allow(unused)] fn main() { struct Struct; impl<'a> Struct {} } ``` Example of a disallowed unconstraining lifetime parameter: ``` #![allow(unused)] fn main() { struct Struct; trait HasAssocType { type Ty; } impl<'a> HasAssocType for Struct { type Ty = &'a Struct; } } ``` Attributes on Implementations ----------------------------- Implementations may contain outer [attributes](../attributes) before the `impl` keyword and inner [attributes](../attributes) inside the brackets that contain the associated items. Inner attributes must come before any associated items. The attributes that have meaning here are [`cfg`](../conditional-compilation), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), and [the lint check attributes](../attributes/diagnostics#lint-check-attributes). rust Traits Traits ====== > **Syntax** > *Trait* : > `unsafe`? `trait` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? ( `:` [*TypeParamBounds*](../trait-bounds)? )? [*WhereClause*](generics#where-clauses)? `{` > [*InnerAttribute*](../attributes)\* > [*AssociatedItem*](associated-items)\* > `}` > > A *trait* describes an abstract interface that types can implement. This interface consists of [associated items](associated-items), which come in three varieties: * [functions](associated-items#associated-functions-and-methods) * [types](associated-items#associated-types) * [constants](associated-items#associated-constants) All traits define an implicit type parameter `Self` that refers to "the type that is implementing this interface". Traits may also contain additional type parameters. These type parameters, including `Self`, may be constrained by other traits and so forth [as usual](generics). Traits are implemented for specific types through separate <implementations>. Trait functions may omit the function body by replacing it with a semicolon. This indicates that the implementation must define the function. If the trait function defines a body, this definition acts as a default for any implementation which does not override it. Similarly, associated constants may omit the equals sign and expression to indicate implementations must define the constant value. Associated types must never define the type, the type may only be specified in an implementation. ``` #![allow(unused)] fn main() { // Examples of associated trait items with and without definitions. trait Example { const CONST_NO_DEFAULT: i32; const CONST_WITH_DEFAULT: i32 = 99; type TypeNoDefault; fn method_without_default(&self); fn method_with_default(&self) {} } } ``` Trait functions are not allowed to be [`async`](functions#async-functions) or [`const`](functions#const-functions). Trait bounds ------------ Generic items may use traits as [bounds](../trait-bounds) on their type parameters. Generic Traits -------------- Type parameters can be specified for a trait to make it generic. These appear after the trait name, using the same syntax used in [generic functions](functions#generic-functions). ``` #![allow(unused)] fn main() { trait Seq<T> { fn len(&self) -> u32; fn elt_at(&self, n: u32) -> T; fn iter<F>(&self, f: F) where F: Fn(T); } } ``` Object Safety ------------- Object safe traits can be the base trait of a [trait object](../types/trait-object). A trait is *object safe* if it has the following qualities (defined in [RFC 255](https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md)): * All [supertraits](#supertraits) must also be object safe. * `Sized` must not be a [supertrait](#supertraits). In other words, it must not require `Self: Sized`. * It must not have any associated constants. * All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable: + Dispatchable functions require: - Not have any type parameters (although lifetime parameters are allowed), - Be a [method](associated-items#methods) that does not use `Self` except in the type of the receiver. - Have a receiver with one of the following types: * `&Self` (i.e. `&self`) * `&mut Self` (i.e `&mut self`) * [`Box<Self>`](../special-types-and-traits#boxt) * [`Rc<Self>`](../special-types-and-traits#rct) * [`Arc<Self>`](../special-types-and-traits#arct) * [`Pin<P>`](../special-types-and-traits#pinp) where `P` is one of the types above - Does not have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this). + Explicitly non-dispatchable functions require: - Have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this). ``` #![allow(unused)] fn main() { use std::rc::Rc; use std::sync::Arc; use std::pin::Pin; // Examples of object safe methods. trait TraitMethods { fn by_ref(self: &Self) {} fn by_ref_mut(self: &mut Self) {} fn by_box(self: Box<Self>) {} fn by_rc(self: Rc<Self>) {} fn by_arc(self: Arc<Self>) {} fn by_pin(self: Pin<&Self>) {} fn with_lifetime<'a>(self: &'a Self) {} fn nested_pin(self: Pin<Arc<Self>>) {} } struct S; impl TraitMethods for S {} let t: Box<dyn TraitMethods> = Box::new(S); } ``` ``` #![allow(unused)] fn main() { // This trait is object-safe, but these methods cannot be dispatched on a trait object. trait NonDispatchable { // Non-methods cannot be dispatched. fn foo() where Self: Sized {} // Self type isn't known until runtime. fn returns(&self) -> Self where Self: Sized; // `other` may be a different concrete type of the receiver. fn param(&self, other: Self) where Self: Sized {} // Generics are not compatible with vtables. fn typed<T>(&self, x: T) where Self: Sized {} } struct S; impl NonDispatchable for S { fn returns(&self) -> Self where Self: Sized { S } } let obj: Box<dyn NonDispatchable> = Box::new(S); obj.returns(); // ERROR: cannot call with Self return obj.param(S); // ERROR: cannot call with Self parameter obj.typed(1); // ERROR: cannot call with generic type } ``` ``` #![allow(unused)] fn main() { use std::rc::Rc; // Examples of non-object safe traits. trait NotObjectSafe { const CONST: i32 = 1; // ERROR: cannot have associated const fn foo() {} // ERROR: associated function without Sized fn returns(&self) -> Self; // ERROR: Self in return type fn typed<T>(&self, x: T) {} // ERROR: has generic type parameters fn nested(self: Rc<Box<Self>>) {} // ERROR: nested receiver not yet supported } struct S; impl NotObjectSafe for S { fn returns(&self) -> Self { S } } let obj: Box<dyn NotObjectSafe> = Box::new(S); // ERROR } ``` ``` #![allow(unused)] fn main() { // Self: Sized traits are not object-safe. trait TraitWithSize where Self: Sized {} struct S; impl TraitWithSize for S {} let obj: Box<dyn TraitWithSize> = Box::new(S); // ERROR } ``` ``` #![allow(unused)] fn main() { // Not object safe if `Self` is a type argument. trait Super<A> {} trait WithSelf: Super<Self> where Self: Sized {} struct S; impl<A> Super<A> for S {} impl WithSelf for S {} let obj: Box<dyn WithSelf> = Box::new(S); // ERROR: cannot use `Self` type parameter } ``` Supertraits ----------- **Supertraits** are traits that are required to be implemented for a type to implement a specific trait. Furthermore, anywhere a [generic](generics) or [trait object](../types/trait-object) is bounded by a trait, it has access to the associated items of its supertraits. Supertraits are declared by trait bounds on the `Self` type of a trait and transitively the supertraits of the traits declared in those trait bounds. It is an error for a trait to be its own supertrait. The trait with a supertrait is called a **subtrait** of its supertrait. The following is an example of declaring `Shape` to be a supertrait of `Circle`. ``` #![allow(unused)] fn main() { trait Shape { fn area(&self) -> f64; } trait Circle : Shape { fn radius(&self) -> f64; } } ``` And the following is the same example, except using [where clauses](generics#where-clauses). ``` #![allow(unused)] fn main() { trait Shape { fn area(&self) -> f64; } trait Circle where Self: Shape { fn radius(&self) -> f64; } } ``` This next example gives `radius` a default implementation using the `area` function from `Shape`. ``` #![allow(unused)] fn main() { trait Shape { fn area(&self) -> f64; } trait Circle where Self: Shape { fn radius(&self) -> f64 { // A = pi * r^2 // so algebraically, // r = sqrt(A / pi) (self.area() /std::f64::consts::PI).sqrt() } } } ``` This next example calls a supertrait method on a generic parameter. ``` #![allow(unused)] fn main() { trait Shape { fn area(&self) -> f64; } trait Circle : Shape { fn radius(&self) -> f64; } fn print_area_and_radius<C: Circle>(c: C) { // Here we call the area method from the supertrait `Shape` of `Circle`. println!("Area: {}", c.area()); println!("Radius: {}", c.radius()); } } ``` Similarly, here is an example of calling supertrait methods on trait objects. ``` #![allow(unused)] fn main() { trait Shape { fn area(&self) -> f64; } trait Circle : Shape { fn radius(&self) -> f64; } struct UnitCircle; impl Shape for UnitCircle { fn area(&self) -> f64 { std::f64::consts::PI } } impl Circle for UnitCircle { fn radius(&self) -> f64 { 1.0 } } let circle = UnitCircle; let circle = Box::new(circle) as Box<dyn Circle>; let nonsense = circle.radius() * circle.area(); } ``` Unsafe traits ------------- Traits items that begin with the `unsafe` keyword indicate that *implementing* the trait may be [unsafe](../unsafety). It is safe to use a correctly implemented unsafe trait. The [trait implementation](implementations#trait-implementations) must also begin with the `unsafe` keyword. [`Sync`](../special-types-and-traits#sync) and [`Send`](../special-types-and-traits#send) are examples of unsafe traits. Parameter patterns ------------------ Function or method declarations without a body only allow [IDENTIFIER](../identifiers) or `_` [wild card](../patterns#wildcard-pattern) patterns. `mut` [IDENTIFIER](../identifiers) is currently allowed, but it is deprecated and will become a hard error in the future. In the 2015 edition, the pattern for a trait function or method parameter is optional: ``` #![allow(unused)] fn main() { // 2015 Edition trait T { fn f(i32); // Parameter identifiers are not required. } } ``` The kinds of patterns for parameters is limited to one of the following: * [IDENTIFIER](../identifiers) * `mut` [IDENTIFIER](../identifiers) * [`_`](../patterns#wildcard-pattern) * `&` [IDENTIFIER](../identifiers) * `&&` [IDENTIFIER](../identifiers) Beginning in the 2018 edition, function or method parameter patterns are no longer optional. Also, all irrefutable patterns are allowed as long as there is a body. Without a body, the limitations listed above are still in effect. ``` #![allow(unused)] fn main() { trait T { fn f1((a, b): (i32, i32)) {} fn f2(_: (i32, i32)); // Cannot use tuple pattern without a body. } } ``` Item visibility --------------- Trait items syntactically allow a [*Visibility*](../visibility-and-privacy) annotation, but this is rejected when the trait is validated. This allows items to be parsed with a unified syntax across different contexts where they are used. As an example, an empty `vis` macro fragment specifier can be used for trait items, where the macro rule may be used in other situations where visibility is allowed. ``` macro_rules! create_method { ($vis:vis $name:ident) => { $vis fn $name(&self) {} }; } trait T1 { // Empty `vis` is allowed. create_method! { method_of_t1 } } struct S; impl S { // Visibility is allowed here. create_method! { pub method_of_s } } impl T1 for S {} fn main() { let s = S; s.method_of_t1(); s.method_of_s(); } ```
programming_docs
rust Use declarations Use declarations ================ > **Syntax:** > *UseDeclaration* : > `use` *UseTree* `;` > > *UseTree* : > ([*SimplePath*](../paths#simple-paths)? `::`)? `*` > | ([*SimplePath*](../paths#simple-paths)? `::`)? `{` (*UseTree* ( `,` *UseTree* )\* `,`?)? `}` > | [*SimplePath*](../paths#simple-paths) ( `as` ( [IDENTIFIER](../identifiers) | `_` ) )? > > A *use declaration* creates one or more local name bindings synonymous with some other [path](../paths). Usually a `use` declaration is used to shorten the path required to refer to a module item. These declarations may appear in <modules> and [blocks](../expressions/block-expr), usually at the top. Use declarations support a number of convenient shortcuts: * Simultaneously binding a list of paths with a common prefix, using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};` * Simultaneously binding a list of paths with a common prefix and their common parent module, using the `self` keyword, such as `use a::b::{self, c, d::e};` * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`. This can also be used with the last two features: `use a::b::{self as ab, c as abc}`. * Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`. * Nesting groups of the previous features multiple times, such as `use a::b::{self as ab, c, d::{*, e::f}};` An example of `use` declarations: ``` use std::collections::hash_map::{self, HashMap}; fn foo<T>(_: T){} fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){} fn main() { // use declarations can also exist inside of functions use std::option::Option::{Some, None}; // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64), // std::option::Option::None]);' foo(vec![Some(1.0f64), None]); // Both `hash_map` and `HashMap` are in scope. let map1 = HashMap::new(); let map2 = hash_map::HashMap::new(); bar(map1, map2); } ``` `use` Visibility ----------------- Like items, `use` declarations are private to the containing module, by default. Also like items, a `use` declaration can be public, if qualified by the `pub` keyword. Such a `use` declaration serves to *re-export* a name. A public `use` declaration can therefore *redirect* some public name to a different target definition: even a definition with a private canonical path, inside a different module. If a sequence of such redirections form a cycle or cannot be resolved unambiguously, they represent a compile-time error. An example of re-exporting: ``` mod quux { pub use self::foo::{bar, baz}; pub mod foo { pub fn bar() {} pub fn baz() {} } } fn main() { quux::bar(); quux::baz(); } ``` In this example, the module `quux` re-exports two public names defined in `foo`. `use` Paths ------------ > **Note**: This section is incomplete. > > Some examples of what will and will not work for `use` items: ``` #![allow(unused_imports)] use std::path::{self, Path, PathBuf}; // good: std is a crate name use crate::foo::baz::foobaz; // good: foo is at the root of the crate mod foo { pub mod example { pub mod iter {} } use crate::foo::example::iter; // good: foo is at crate root // use example::iter; // bad in 2015 edition: relative paths are not allowed without `self`; good in 2018 edition use self::baz::foobaz; // good: self refers to module 'foo' use crate::foo::bar::foobar; // good: foo is at crate root pub mod bar { pub fn foobar() { } } pub mod baz { use super::bar::foobar; // good: super refers to module 'foo' pub fn foobaz() { } } } fn main() {} ``` > **Edition Differences**: In the 2015 edition, `use` paths also allow accessing items in the crate root. Using the example above, the following `use` paths work in 2015 but not 2018: > > > ``` > mod foo { > pub mod example { pub mod iter {} } > pub mod baz { pub fn foobaz() {} } > } > use foo::example::iter; > use ::foo::baz::foobaz; > fn main() {} > > ``` > The 2015 edition does not allow use declarations to reference the [extern prelude](../names/preludes#extern-prelude). Thus [`extern crate`](extern-crates) declarations are still required in 2015 to reference an external crate in a use declaration. Beginning with the 2018 edition, use declarations can specify an external crate dependency the same way `extern crate` can. > > In the 2018 edition, if an in-scope item has the same name as an external crate, then `use` of that crate name requires a leading `::` to unambiguously select the crate name. This is to retain compatibility with potential future changes. > > > ``` > // use std::fs; // Error, this is ambiguous. > use ::std::fs; // Imports from the `std` crate, not the module below. > use self::std::fs as self_fs; // Imports the module below. > > mod std { > pub mod fs {} > } > fn main() {} > > ``` > Underscore Imports ------------------ Items can be imported without binding to a name by using an underscore with the form `use path as _`. This is particularly useful to import a trait so that its methods may be used without importing the trait's symbol, for example if the trait's symbol may conflict with another symbol. Another example is to link an external crate without importing its name. Asterisk glob imports will import items imported with `_` in their unnameable form. ``` mod foo { pub trait Zoo { fn zoo(&self) {} } impl<T> Zoo for T {} } use self::foo::Zoo as _; struct Zoo; // Underscore import avoids name conflict with this item. fn main() { let z = Zoo; z.zoo(); } ``` The unique, unnameable symbols are created after macro expansion so that macros may safely emit multiple references to `_` imports. For example, the following should not produce an error: ``` #![allow(unused)] fn main() { macro_rules! m { ($item: item) => { $item $item } } m!(use std as _;); // This expands to: // use std as _; // use std as _; } ``` rust Type aliases Type aliases ============ > **Syntax** > *TypeAlias* : > `type` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? ( `:` [*TypeParamBounds*](../trait-bounds) )? [*WhereClause*](generics#where-clauses)? ( `=` [*Type*](../types#type-expressions) )? `;` > > A *type alias* defines a new name for an existing [type](../types). Type aliases are declared with the keyword `type`. Every value has a single, specific type, but may implement several different traits, or be compatible with several different type constraints. For example, the following defines the type `Point` as a synonym for the type `(u8, u8)`, the type of pairs of unsigned 8 bit integers: ``` #![allow(unused)] fn main() { type Point = (u8, u8); let p: Point = (41, 68); } ``` A type alias to a tuple-struct or unit-struct cannot be used to qualify that type's constructor: ``` #![allow(unused)] fn main() { struct MyStruct(u32); use MyStruct as UseAlias; type TypeAlias = MyStruct; let _ = UseAlias(5); // OK let _ = TypeAlias(5); // Doesn't work } ``` A type alias without the [*Type*](../types#type-expressions) specification may only appear as an [associated type](associated-items#associated-types) in a [trait](traits). A type alias with [*TypeParamBounds*](../trait-bounds) may only specified when used as an [associated type](associated-items#associated-types) in a [trait](traits). ramda Ramda Ramda ===== ### \_\_ Added in v0.6.0 A special placeholder value used to specify "gaps" within curried functions, allowing partial application of any combination of arguments, regardless of their positions. If `g` is a curried ternary function and `_` is `R.__`, the following are equivalent: * `g(1, 2, 3)` * `g(_, 2, 3)(1)` * `g(_, _, 3)(1)(2)` * `g(_, _, 3)(1, 2)` * `g(_, 2, _)(1, 3)` * `g(_, 2)(1)(3)` * `g(_, 2)(1, 3)` * `g(_, 2)(_, 3)(1)` ``` const greet = R.replace('{name}', R.__, 'Hello, {name}!'); greet('Alice'); //=> 'Hello, Alice!' ``` ### add Added in v0.1.0 ``` Number → Number → Number ``` #### Parameters * `a` * `b` #### Returns * Number Adds two values. See also `[subtract](#subtract)`. ``` R.add(2, 3); //=> 5 R.add(7)(10); //=> 17 ``` ### addIndex Added in v0.15.0 ``` ((a … → b) … → [a] → *) → ((a …, Int, [a] → b) … → [a] → *) ``` #### Parameters * `fn` A list iteration function that does not pass index or list to its callback #### Returns * function An altered list iteration function that passes (item, index, list) to its callback Creates a new list iteration function from an existing one by adding two new parameters to its callback function: the current index, and the entire list. This would turn, for instance, [`R.map`](#map) function into one that more closely resembles `Array.prototype.map`. Note that this will only work for functions in which the iteration callback function is the first parameter, and where the list is the last parameter. (This latter might be unimportant if the list parameter is not used.) ``` const mapIndexed = R.addIndex(R.map); mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']); //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] ``` ### adjust Added in v0.14.0 ``` Number → (a → a) → [a] → [a] ``` #### Parameters * `idx` The index. * `fn` The function to apply. * `list` An array-like object whose value at the supplied index will be replaced. #### Returns * Array A copy of the supplied array-like object with the element at index `idx` replaced with the value returned by applying `fn` to the existing element. Applies a function to the value at the given index of an array, returning a new copy of the array with the element at the given index replaced with the result of the function application. See also `[update](#update)`. ``` R.adjust(1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'B', 'c', 'd'] R.adjust(-1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c', 'D'] ``` ### all Added in v0.1.0 ``` (a → Boolean) → [a] → Boolean ``` #### Parameters * `fn` The predicate function. * `list` The array to consider. #### Returns * Boolean `true` if the predicate is satisfied by every element, `false` otherwise. Returns `true` if all elements of the list match the predicate, `false` if there are any that don't. Dispatches to the `all` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[any](#any)`, `[none](#none)`, `[transduce](#transduce)`. ``` const equals3 = R.equals(3); R.all(equals3)([3, 3, 3, 3]); //=> true R.all(equals3)([3, 3, 1, 3]); //=> false ``` ### allPass Added in v0.9.0 ``` [(*… → Boolean)] → (*… → Boolean) ``` #### Parameters * `predicates` An array of predicates to check #### Returns * function The combined predicate Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments. The function returned is a curried function whose arity matches that of the highest-arity predicate. See also `[anyPass](#anyPass)`. ``` const isQueen = R.propEq('rank', 'Q'); const isSpade = R.propEq('suit', '♠︎'); const isQueenOfSpades = R.allPass([isQueen, isSpade]); isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true ``` ### always Added in v0.1.0 ``` a → (* → a) ``` #### Parameters * `val` The value to wrap in a function #### Returns * function A Function :: \* -> val. Returns a function that always returns the given value. Note that for non-primitives the value returned is a reference to the original value. This function is known as `const`, `constant`, or `K` (for K combinator) in other languages and libraries. ``` const t = R.always('Tee'); t(); //=> 'Tee' ``` ### and Added in v0.1.0 ``` a → b → a | b ``` #### Parameters * `a` * `b` #### Returns * Any the first argument if it is falsy, otherwise the second argument. Returns `true` if both arguments are `true`; `false` otherwise. See also `[both](#both)`, `[xor](#xor)`. ``` R.and(true, true); //=> true R.and(true, false); //=> false R.and(false, true); //=> false R.and(false, false); //=> false ``` ### andThen Added in v0.27.0 ``` (a → b) → (Promise e a) → (Promise e b) ``` `(a → (Promise e b)) → (Promise e a) → (Promise e b)` #### Parameters * `onSuccess` The function to apply. Can return a value or a promise of a value. * `p` #### Returns * Promise The result of calling `p.then(onSuccess)` Returns the result of applying the onSuccess function to the value inside a successfully resolved promise. This is useful for working with promises inside function compositions. See also `[otherwise](#otherwise)`. ``` var makeQuery = (email) => ({ query: { email }}); //getMemberName :: String -> Promise ({firstName, lastName}) var getMemberName = R.pipe( makeQuery, fetchMember, R.andThen(R.pick(['firstName', 'lastName'])) ); ``` ### any Added in v0.1.0 ``` (a → Boolean) → [a] → Boolean ``` #### Parameters * `fn` The predicate function. * `list` The array to consider. #### Returns * Boolean `true` if the predicate is satisfied by at least one element, `false` otherwise. Returns `true` if at least one of the elements of the list match the predicate, `false` otherwise. Dispatches to the `any` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[all](#all)`, `[none](#none)`, `[transduce](#transduce)`. ``` const lessThan0 = R.flip(R.lt)(0); const lessThan2 = R.flip(R.lt)(2); R.any(lessThan0)([1, 2]); //=> false R.any(lessThan2)([1, 2]); //=> true ``` ### anyPass Added in v0.9.0 ``` [(*… → Boolean)] → (*… → Boolean) ``` #### Parameters * `predicates` An array of predicates to check #### Returns * function The combined predicate Takes a list of predicates and returns a predicate that returns true for a given list of arguments if at least one of the provided predicates is satisfied by those arguments. The function returned is a curried function whose arity matches that of the highest-arity predicate. See also `[allPass](#allPass)`. ``` const isClub = R.propEq('suit', '♣'); const isSpade = R.propEq('suit', '♠'); const isBlackCard = R.anyPass([isClub, isSpade]); isBlackCard({rank: '10', suit: '♣'}); //=> true isBlackCard({rank: 'Q', suit: '♠'}); //=> true isBlackCard({rank: 'Q', suit: '♦'}); //=> false ``` ### ap Added in v0.3.0 ``` [a → b] → [a] → [b] ``` `Apply f => f (a → b) → f a → f b` `(r → a → b) → (r → a) → (r → b)` #### Parameters * `applyF` * `applyX` #### Returns * \* ap applies a list of functions to a list of values. Dispatches to the `ap` method of the second argument, if present. Also treats curried functions as applicatives. ``` R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] R.ap([R.concat('tasty '), R.toUpper], ['pizza', 'salad']); //=> ["tasty pizza", "tasty salad", "PIZZA", "SALAD"] // R.ap can also be used as S combinator // when only two functions are passed R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA' ``` ### aperture Added in v0.12.0 ``` Number → [a] → [[a]] ``` #### Parameters * `n` The size of the tuples to create * `list` The list to split into `n`-length tuples #### Returns * Array The resulting list of `n`-length tuples Returns a new list, composed of n-tuples of consecutive elements. If `n` is greater than the length of the list, an empty list is returned. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] R.aperture(7, [1, 2, 3, 4, 5]); //=> [] ``` ### append Added in v0.1.0 ``` a → [a] → [a] ``` #### Parameters * `el` The element to add to the end of the new list. * `list` The list of elements to add a new item to. list. #### Returns * Array A new list containing the elements of the old list followed by `el`. Returns a new list containing the contents of the given list, followed by the given element. See also `[prepend](#prepend)`. ``` R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] R.append('tests', []); //=> ['tests'] R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] ``` ### apply Added in v0.7.0 ``` (*… → a) → [*] → a ``` #### Parameters * `fn` The function which will be called with `args` * `args` The arguments to call `fn` with #### Returns * \* result The result, equivalent to `fn(...args)` Applies function `fn` to the argument list `args`. This is useful for creating a fixed-arity function from a variadic function. `fn` should be a bound function if context is significant. See also `[call](#call)`, `[unapply](#unapply)`. ``` const nums = [1, 2, 3, -99, 42, 6, 7]; R.apply(Math.max, nums); //=> 42 ``` ### applySpec Added in v0.20.0 ``` {k: ((a, b, …, m) → v)} → ((a, b, …, m) → {k: v}) ``` #### Parameters * `spec` an object recursively mapping properties to functions for producing the values for these properties. #### Returns * function A function that returns an object of the same structure as `spec', with each property set to the value returned by calling its associated function with the supplied arguments. Given a spec object recursively mapping properties to functions, creates a function producing an object of the same structure, by mapping each property to the result of calling its associated function with the supplied arguments. See also `[converge](#converge)`, `[juxt](#juxt)`. ``` const getMetrics = R.applySpec({ sum: R.add, nested: { mul: R.multiply } }); getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } ``` ### applyTo Added in v0.25.0 ``` a → (a → b) → b ``` #### Parameters * `x` The value * `f` The function to apply #### Returns * \* The result of applying `f` to `x` Takes a value and applies a function to it. This function is also known as the `thrush` combinator. ``` const t42 = R.applyTo(42); t42(R.identity); //=> 42 t42(R.add(1)); //=> 43 ``` ### ascend Added in v0.23.0 ``` Ord b => (a → b) → a → a → Number ``` #### Parameters * `fn` A function of arity one that returns a value that can be compared * `a` The first item to be compared. * `b` The second item to be compared. #### Returns * Number `-1` if fn(a) < fn(b), `1` if fn(b) < fn(a), otherwise `0` Makes an ascending comparator function out of a function that returns a value that can be compared with `<` and `>`. See also `[descend](#descend)`. ``` const byAge = R.ascend(R.prop('age')); const people = [ { name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }, { name: 'Mikhail', age: 62 }, ]; const peopleByYoungestFirst = R.sort(byAge, people); //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }] ``` ### assoc Added in v0.8.0 ``` String → a → {k: v} → {k: v} ``` #### Parameters * `prop` The property name to set * `val` The new value * `obj` The object to clone #### Returns * Object A new object equivalent to the original except for the changed property. Makes a shallow clone of an object, setting or overriding the specified property with the given value. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference. See also `[dissoc](#dissoc)`, `[pick](#pick)`. ``` R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} ``` ### assocPath Added in v0.8.0 ``` [Idx] → a → {a} → {a} ``` `Idx = String | Int` #### Parameters * `path` the path to set * `val` The new value * `obj` The object to clone #### Returns * Object A new object equivalent to the original except along the specified path. Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and placing the specific value at the tail end of that path. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference. See also `[dissocPath](#dissocPath)`. ``` R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} // Any missing or non-object keys in path will be overridden R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}} ``` ### binary Added in v0.2.0 ``` (* → c) → (a, b → c) ``` #### Parameters * `fn` The function to wrap. #### Returns * function A new function wrapping `fn`. The new function is guaranteed to be of arity 2. Wraps a function of any arity (including nullary) in a function that accepts exactly 2 parameters. Any extraneous parameters will not be passed to the supplied function. See also `[nAry](#nAry)`, `[unary](#unary)`. ``` const takesThreeArgs = function(a, b, c) { return [a, b, c]; }; takesThreeArgs.length; //=> 3 takesThreeArgs(1, 2, 3); //=> [1, 2, 3] const takesTwoArgs = R.binary(takesThreeArgs); takesTwoArgs.length; //=> 2 // Only 2 arguments are passed to the wrapped function takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] ``` ### bind Added in v0.6.0 ``` (* → *) → {*} → (* → *) ``` #### Parameters * `fn` The function to bind to context * `thisObj` The context to bind `fn` to #### Returns * function A function that will execute in the context of `thisObj`. Creates a function that is bound to a context. Note: `R.bind` does not provide the additional argument-binding capabilities of [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). See also `[partial](#partial)`. ``` const log = R.bind(console.log, console); R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3} // logs {a: 2} ``` ### both Added in v0.12.0 ``` (*… → Boolean) → (*… → Boolean) → (*… → Boolean) ``` #### Parameters * `f` A predicate * `g` Another predicate #### Returns * function a function that applies its arguments to `f` and `g` and `&&`s their outputs together. A function which calls the two provided functions and returns the `&&` of the results. It returns the result of the first function if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning that the second function will not be invoked if the first returns a false-y value. In addition to functions, `R.both` also accepts any fantasy-land compatible applicative functor. See also `[and](#and)`. ``` const gt10 = R.gt(R.__, 10) const lt20 = R.lt(R.__, 20) const f = R.both(gt10, lt20); f(15); //=> true f(30); //=> false R.both(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(false) R.both([false, false, 'a'], [11]); //=> [false, false, 11] ``` ### call Added in v0.9.0 ``` (*… → a),*… → a ``` #### Parameters * `fn` The function to apply to the remaining arguments. * `args` Any number of positional arguments. #### Returns * \* Returns the result of calling its first argument with the remaining arguments. This is occasionally useful as a converging function for [`R.converge`](#converge): the first branch can produce a function while the remaining branches produce values to be passed to that function as its arguments. See also `[apply](#apply)`. ``` R.call(R.add, 1, 2); //=> 3 const indentN = R.pipe(R.repeat(' '), R.join(''), R.replace(/^(?!$)/gm)); const format = R.converge(R.call, [ R.pipe(R.prop('indent'), indentN), R.prop('value') ]); format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' ``` ### chain Added in v0.3.0 ``` Chain m => (a → m b) → m a → m b ``` #### Parameters * `fn` The function to map with * `list` The list to map over #### Returns * Array The result of flat-mapping `list` with `fn` `chain` maps a function over a list and concatenates the results. `chain` is also known as `flatMap` in some libraries. Dispatches to the `chain` method of the second argument, if present, according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain). If second argument is a function, `chain(f, g)(x)` is equivalent to `f(g(x), x)`. Acts as a transducer if a transformer is given in list position. ``` const duplicate = n => [n, n]; R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1] ``` ### clamp Added in v0.20.0 ``` Ord a => a → a → a → a ``` #### Parameters * `minimum` The lower limit of the clamp (inclusive) * `maximum` The upper limit of the clamp (inclusive) * `value` Value to be clamped #### Returns * Number Returns `minimum` when `val < minimum`, `maximum` when `val > maximum`, returns `val` otherwise Restricts a number to be within a range. Also works for other ordered types such as Strings and Dates. ``` R.clamp(1, 10, -5) // => 1 R.clamp(1, 10, 15) // => 10 R.clamp(1, 10, 4) // => 4 ``` ### clone Added in v0.1.0 ``` {*} → {*} ``` #### Parameters * `value` The object or array to clone #### Returns * \* A deeply cloned copy of `val` Creates a deep copy of the value which may contain (nested) `Array`s and `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are assigned by reference rather than copied Dispatches to a `clone` method if present. ``` const objects = [{}, {}, {}]; const objectsClone = R.clone(objects); objects === objectsClone; //=> false objects[0] === objectsClone[0]; //=> false ``` ### comparator Added in v0.1.0 ``` ((a, b) → Boolean) → ((a, b) → Number) ``` #### Parameters * `pred` A predicate function of arity two which will return `true` if the first argument is less than the second, `false` otherwise #### Returns * function A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0` Makes a comparator function out of a function that reports whether the first element is less than the second. ``` const byAge = R.comparator((a, b) => a.age < b.age); const people = [ { name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }, { name: 'Mikhail', age: 62 }, ]; const peopleByIncreasingAge = R.sort(byAge, people); //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }] ``` ### complement Added in v0.12.0 ``` (*… → *) → (*… → Boolean) ``` #### Parameters * `f` #### Returns * function Takes a function `f` and returns a function `g` such that if called with the same arguments when `f` returns a "truthy" value, `g` returns `false` and when `f` returns a "falsy" value `g` returns `true`. `R.complement` may be applied to any functor See also `[not](#not)`. ``` const isNotNil = R.complement(R.isNil); isNil(null); //=> true isNotNil(null); //=> false isNil(7); //=> false isNotNil(7); //=> true ``` ### compose Added in v0.1.0 ``` ((y → z), (x → y), …, (o → p), ((a, b, …, n) → o)) → ((a, b, …, n) → z) ``` #### Parameters * `...functions` The functions to compose #### Returns * function Performs right-to-left function composition. The last argument may have any arity; the remaining arguments must be unary. **Note:** The result of compose is not automatically curried. See also `[pipe](#pipe)`. ``` const classyGreeting = (firstName, lastName) => "The name's " + lastName + ", " + firstName + " " + lastName const yellGreeting = R.compose(R.toUpper, classyGreeting); yellGreeting('James', 'Bond'); //=> "THE NAME'S BOND, JAMES BOND" R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7 ``` ### composeK Added in v0.16.0 Deprecated since v0.26.0 `Chain m => ((y → m z), (x → m y), …, (a → m b)) → (a → m z)` #### Parameters * `...functions` The functions to compose #### Returns * function Returns the right-to-left Kleisli composition of the provided functions, each of which must return a value of a type supported by [`chain`](#chain). `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), f)`. See also `[pipeK](#pipeK)`. ``` // get :: String -> Object -> Maybe * const get = R.curry((propName, obj) => Maybe(obj[propName])) // getStateCode :: Maybe String -> Maybe String const getStateCode = R.composeK( R.compose(Maybe.of, R.toUpper), get('state'), get('address'), get('user'), ); getStateCode({"user":{"address":{"state":"ny"}}}); //=> Maybe.Just("NY") getStateCode({}); //=> Maybe.Nothing() ``` ### composeP Added in v0.10.0 Deprecated since v0.26.0 `((y → Promise z), (x → Promise y), …, (a → Promise b)) → (a → Promise z)` #### Parameters * `functions` The functions to compose #### Returns * function Performs right-to-left composition of one or more Promise-returning functions. The last arguments may have any arity; the remaining arguments must be unary. See also `[pipeP](#pipeP)`. ``` const db = { users: { JOE: { name: 'Joe', followers: ['STEVE', 'SUZY'] } } } // We'll pretend to do a db lookup which returns a promise const lookupUser = (userId) => Promise.resolve(db.users[userId]) const lookupFollowers = (user) => Promise.resolve(user.followers) lookupUser('JOE').then(lookupFollowers) // followersForUser :: String -> Promise [UserId] const followersForUser = R.composeP(lookupFollowers, lookupUser); followersForUser('JOE').then(followers => console.log('Followers:', followers)) // Followers: ["STEVE","SUZY"] ``` ### composeWith Added in v0.26.0 ``` ((* → *), [(y → z), (x → y), …, (o → p), ((a, b, …, n) → o)]) → ((a, b, …, n) → z) ``` #### Parameters * `...functions` The functions to compose #### Returns * function Performs right-to-left function composition using transforming function. The last argument may have any arity; the remaining arguments must be unary. **Note:** The result of compose is not automatically curried. Transforming function is not used on the last argument. See also `[compose](#compose)`, `[pipeWith](#pipeWith)`. ``` const composeWhileNotNil = R.composeWith((f, res) => R.isNil(res) ? res : f(res)); composeWhileNotNil([R.inc, R.prop('age')])({age: 1}) //=> 2 composeWhileNotNil([R.inc, R.prop('age')])({}) //=> undefined ``` ### concat Added in v0.1.0 ``` [a] → [a] → [a] ``` `String → String → String` #### Parameters * `firstList` The first list * `secondList` The second list #### Returns * Array A list consisting of the elements of `firstList` followed by the elements of `secondList`. Returns the result of concatenating the given lists or strings. Note: `R.concat` expects both arguments to be of the same type, unlike the native `Array.prototype.concat` method. It will throw an error if you `concat` an Array with a non-Array value. Dispatches to the `concat` method of the first argument, if present. Can also concatenate two members of a [fantasy-land compatible semigroup](https://github.com/fantasyland/fantasy-land#semigroup). ``` R.concat('ABC', 'DEF'); // 'ABCDEF' R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] R.concat([], []); //=> [] ``` ### cond Added in v0.6.0 ``` [[(*… → Boolean),(*… → *)]] → (*… → *) ``` #### Parameters * `pairs` A list of [predicate, transformer] #### Returns * function Returns a function, `fn`, which encapsulates `if/else, if/else, ...` logic. `R.cond` takes a list of [predicate, transformer] pairs. All of the arguments to `fn` are applied to each of the predicates in turn until one returns a "truthy" value, at which point `fn` returns the result of applying its arguments to the corresponding transformer. If none of the predicates matches, `fn` returns undefined. See also `[ifElse](#ifElse)`, `[unless](#unless)`, `[when](#when)`. ``` const fn = R.cond([ [R.equals(0), R.always('water freezes at 0°C')], [R.equals(100), R.always('water boils at 100°C')], [R.T, temp => 'nothing special happens at ' + temp + '°C'] ]); fn(0); //=> 'water freezes at 0°C' fn(50); //=> 'nothing special happens at 50°C' fn(100); //=> 'water boils at 100°C' ``` ### construct Added in v0.1.0 ``` (* → {*}) → (* → {*}) ``` #### Parameters * `fn` The constructor function to wrap. #### Returns * function A wrapped, curried constructor function. Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. See also `[invoker](#invoker)`. ``` // Constructor function function Animal(kind) { this.kind = kind; }; Animal.prototype.sighting = function() { return "It's a " + this.kind + "!"; } const AnimalConstructor = R.construct(Animal) // Notice we no longer need the 'new' keyword: AnimalConstructor('Pig'); //=> {"kind": "Pig", "sighting": function (){...}}; const animalTypes = ["Lion", "Tiger", "Bear"]; const animalSighting = R.invoker(0, 'sighting'); const sightNewAnimal = R.compose(animalSighting, AnimalConstructor); R.map(sightNewAnimal, animalTypes); //=> ["It's a Lion!", "It's a Tiger!", "It's a Bear!"] ``` ### constructN Added in v0.4.0 ``` Number → (* → {*}) → (* → {*}) ``` #### Parameters * `n` The arity of the constructor function. * `Fn` The constructor function to wrap. #### Returns * function A wrapped, curried constructor function. Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. The arity of the function returned is specified to allow using variadic constructor functions. ``` // Variadic Constructor function function Salad() { this.ingredients = arguments; } Salad.prototype.recipe = function() { const instructions = R.map(ingredient => 'Add a dollop of ' + ingredient, this.ingredients); return R.join('\n', instructions); }; const ThreeLayerSalad = R.constructN(3, Salad); // Notice we no longer need the 'new' keyword, and the constructor is curried for 3 arguments. const salad = ThreeLayerSalad('Mayonnaise')('Potato Chips')('Ketchup'); console.log(salad.recipe()); // Add a dollop of Mayonnaise // Add a dollop of Potato Chips // Add a dollop of Ketchup ``` ### contains Added in v0.1.0 Deprecated since v0.26.0 `a → [a] → Boolean` #### Parameters * `a` The item to compare against. * `list` The array to consider. #### Returns * Boolean `true` if an equivalent item is in the list, `false` otherwise. Returns `true` if the specified value is equal, in [`R.equals`](#equals) terms, to at least one element of the given list; `false` otherwise. Works also with strings. See also `[includes](#includes)`. ``` R.contains(3, [1, 2, 3]); //=> true R.contains(4, [1, 2, 3]); //=> false R.contains({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true R.contains([42], [[42]]); //=> true R.contains('ba', 'banana'); //=>true ``` ### converge Added in v0.4.2 ``` ((x1, x2, …) → z) → [((a, b, …) → x1), ((a, b, …) → x2), …] → (a → b → … → z) ``` #### Parameters * `after` A function. `after` will be invoked with the return values of `fn1` and `fn2` as its arguments. * `functions` A list of functions. #### Returns * function A new function. Accepts a converging function and a list of branching functions and returns a new function. The arity of the new function is the same as the arity of the longest branching function. When invoked, this new function is applied to some arguments, and each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value. See also `[useWith](#useWith)`. ``` const average = R.converge(R.divide, [R.sum, R.length]) average([1, 2, 3, 4, 5, 6, 7]) //=> 4 const strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower]) strangeConcat("Yodel") //=> "YODELyodel" ``` ### countBy Added in v0.1.0 ``` (a → String) → [a] → {*} ``` #### Parameters * `fn` The function used to map values to keys. * `list` The list to count elements from. #### Returns * Object An object mapping keys to number of occurrences in the list. Counts the elements of a list according to how many match each value of a key generated by the supplied function. Returns an object mapping the keys produced by `fn` to the number of occurrences in the list. Note that all keys are coerced to strings because of how JavaScript objects work. Acts as a transducer if a transformer is given in list position. ``` const numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} const letters = ['a', 'b', 'A', 'a', 'B', 'c']; R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1} ``` ### curry Added in v0.1.0 ``` (* → a) → (* → a) ``` #### Parameters * `fn` The function to curry. #### Returns * function A new, curried function. Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. First, its arguments needn't be provided one at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the following are equivalent: * `g(1)(2)(3)` * `g(1)(2, 3)` * `g(1, 2)(3)` * `g(1, 2, 3)` Secondly, the special placeholder value [`R.__`](#__) may be used to specify "gaps", allowing partial application of any combination of arguments, regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), the following are equivalent: * `g(1, 2, 3)` * `g(_, 2, 3)(1)` * `g(_, _, 3)(1)(2)` * `g(_, _, 3)(1, 2)` * `g(_, 2)(1)(3)` * `g(_, 2)(1, 3)` * `g(_, 2)(_, 3)(1)` See also `[curryN](#curryN)`, `[partial](#partial)`. ``` const addFourNumbers = (a, b, c, d) => a + b + c + d; const curriedAddFourNumbers = R.curry(addFourNumbers); const f = curriedAddFourNumbers(1, 2); const g = f(3); g(4); //=> 10 ``` ### curryN Added in v0.5.0 ``` Number → (* → a) → (* → a) ``` #### Parameters * `length` The arity for the returned function. * `fn` The function to curry. #### Returns * function A new, curried function. Returns a curried equivalent of the provided function, with the specified arity. The curried function has two unusual capabilities. First, its arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the following are equivalent: * `g(1)(2)(3)` * `g(1)(2, 3)` * `g(1, 2)(3)` * `g(1, 2, 3)` Secondly, the special placeholder value [`R.__`](#__) may be used to specify "gaps", allowing partial application of any combination of arguments, regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), the following are equivalent: * `g(1, 2, 3)` * `g(_, 2, 3)(1)` * `g(_, _, 3)(1)(2)` * `g(_, _, 3)(1, 2)` * `g(_, 2)(1)(3)` * `g(_, 2)(1, 3)` * `g(_, 2)(_, 3)(1)` See also `[curry](#curry)`. ``` const sumArgs = (...args) => R.sum(args); const curriedAddFourNumbers = R.curryN(4, sumArgs); const f = curriedAddFourNumbers(1, 2); const g = f(3); g(4); //=> 10 ``` ### dec Added in v0.9.0 ``` Number → Number ``` #### Parameters * `n` #### Returns * Number n - 1 Decrements its argument. See also `[inc](#inc)`. ``` R.dec(42); //=> 41 ``` ### defaultTo Added in v0.10.0 ``` a → b → a | b ``` #### Parameters * `default` The default value. * `val` `val` will be returned instead of `default` unless `val` is `null`, `undefined` or `NaN`. #### Returns * \* The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value Returns the second argument if it is not `null`, `undefined` or `NaN`; otherwise the first argument is returned. ``` const defaultTo42 = R.defaultTo(42); defaultTo42(null); //=> 42 defaultTo42(undefined); //=> 42 defaultTo42(false); //=> false defaultTo42('Ramda'); //=> 'Ramda' // parseInt('string') results in NaN defaultTo42(parseInt('string')); //=> 42 ``` ### descend Added in v0.23.0 ``` Ord b => (a → b) → a → a → Number ``` #### Parameters * `fn` A function of arity one that returns a value that can be compared * `a` The first item to be compared. * `b` The second item to be compared. #### Returns * Number `-1` if fn(a) > fn(b), `1` if fn(b) > fn(a), otherwise `0` Makes a descending comparator function out of a function that returns a value that can be compared with `<` and `>`. See also `[ascend](#ascend)`. ``` const byAge = R.descend(R.prop('age')); const people = [ { name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }, { name: 'Mikhail', age: 62 }, ]; const peopleByOldestFirst = R.sort(byAge, people); //=> [{ name: 'Peter', age: 78 }, { name: 'Emma', age: 70 }, { name: 'Mikhail', age: 62 }] ``` ### difference Added in v0.1.0 ``` [*] → [*] → [*] ``` #### Parameters * `list1` The first list. * `list2` The second list. #### Returns * Array The elements in `list1` that are not in `list2`. Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Objects and Arrays are compared in terms of value equality, not reference equality. See also `[differenceWith](#differenceWith)`, `[symmetricDifference](#symmetricDifference)`, `[symmetricDifferenceWith](#symmetricDifferenceWith)`, `[without](#without)`. ``` R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] R.difference([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}] ``` ### differenceWith Added in v0.1.0 ``` ((a, a) → Boolean) → [a] → [a] → [a] ``` #### Parameters * `pred` A predicate used to test whether two items are equal. * `list1` The first list. * `list2` The second list. #### Returns * Array The elements in `list1` that are not in `list2`. Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements. See also `[difference](#difference)`, `[symmetricDifference](#symmetricDifference)`, `[symmetricDifferenceWith](#symmetricDifferenceWith)`. ``` const cmp = (x, y) => x.a === y.a; const l1 = [{a: 1}, {a: 2}, {a: 3}]; const l2 = [{a: 3}, {a: 4}]; R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] ``` ### dissoc Added in v0.10.0 ``` String → {k: v} → {k: v} ``` #### Parameters * `prop` The name of the property to dissociate * `obj` The object to clone #### Returns * Object A new object equivalent to the original but without the specified property Returns a new object that does not contain a `prop` property. See also `[assoc](#assoc)`, `[omit](#omit)`. ``` R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} ``` ### dissocPath Added in v0.11.0 ``` [Idx] → {k: v} → {k: v} ``` `Idx = String | Int` #### Parameters * `path` The path to the value to omit * `obj` The object to clone #### Returns * Object A new object without the property at path Makes a shallow clone of an object, omitting the property at the given path. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference. See also `[assocPath](#assocPath)`. ``` R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} ``` ### divide Added in v0.1.0 ``` Number → Number → Number ``` #### Parameters * `a` The first value. * `b` The second value. #### Returns * Number The result of `a / b`. Divides two numbers. Equivalent to `a / b`. See also `[multiply](#multiply)`. ``` R.divide(71, 100); //=> 0.71 const half = R.divide(R.__, 2); half(42); //=> 21 const reciprocal = R.divide(1); reciprocal(4); //=> 0.25 ``` ### drop Added in v0.1.0 ``` Number → [a] → [a] ``` `Number → String → String` #### Parameters * `n` * `list` #### Returns * \* A copy of list without the first `n` elements Returns all but the first `n` elements of the given list, string, or transducer/transformer (or object with a `drop` method). Dispatches to the `drop` method of the second argument, if present. See also `[take](#take)`, `[transduce](#transduce)`, `[dropLast](#dropLast)`, `[dropWhile](#dropWhile)`. ``` R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz'] R.drop(3, ['foo', 'bar', 'baz']); //=> [] R.drop(4, ['foo', 'bar', 'baz']); //=> [] R.drop(3, 'ramda'); //=> 'da' ``` ### dropLast Added in v0.16.0 ``` Number → [a] → [a] ``` `Number → String → String` #### Parameters * `n` The number of elements of `list` to skip. * `list` The list of elements to consider. #### Returns * Array A copy of the list with only the first `list.length - n` elements Returns a list containing all but the last `n` elements of the given `list`. Acts as a transducer if a transformer is given in list position. See also `[takeLast](#takeLast)`, `[drop](#drop)`, `[dropWhile](#dropWhile)`, `[dropLastWhile](#dropLastWhile)`. ``` R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo'] R.dropLast(3, ['foo', 'bar', 'baz']); //=> [] R.dropLast(4, ['foo', 'bar', 'baz']); //=> [] R.dropLast(3, 'ramda'); //=> 'ra' ``` ### dropLastWhile Added in v0.16.0 ``` (a → Boolean) → [a] → [a] ``` `(a → Boolean) → String → String` #### Parameters * `predicate` The function to be called on each element * `xs` The collection to iterate over. #### Returns * Array A new array without any trailing elements that return `falsy` values from the `predicate`. Returns a new list excluding all the tailing elements of a given list which satisfy the supplied predicate function. It passes each value from the right to the supplied predicate function, skipping elements until the predicate function returns a `falsy` value. The predicate function is applied to one argument: *(value)*. Acts as a transducer if a transformer is given in list position. See also `[takeLastWhile](#takeLastWhile)`, `[addIndex](#addIndex)`, `[drop](#drop)`, `[dropWhile](#dropWhile)`. ``` const lteThree = x => x <= 3; R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] R.dropLastWhile(x => x !== 'd' , 'Ramda'); //=> 'Ramd' ``` ### dropRepeats Added in v0.14.0 ``` [a] → [a] ``` #### Parameters * `list` The array to consider. #### Returns * Array `list` without repeating elements. Returns a new list without any consecutively repeating elements. [`R.equals`](#equals) is used to determine equality. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2] ``` ### dropRepeatsWith Added in v0.14.0 ``` ((a, a) → Boolean) → [a] → [a] ``` #### Parameters * `pred` A predicate used to test whether two items are equal. * `list` The array to consider. #### Returns * Array `list` without repeating elements. Returns a new list without any consecutively repeating elements. Equality is determined by applying the supplied predicate to each pair of consecutive elements. The first element in a series of equal elements will be preserved. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` const l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3]; R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3] ``` ### dropWhile Added in v0.9.0 ``` (a → Boolean) → [a] → [a] ``` `(a → Boolean) → String → String` #### Parameters * `fn` The function called per iteration. * `xs` The collection to iterate over. #### Returns * Array A new array. Returns a new list excluding the leading elements of a given list which satisfy the supplied predicate function. It passes each value to the supplied predicate function, skipping elements while the predicate function returns `true`. The predicate function is applied to one argument: *(value)*. Dispatches to the `dropWhile` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[takeWhile](#takeWhile)`, `[transduce](#transduce)`, `[addIndex](#addIndex)`. ``` const lteTwo = x => x <= 2; R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1] R.dropWhile(x => x !== 'd' , 'Ramda'); //=> 'da' ``` ### either Added in v0.12.0 ``` (*… → Boolean) → (*… → Boolean) → (*… → Boolean) ``` #### Parameters * `f` a predicate * `g` another predicate #### Returns * function a function that applies its arguments to `f` and `g` and `||`s their outputs together. A function wrapping calls to the two functions in an `||` operation, returning the result of the first function if it is truth-y and the result of the second function otherwise. Note that this is short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. In addition to functions, `R.either` also accepts any fantasy-land compatible applicative functor. See also `[or](#or)`. ``` const gt10 = x => x > 10; const even = x => x % 2 === 0; const f = R.either(gt10, even); f(101); //=> true f(8); //=> true R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55) R.either([false, false, 'a'], [11]) // => [11, 11, "a"] ``` ### empty Added in v0.3.0 ``` a → a ``` #### Parameters * `x` #### Returns * \* Returns the empty value of its argument's type. Ramda defines the empty value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other types are supported if they define `<Type>.empty`, `<Type>.prototype.empty` or implement the [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid). Dispatches to the `empty` method of the first argument, if present. ``` R.empty(Just(42)); //=> Nothing() R.empty([1, 2, 3]); //=> [] R.empty('unicorns'); //=> '' R.empty({x: 1, y: 2}); //=> {} ``` ### endsWith Added in v0.24.0 ``` [a] → [a] → Boolean ``` `String → String → Boolean` #### Parameters * `suffix` * `list` #### Returns * Boolean Checks if a list ends with the provided sublist. Similarly, checks if a string ends with the provided substring. See also `[startsWith](#startsWith)`. ``` R.endsWith('c', 'abc') //=> true R.endsWith('b', 'abc') //=> false R.endsWith(['c'], ['a', 'b', 'c']) //=> true R.endsWith(['b'], ['a', 'b', 'c']) //=> false ``` ### eqBy Added in v0.18.0 ``` (a → b) → a → a → Boolean ``` #### Parameters * `f` * `x` * `y` #### Returns * Boolean Takes a function and two values in its domain and returns `true` if the values map to the same value in the codomain; `false` otherwise. ``` R.eqBy(Math.abs, 5, -5); //=> true ``` ### eqProps Added in v0.1.0 ``` k → {k: v} → {k: v} → Boolean ``` #### Parameters * `prop` The name of the property to compare * `obj1` * `obj2` #### Returns * Boolean Reports whether two objects have the same value, in [`R.equals`](#equals) terms, for the specified property. Useful as a curried predicate. ``` const o1 = { a: 1, b: 2, c: 3, d: 4 }; const o2 = { a: 10, b: 20, c: 3, d: 40 }; R.eqProps('a', o1, o2); //=> false R.eqProps('c', o1, o2); //=> true ``` ### equals Added in v0.15.0 ``` a → b → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns `true` if its arguments are equivalent, `false` otherwise. Handles cyclical data structures. Dispatches symmetrically to the `equals` methods of both arguments, if present. ``` R.equals(1, 1); //=> true R.equals(1, '1'); //=> false R.equals([1, 2, 3], [1, 2, 3]); //=> true const a = {}; a.v = a; const b = {}; b.v = b; R.equals(a, b); //=> true ``` ### evolve Added in v0.9.0 ``` {k: (v → v)} → {k: v} → {k: v} ``` #### Parameters * `transformations` The object specifying transformation functions to apply to the object. * `object` The object to be transformed. #### Returns * Object The transformed object. Creates a new object by recursively evolving a shallow copy of `object`, according to the `transformation` functions. All non-primitive properties are copied by reference. A `transformation` function will not be invoked if its corresponding key does not exist in the evolved object. ``` const tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; const transformations = { firstName: R.trim, lastName: R.trim, // Will not get invoked. data: {elapsed: R.add(1), remaining: R.add(-1)} }; R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} ``` ### F Added in v0.9.0 ``` * → Boolean ``` #### Parameters #### Returns * Boolean A function that always returns `false`. Any passed in parameters are ignored. See also `[T](#T)`. ``` R.F(); //=> false ``` ### filter Added in v0.1.0 ``` Filterable f => (a → Boolean) → f a → f a ``` #### Parameters * `pred` * `filterable` #### Returns * Array Filterable Takes a predicate and a `Filterable`, and returns a new filterable of the same type containing the members of the given filterable which satisfy the given predicate. Filterable objects include plain objects or any object that has a filter method such as `Array`. Dispatches to the `filter` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[reject](#reject)`, `[transduce](#transduce)`, `[addIndex](#addIndex)`. ``` const isEven = n => n % 2 === 0; R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} ``` ### find Added in v0.1.0 ``` (a → Boolean) → [a] → a | undefined ``` #### Parameters * `fn` The predicate function used to determine if the element is the desired one. * `list` The array to consider. #### Returns * Object The element found, or `undefined`. Returns the first element of the list which matches the predicate, or `undefined` if no element matches. Dispatches to the `find` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` const xs = [{a: 1}, {a: 2}, {a: 3}]; R.find(R.propEq('a', 2))(xs); //=> {a: 2} R.find(R.propEq('a', 4))(xs); //=> undefined ``` ### findIndex Added in v0.1.1 ``` (a → Boolean) → [a] → Number ``` #### Parameters * `fn` The predicate function used to determine if the element is the desired one. * `list` The array to consider. #### Returns * Number The index of the element found, or `-1`. Returns the index of the first element of the list which matches the predicate, or `-1` if no element matches. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` const xs = [{a: 1}, {a: 2}, {a: 3}]; R.findIndex(R.propEq('a', 2))(xs); //=> 1 R.findIndex(R.propEq('a', 4))(xs); //=> -1 ``` ### findLast Added in v0.1.1 ``` (a → Boolean) → [a] → a | undefined ``` #### Parameters * `fn` The predicate function used to determine if the element is the desired one. * `list` The array to consider. #### Returns * Object The element found, or `undefined`. Returns the last element of the list which matches the predicate, or `undefined` if no element matches. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` const xs = [{a: 1, b: 0}, {a:1, b: 1}]; R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} R.findLast(R.propEq('a', 4))(xs); //=> undefined ``` ### findLastIndex Added in v0.1.1 ``` (a → Boolean) → [a] → Number ``` #### Parameters * `fn` The predicate function used to determine if the element is the desired one. * `list` The array to consider. #### Returns * Number The index of the element found, or `-1`. Returns the index of the last element of the list which matches the predicate, or `-1` if no element matches. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`. ``` const xs = [{a: 1, b: 0}, {a:1, b: 1}]; R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 ``` ### flatten Added in v0.1.0 ``` [a] → [b] ``` #### Parameters * `list` The array to consider. #### Returns * Array The flattened list. Returns a new list by pulling every item out of it (and all its sub-arrays) and putting them in a new array, depth-first. See also `[unnest](#unnest)`. ``` R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ``` ### flip Added in v0.1.0 ``` ((a, b, c, …) → z) → (b → a → c → … → z) ``` #### Parameters * `fn` The function to invoke with its first two parameters reversed. #### Returns * \* The result of invoking `fn` with its first two parameters' order reversed. Returns a new function much like the supplied one, except that the first two arguments' order is reversed. ``` const mergeThree = (a, b, c) => [].concat(a, b, c); mergeThree(1, 2, 3); //=> [1, 2, 3] R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] ``` ### forEach Added in v0.1.1 ``` (a → *) → [a] → [a] ``` #### Parameters * `fn` The function to invoke. Receives one argument, `value`. * `list` The list to iterate over. #### Returns * Array The original list. Iterate over an input `list`, calling a provided function `fn` for each element in the list. `fn` receives one argument: *(value)*. Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike the native `Array.prototype.forEach` method. For more details on this behavior, see: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description> Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original array. In some libraries this function is named `each`. Dispatches to the `forEach` method of the second argument, if present. See also `[addIndex](#addIndex)`. ``` const printXPlusFive = x => console.log(x + 5); R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] // logs 6 // logs 7 // logs 8 ``` ### forEachObjIndexed Added in v0.23.0 ``` ((a, String, StrMap a) → Any) → StrMap a → StrMap a ``` #### Parameters * `fn` The function to invoke. Receives three argument, `value`, `key`, `obj`. * `obj` The object to iterate over. #### Returns * Object The original object. Iterate over an input `object`, calling a provided function `fn` for each key and value in the object. `fn` receives three argument: *(value, key, obj)*. ``` const printKeyConcatValue = (value, key) => console.log(key + ':' + value); R.forEachObjIndexed(printKeyConcatValue, {x: 1, y: 2}); //=> {x: 1, y: 2} // logs x:1 // logs y:2 ``` ### fromPairs Added in v0.3.0 ``` [[k,v]] → {k: v} ``` #### Parameters * `pairs` An array of two-element arrays that will be the keys and values of the output object. #### Returns * Object The object made by pairing up `keys` and `values`. Creates a new object from a list key-value pairs. If a key appears in multiple pairs, the rightmost pair is included in the object. See also `[toPairs](#toPairs)`, `[pair](#pair)`. ``` R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} ``` ### groupBy Added in v0.1.0 ``` (a → String) → [a] → {String: [a]} ``` #### Parameters * `fn` Function :: a -> String * `list` The array to group #### Returns * Object An object with the output of `fn` for keys, mapped to arrays of elements that produced that key when passed to `fn`. Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function on each element, and grouping the results according to values returned. Dispatches to the `groupBy` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[reduceBy](#reduceBy)`, `[transduce](#transduce)`. ``` const byGrade = R.groupBy(function(student) { const score = student.score; return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A'; }); const students = [{name: 'Abby', score: 84}, {name: 'Eddy', score: 58}, // ... {name: 'Jack', score: 69}]; byGrade(students); // { // 'A': [{name: 'Dianne', score: 99}], // 'B': [{name: 'Abby', score: 84}] // // ..., // 'F': [{name: 'Eddy', score: 58}] // } ``` ### groupWith Added in v0.21.0 ``` ((a, a) → Boolean) → [a] → [[a]] ``` #### Parameters * `fn` Function for determining whether two given (adjacent) elements should be in the same group * `list` The array to group. Also accepts a string, which will be treated as a list of characters. #### Returns * List A list that contains sublists of elements, whose concatenations are equal to the original list. Takes a list and returns a list of lists where each sublist's elements are all satisfied pairwise comparison according to the provided function. Only adjacent elements are passed to the comparison function. ``` R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]] R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21]) //=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]] R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]] R.groupWith(R.eqBy(isVowel), 'aestiou') //=> ['ae', 'st', 'iou'] ``` ### gt Added in v0.1.0 ``` Ord a => a → a → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns `true` if the first argument is greater than the second; `false` otherwise. See also `[lt](#lt)`. ``` R.gt(2, 1); //=> true R.gt(2, 2); //=> false R.gt(2, 3); //=> false R.gt('a', 'z'); //=> false R.gt('z', 'a'); //=> true ``` ### gte Added in v0.1.0 ``` Ord a => a → a → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns `true` if the first argument is greater than or equal to the second; `false` otherwise. See also `[lte](#lte)`. ``` R.gte(2, 1); //=> true R.gte(2, 2); //=> true R.gte(2, 3); //=> false R.gte('a', 'z'); //=> false R.gte('z', 'a'); //=> true ``` ### has Added in v0.7.0 ``` s → {s: x} → Boolean ``` #### Parameters * `prop` The name of the property to check for. * `obj` The object to query. #### Returns * Boolean Whether the property exists. Returns whether or not an object has an own property with the specified name ``` const hasName = R.has('name'); hasName({name: 'alice'}); //=> true hasName({name: 'bob'}); //=> true hasName({}); //=> false const point = {x: 0, y: 0}; const pointHas = R.has(R.__, point); pointHas('x'); //=> true pointHas('y'); //=> true pointHas('z'); //=> false ``` ### hasIn Added in v0.7.0 ``` s → {s: x} → Boolean ``` #### Parameters * `prop` The name of the property to check for. * `obj` The object to query. #### Returns * Boolean Whether the property exists. Returns whether or not an object or its prototype chain has a property with the specified name ``` function Rectangle(width, height) { this.width = width; this.height = height; } Rectangle.prototype.area = function() { return this.width * this.height; }; const square = new Rectangle(2, 2); R.hasIn('width', square); //=> true R.hasIn('area', square); //=> true ``` ### hasPath Added in v0.26.0 ``` [Idx] → {a} → Boolean ``` `Idx = String | Int` #### Parameters * `path` The path to use. * `obj` The object to check the path in. #### Returns * Boolean Whether the path exists. Returns whether or not a path exists in an object. Only the object's own properties are checked. See also `[has](#has)`. ``` R.hasPath(['a', 'b'], {a: {b: 2}}); // => true R.hasPath(['a', 'b'], {a: {b: undefined}}); // => true R.hasPath(['a', 'b'], {a: {c: 2}}); // => false R.hasPath(['a', 'b'], {}); // => false ``` ### head Added in v0.1.0 ``` [a] → a | Undefined ``` `String → String` #### Parameters * `list` #### Returns * \* Returns the first element of the given list or string. In some libraries this function is named `first`. See also `[tail](#tail)`, `[init](#init)`, `[last](#last)`. ``` R.head(['fi', 'fo', 'fum']); //=> 'fi' R.head([]); //=> undefined R.head('abc'); //=> 'a' R.head(''); //=> '' ``` ### identical Added in v0.15.0 ``` a → a → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns true if its arguments are identical, false otherwise. Values are identical if they reference the same memory. `NaN` is identical to `NaN`; `0` and `-0` are not identical. Note this is merely a curried version of ES6 `Object.is`. ``` const o = {}; R.identical(o, o); //=> true R.identical(1, 1); //=> true R.identical(1, '1'); //=> false R.identical([], []); //=> false R.identical(0, -0); //=> false R.identical(NaN, NaN); //=> true ``` ### identity Added in v0.1.0 ``` a → a ``` #### Parameters * `x` The value to return. #### Returns * \* The input value, `x`. A function that does nothing but return the parameter supplied to it. Good as a default or placeholder function. ``` R.identity(1); //=> 1 const obj = {}; R.identity(obj) === obj; //=> true ``` ### ifElse Added in v0.8.0 ``` (*… → Boolean) → (*… → *) → (*… → *) → (*… → *) ``` #### Parameters * `condition` A predicate function * `onTrue` A function to invoke when the `condition` evaluates to a truthy value. * `onFalse` A function to invoke when the `condition` evaluates to a falsy value. #### Returns * function A new function that will process either the `onTrue` or the `onFalse` function depending upon the result of the `condition` predicate. Creates a function that will process either the `onTrue` or the `onFalse` function depending upon the result of the `condition` predicate. See also `[unless](#unless)`, `[when](#when)`, `[cond](#cond)`. ``` const incCount = R.ifElse( R.has('count'), R.over(R.lensProp('count'), R.inc), R.assoc('count', 1) ); incCount({}); //=> { count: 1 } incCount({ count: 1 }); //=> { count: 2 } ``` ### inc Added in v0.9.0 ``` Number → Number ``` #### Parameters * `n` #### Returns * Number n + 1 Increments its argument. See also `[dec](#dec)`. ``` R.inc(42); //=> 43 ``` ### includes Added in v0.26.0 ``` a → [a] → Boolean ``` #### Parameters * `a` The item to compare against. * `list` The array to consider. #### Returns * Boolean `true` if an equivalent item is in the list, `false` otherwise. Returns `true` if the specified value is equal, in [`R.equals`](#equals) terms, to at least one element of the given list; `false` otherwise. Works also with strings. See also `[any](#any)`. ``` R.includes(3, [1, 2, 3]); //=> true R.includes(4, [1, 2, 3]); //=> false R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true R.includes([42], [[42]]); //=> true R.includes('ba', 'banana'); //=>true ``` ### indexBy Added in v0.19.0 ``` (a → String) → [{k: v}] → {k: {k: v}} ``` #### Parameters * `fn` Function :: a -> String * `array` The array of objects to index #### Returns * Object An object indexing each array element by the given property. Given a function that generates a key, turns a list of objects into an object indexing the objects by the given key. Note that if multiple objects generate the same value for the indexing key only the last value will be included in the generated object. Acts as a transducer if a transformer is given in list position. ``` const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; R.indexBy(R.prop('id'), list); //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}} ``` ### indexOf Added in v0.1.0 ``` a → [a] → Number ``` #### Parameters * `target` The item to find. * `xs` The array to search in. #### Returns * Number the index of the target, or -1 if the target is not found. Returns the position of the first occurrence of an item in an array, or -1 if the item is not included in the array. [`R.equals`](#equals) is used to determine equality. See also `[lastIndexOf](#lastIndexOf)`. ``` R.indexOf(3, [1,2,3,4]); //=> 2 R.indexOf(10, [1,2,3,4]); //=> -1 ``` ### init Added in v0.9.0 ``` [a] → [a] ``` `String → String` #### Parameters * `list` #### Returns * \* Returns all but the last element of the given list or string. See also `[last](#last)`, `[head](#head)`, `[tail](#tail)`. ``` R.init([1, 2, 3]); //=> [1, 2] R.init([1, 2]); //=> [1] R.init([1]); //=> [] R.init([]); //=> [] R.init('abc'); //=> 'ab' R.init('ab'); //=> 'a' R.init('a'); //=> '' R.init(''); //=> '' ``` ### innerJoin Added in v0.24.0 ``` ((a, b) → Boolean) → [a] → [b] → [a] ``` #### Parameters * `pred` * `xs` * `ys` #### Returns * Array Takes a predicate `pred`, a list `xs`, and a list `ys`, and returns a list `xs'` comprising each of the elements of `xs` which is equal to one or more elements of `ys` according to `pred`. `pred` must be a binary function expecting an element from each list. `xs`, `ys`, and `xs'` are treated as sets, semantically, so ordering should not be significant, but since `xs'` is ordered the implementation guarantees that its values are in the same order as they appear in `xs`. Duplicates are not removed, so `xs'` may contain duplicates if `xs` contains duplicates. See also `[intersection](#intersection)`. ``` R.innerJoin( (record, id) => record.id === id, [{id: 824, name: 'Richie Furay'}, {id: 956, name: 'Dewey Martin'}, {id: 313, name: 'Bruce Palmer'}, {id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}], [177, 456, 999] ); //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] ``` ### insert Added in v0.2.2 ``` Number → a → [a] → [a] ``` #### Parameters * `index` The position to insert the element * `elt` The element to insert into the Array * `list` The list to insert into #### Returns * Array A new Array with `elt` inserted at `index`. Inserts the supplied element into the list, at the specified `index`. *Note that this is not destructive*: it returns a copy of the list with the changes. No lists have been harmed in the application of this function. ``` R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] ``` ### insertAll Added in v0.9.0 ``` Number → [a] → [a] → [a] ``` #### Parameters * `index` The position to insert the sub-list * `elts` The sub-list to insert into the Array * `list` The list to insert the sub-list into #### Returns * Array A new Array with `elts` inserted starting at `index`. Inserts the sub-list into the list, at the specified `index`. *Note that this is not destructive*: it returns a copy of the list with the changes. No lists have been harmed in the application of this function. ``` R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] ``` ### intersection Added in v0.1.0 ``` [*] → [*] → [*] ``` #### Parameters * `list1` The first list. * `list2` The second list. #### Returns * Array The list of elements found in both `list1` and `list2`. Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. See also `[innerJoin](#innerJoin)`. ``` R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] ``` ### intersperse Added in v0.14.0 ``` a → [a] → [a] ``` #### Parameters * `separator` The element to add to the list. * `list` The list to be interposed. #### Returns * Array The new list. Creates a new list with the separator interposed between elements. Dispatches to the `intersperse` method of the second argument, if present. ``` R.intersperse('a', ['b', 'n', 'n', 's']); //=> ['b', 'a', 'n', 'a', 'n', 'a', 's'] ``` ### into Added in v0.12.0 ``` a → (b → b) → [c] → a ``` #### Parameters * `acc` The initial accumulator value. * `xf` The transducer function. Receives a transformer and returns a transformer. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. Transforms the items of the list with the transducer and appends the transformed items to the accumulator using an appropriate iterator function based on the accumulator type. The accumulator can be an array, string, object or a transformer. Iterated items will be appended to arrays and concatenated to strings. Objects will be merged directly or 2-item arrays will be merged as key, value pairs. The accumulator can also be a transformer object that provides a 2-arity reducing iterator function, step, 0-arity initial value function, init, and 1-arity result extraction function result. The step function is used as the iterator function in reduce. The result function is used to convert the final accumulator into the return type and in most cases is R.identity. The init function is used to provide the initial accumulator. The iteration is performed with [`R.reduce`](#reduce) after initializing the transducer. See also `[transduce](#transduce)`. ``` const numbers = [1, 2, 3, 4]; const transducer = R.compose(R.map(R.add(1)), R.take(2)); R.into([], transducer, numbers); //=> [2, 3] const intoArray = R.into([]); intoArray(transducer, numbers); //=> [2, 3] ``` ### invert Added in v0.9.0 ``` {s: x} → {x: [ s, … ]} ``` #### Parameters * `obj` The object or array to invert #### Returns * Object out A new object with keys in an array. Same as [`R.invertObj`](#invertObj), however this accounts for objects with duplicate values by putting the values into an array. See also `[invertObj](#invertObj)`. ``` const raceResultsByFirstName = { first: 'alice', second: 'jake', third: 'alice', }; R.invert(raceResultsByFirstName); //=> { 'alice': ['first', 'third'], 'jake':['second'] } ``` ### invertObj Added in v0.9.0 ``` {s: x} → {x: s} ``` #### Parameters * `obj` The object or array to invert #### Returns * Object out A new object Returns a new object with the keys of the given object as values, and the values of the given object, which are coerced to strings, as keys. Note that the last key found is preferred when handling the same value. See also `[invert](#invert)`. ``` const raceResults = { first: 'alice', second: 'jake' }; R.invertObj(raceResults); //=> { 'alice': 'first', 'jake':'second' } // Alternatively: const raceResults = ['alice', 'jake']; R.invertObj(raceResults); //=> { 'alice': '0', 'jake':'1' } ``` ### invoker Added in v0.1.0 ``` Number → String → (a → b → … → n → Object → *) ``` #### Parameters * `arity` Number of arguments the returned function should take before the target object. * `method` Name of any of the target object's methods to call. #### Returns * function A new curried function. Turns a named method with a specified arity into a function that can be called directly supplied with arguments and a target object. The returned function is curried and accepts `arity + 1` parameters where the final parameter is the target object. See also `[construct](#construct)`. ``` const sliceFrom = R.invoker(1, 'slice'); sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm' const sliceFrom6 = R.invoker(2, 'slice')(6); sliceFrom6(8, 'abcdefghijklm'); //=> 'gh' const dog = { speak: async () => 'Woof!' }; const speak = R.invoker(0, 'speak'); speak(dog).then(console.log) //~> 'Woof!' ``` ### is Added in v0.3.0 ``` (* → {*}) → a → Boolean ``` #### Parameters * `ctor` A constructor * `val` The value to test #### Returns * Boolean See if an object (`val`) is an instance of the supplied constructor. This function will check up the inheritance chain, if any. ``` R.is(Object, {}); //=> true R.is(Number, 1); //=> true R.is(Object, 1); //=> false R.is(String, 's'); //=> true R.is(String, new String('')); //=> true R.is(Object, new String('')); //=> true R.is(Object, 's'); //=> false R.is(Number, {}); //=> false ``` ### isEmpty Added in v0.1.0 ``` a → Boolean ``` #### Parameters * `x` #### Returns * Boolean Returns `true` if the given value is its type's empty value; `false` otherwise. See also `[empty](#empty)`. ``` R.isEmpty([1, 2, 3]); //=> false R.isEmpty([]); //=> true R.isEmpty(''); //=> true R.isEmpty(null); //=> false R.isEmpty({}); //=> true R.isEmpty({length: 0}); //=> false ``` ### isNil Added in v0.9.0 ``` * → Boolean ``` #### Parameters * `x` The value to test. #### Returns * Boolean `true` if `x` is `undefined` or `null`, otherwise `false`. Checks if the input value is `null` or `undefined`. ``` R.isNil(null); //=> true R.isNil(undefined); //=> true R.isNil(0); //=> false R.isNil([]); //=> false ``` ### join Added in v0.1.0 ``` String → [a] → String ``` #### Parameters * `separator` The string used to separate the elements. * `xs` The elements to join into a string. #### Returns * String str The string made by concatenating `xs` with `separator`. Returns a string made by inserting the `separator` between each element and concatenating all the elements into a single string. See also `[split](#split)`. ``` const spacer = R.join(' '); spacer(['a', 2, 3.4]); //=> 'a 2 3.4' R.join('|', [1, 2, 3]); //=> '1|2|3' ``` ### juxt Added in v0.19.0 ``` [(a, b, …, m) → n] → ((a, b, …, m) → [n]) ``` #### Parameters * `fns` An array of functions #### Returns * function A function that returns a list of values after applying each of the original `fns` to its parameters. juxt applies a list of functions to a list of values. See also `[applySpec](#applySpec)`. ``` const getRange = R.juxt([Math.min, Math.max]); getRange(3, 4, 9, -3); //=> [-3, 9] ``` ### keys Added in v0.1.0 ``` {k: v} → [k] ``` #### Parameters * `obj` The object to extract properties from #### Returns * Array An array of the object's own properties. Returns a list containing the names of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. See also `[keysIn](#keysIn)`, `[values](#values)`. ``` R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] ``` ### keysIn Added in v0.2.0 ``` {k: v} → [k] ``` #### Parameters * `obj` The object to extract properties from #### Returns * Array An array of the object's own and prototype properties. Returns a list containing the names of all the properties of the supplied object, including prototype properties. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. See also `[keys](#keys)`, `[valuesIn](#valuesIn)`. ``` const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.keysIn(f); //=> ['x', 'y'] ``` ### last Added in v0.1.4 ``` [a] → a | Undefined ``` `String → String` #### Parameters * `list` #### Returns * \* Returns the last element of the given list or string. See also `[init](#init)`, `[head](#head)`, `[tail](#tail)`. ``` R.last(['fi', 'fo', 'fum']); //=> 'fum' R.last([]); //=> undefined R.last('abc'); //=> 'c' R.last(''); //=> '' ``` ### lastIndexOf Added in v0.1.0 ``` a → [a] → Number ``` #### Parameters * `target` The item to find. * `xs` The array to search in. #### Returns * Number the index of the target, or -1 if the target is not found. Returns the position of the last occurrence of an item in an array, or -1 if the item is not included in the array. [`R.equals`](#equals) is used to determine equality. See also `[indexOf](#indexOf)`. ``` R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 R.lastIndexOf(10, [1,2,3,4]); //=> -1 ``` ### length Added in v0.3.0 ``` [a] → Number ``` #### Parameters * `list` The array to inspect. #### Returns * Number The length of the array. Returns the number of elements in the array by returning `list.length`. ``` R.length([]); //=> 0 R.length([1, 2, 3]); //=> 3 ``` ### lens Added in v0.8.0 ``` (s → a) → ((a, s) → s) → Lens s a ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `getter` * `setter` #### Returns * Lens Returns a lens for the given getter and setter functions. The getter "gets" the value of the focus; the setter "sets" the value of the focus. The setter should not mutate the data structure. See also `[view](#view)`, `[set](#set)`, `[over](#over)`, `[lensIndex](#lensIndex)`, `[lensProp](#lensProp)`. ``` const xLens = R.lens(R.prop('x'), R.assoc('x')); R.view(xLens, {x: 1, y: 2}); //=> 1 R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} ``` ### lensIndex Added in v0.14.0 ``` Number → Lens s a ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `n` #### Returns * Lens Returns a lens whose focus is the specified index. See also `[view](#view)`, `[set](#set)`, `[over](#over)`, `[nth](#nth)`. ``` const headLens = R.lensIndex(0); R.view(headLens, ['a', 'b', 'c']); //=> 'a' R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] ``` ### lensPath Added in v0.19.0 ``` [Idx] → Lens s a ``` `Idx = String | Int` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `path` The path to use. #### Returns * Lens Returns a lens whose focus is the specified path. See also `[view](#view)`, `[set](#set)`, `[over](#over)`. ``` const xHeadYLens = R.lensPath(['x', 0, 'y']); R.view(xHeadYLens, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> 2 R.set(xHeadYLens, 1, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> {x: [{y: 1, z: 3}, {y: 4, z: 5}]} R.over(xHeadYLens, R.negate, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); //=> {x: [{y: -2, z: 3}, {y: 4, z: 5}]} ``` ### lensProp Added in v0.14.0 ``` String → Lens s a ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `k` #### Returns * Lens Returns a lens whose focus is the specified property. See also `[view](#view)`, `[set](#set)`, `[over](#over)`. ``` const xLens = R.lensProp('x'); R.view(xLens, {x: 1, y: 2}); //=> 1 R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} ``` ### lift Added in v0.7.0 ``` (*… → *) → ([*]… → [*]) ``` #### Parameters * `fn` The function to lift into higher context #### Returns * function The lifted function. "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). See also `[liftN](#liftN)`. ``` const madd3 = R.lift((a, b, c) => a + b + c); madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e); madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24] ``` ### liftN Added in v0.7.0 ``` Number → (*… → *) → ([*]… → [*]) ``` #### Parameters * `fn` The function to lift into higher context #### Returns * function The lifted function. "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). See also `[lift](#lift)`, `[ap](#ap)`. ``` const madd3 = R.liftN(3, (...args) => R.sum(args)); madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] ``` ### lt Added in v0.1.0 ``` Ord a => a → a → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns `true` if the first argument is less than the second; `false` otherwise. See also `[gt](#gt)`. ``` R.lt(2, 1); //=> false R.lt(2, 2); //=> false R.lt(2, 3); //=> true R.lt('a', 'z'); //=> true R.lt('z', 'a'); //=> false ``` ### lte Added in v0.1.0 ``` Ord a => a → a → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean Returns `true` if the first argument is less than or equal to the second; `false` otherwise. See also `[gte](#gte)`. ``` R.lte(2, 1); //=> false R.lte(2, 2); //=> true R.lte(2, 3); //=> true R.lte('a', 'z'); //=> true R.lte('z', 'a'); //=> false ``` ### map Added in v0.1.0 ``` Functor f => (a → b) → f a → f b ``` #### Parameters * `fn` The function to be called on every element of the input `list`. * `list` The list to be iterated over. #### Returns * Array The new list. Takes a function and a [functor](https://github.com/fantasyland/fantasy-land#functor), applies the function to each of the functor's values, and returns a functor of the same shape. Ramda provides suitable `map` implementations for `Array` and `Object`, so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`. Dispatches to the `map` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. Also treats functions as functors and will compose them together. See also `[transduce](#transduce)`, `[addIndex](#addIndex)`. ``` const double = x => x * 2; R.map(double, [1, 2, 3]); //=> [2, 4, 6] R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6} ``` ### mapAccum Added in v0.10.0 ``` ((acc, x) → (acc, y)) → acc → [x] → (acc, [y]) ``` #### Parameters * `fn` The function to be called on every element of the input `list`. * `acc` The accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. The `mapAccum` function behaves like a combination of map and reduce; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list. The iterator function receives two arguments, *acc* and *value*, and should return a tuple *[acc, value]*. See also `[scan](#scan)`, `[addIndex](#addIndex)`, `[mapAccumRight](#mapAccumRight)`. ``` const digits = ['1', '2', '3', '4']; const appender = (a, b) => [a + b, a + b]; R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']] ``` ### mapAccumRight Added in v0.10.0 ``` ((acc, x) → (acc, y)) → acc → [x] → (acc, [y]) ``` #### Parameters * `fn` The function to be called on every element of the input `list`. * `acc` The accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. The `mapAccumRight` function behaves like a combination of map and reduce; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list. Similar to [`mapAccum`](#mapAccum), except moves through the input list from the right to the left. The iterator function receives two arguments, *acc* and *value*, and should return a tuple *[acc, value]*. See also `[addIndex](#addIndex)`, `[mapAccum](#mapAccum)`. ``` const digits = ['1', '2', '3', '4']; const appender = (a, b) => [b + a, b + a]; R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']] ``` ### mapObjIndexed Added in v0.9.0 ``` ((*, String, Object) → *) → Object → Object ``` #### Parameters * `fn` * `obj` #### Returns * Object An Object-specific version of [`map`](#map). The function is applied to three arguments: *(value, key, obj)*. If only the value is significant, use [`map`](#map) instead. See also `[map](#map)`. ``` const xyz = { x: 1, y: 2, z: 3 }; const prependKeyAndDouble = (num, key, obj) => key + (num * 2); R.mapObjIndexed(prependKeyAndDouble, xyz); //=> { x: 'x2', y: 'y4', z: 'z6' } ``` ### match Added in v0.1.0 ``` RegExp → String → [String | Undefined] ``` #### Parameters * `rx` A regular expression. * `str` The string to match against #### Returns * Array The list of matches or empty array. Tests a regular expression against a String. Note that this function will return an empty array when there are no matches. This differs from [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) which returns `null` when there are no matches. See also `[test](#test)`. ``` R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] R.match(/a/, 'b'); //=> [] R.match(/a/, null); //=> TypeError: null does not have a method named "match" ``` ### mathMod Added in v0.3.0 ``` Number → Number → Number ``` #### Parameters * `m` The dividend. * `p` the modulus. #### Returns * Number The result of `b mod a`. `mathMod` behaves like the modulo operator should mathematically, unlike the `%` operator (and by extension, [`R.modulo`](#modulo)). So while `-17 % 5` is `-2`, `mathMod(-17, 5)` is `3`. `mathMod` requires Integer arguments, and returns NaN when the modulus is zero or negative. See also `[modulo](#modulo)`. ``` R.mathMod(-17, 5); //=> 3 R.mathMod(17, 5); //=> 2 R.mathMod(17, -5); //=> NaN R.mathMod(17, 0); //=> NaN R.mathMod(17.2, 5); //=> NaN R.mathMod(17, 5.3); //=> NaN const clock = R.mathMod(R.__, 12); clock(15); //=> 3 clock(24); //=> 0 const seventeenMod = R.mathMod(17); seventeenMod(3); //=> 2 seventeenMod(4); //=> 1 seventeenMod(10); //=> 7 ``` ### max Added in v0.1.0 ``` Ord a => a → a → a ``` #### Parameters * `a` * `b` #### Returns * \* Returns the larger of its two arguments. See also `[maxBy](#maxBy)`, `[min](#min)`. ``` R.max(789, 123); //=> 789 R.max('a', 'b'); //=> 'b' ``` ### maxBy Added in v0.8.0 ``` Ord b => (a → b) → a → a → a ``` #### Parameters * `f` * `a` * `b` #### Returns * \* Takes a function and two values, and returns whichever value produces the larger result when passed to the provided function. See also `[max](#max)`, `[minBy](#minBy)`. ``` // square :: Number -> Number const square = n => n * n; R.maxBy(square, -3, 2); //=> -3 R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 R.reduce(R.maxBy(square), 0, []); //=> 0 ``` ### mean Added in v0.14.0 ``` [Number] → Number ``` #### Parameters * `list` #### Returns * Number Returns the mean of the given list of numbers. See also `[median](#median)`. ``` R.mean([2, 7, 9]); //=> 6 R.mean([]); //=> NaN ``` ### median Added in v0.14.0 ``` [Number] → Number ``` #### Parameters * `list` #### Returns * Number Returns the median of the given list of numbers. See also `[mean](#mean)`. ``` R.median([2, 9, 7]); //=> 7 R.median([7, 2, 10, 9]); //=> 8 R.median([]); //=> NaN ``` ### memoizeWith Added in v0.24.0 ``` (*… → String) → (*… → a) → (*… → a) ``` #### Parameters * `fn` The function to generate the cache key. * `fn` The function to memoize. #### Returns * function Memoized version of `fn`. Creates a new function that, when invoked, caches the result of calling `fn` for a given argument set and returns the result. Subsequent calls to the memoized `fn` with the same argument set will not result in an additional call to `fn`; instead, the cached result for that set of arguments will be returned. ``` let count = 0; const factorial = R.memoizeWith(R.identity, n => { count += 1; return R.product(R.range(1, n + 1)); }); factorial(5); //=> 120 factorial(5); //=> 120 factorial(5); //=> 120 count; //=> 1 ``` ### merge Added in v0.1.0 Deprecated since v0.26.0 `{k: v} → {k: v} → {k: v}` #### Parameters * `l` * `r` #### Returns * Object Create a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects, the value from the second object will be used. See also `[mergeRight](#mergeRight)`, `[mergeDeepRight](#mergeDeepRight)`, `[mergeWith](#mergeWith)`, `[mergeWithKey](#mergeWithKey)`. ``` R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); //=> { 'name': 'fred', 'age': 40 } const withDefaults = R.merge({x: 0, y: 0}); withDefaults({y: 2}); //=> {x: 0, y: 2} ``` ### mergeAll Added in v0.10.0 ``` [{k: v}] → {k: v} ``` #### Parameters * `list` An array of objects #### Returns * Object A merged object. Merges a list of objects together into one object. See also `[reduce](#reduce)`. ``` R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} ``` ### mergeDeepLeft Added in v0.24.0 ``` {a} → {a} → {a} ``` #### Parameters * `lObj` * `rObj` #### Returns * Object Creates a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects: * and both values are objects, the two values will be recursively merged * otherwise the value from the first object will be used. See also `[merge](#merge)`, `[mergeDeepRight](#mergeDeepRight)`, `[mergeDeepWith](#mergeDeepWith)`, `[mergeDeepWithKey](#mergeDeepWithKey)`. ``` R.mergeDeepLeft({ name: 'fred', age: 10, contact: { email: '[email protected]' }}, { age: 40, contact: { email: '[email protected]' }}); //=> { name: 'fred', age: 10, contact: { email: '[email protected]' }} ``` ### mergeDeepRight Added in v0.24.0 ``` {a} → {a} → {a} ``` #### Parameters * `lObj` * `rObj` #### Returns * Object Creates a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects: * and both values are objects, the two values will be recursively merged * otherwise the value from the second object will be used. See also `[merge](#merge)`, `[mergeDeepLeft](#mergeDeepLeft)`, `[mergeDeepWith](#mergeDeepWith)`, `[mergeDeepWithKey](#mergeDeepWithKey)`. ``` R.mergeDeepRight({ name: 'fred', age: 10, contact: { email: '[email protected]' }}, { age: 40, contact: { email: '[email protected]' }}); //=> { name: 'fred', age: 40, contact: { email: '[email protected]' }} ``` ### mergeDeepWith Added in v0.24.0 ``` ((a, a) → a) → {a} → {a} → {a} ``` #### Parameters * `fn` * `lObj` * `rObj` #### Returns * Object Creates a new object with the own properties of the two provided objects. If a key exists in both objects: * and both associated values are also objects then the values will be recursively merged. * otherwise the provided function is applied to associated values using the resulting value as the new value associated with the key. If a key only exists in one object, the value will be associated with the key of the resulting object. See also `[mergeWith](#mergeWith)`, `[mergeDeepWithKey](#mergeDeepWithKey)`. ``` R.mergeDeepWith(R.concat, { a: true, c: { values: [10, 20] }}, { b: true, c: { values: [15, 35] }}); //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }} ``` ### mergeDeepWithKey Added in v0.24.0 ``` ((String, a, a) → a) → {a} → {a} → {a} ``` #### Parameters * `fn` * `lObj` * `rObj` #### Returns * Object Creates a new object with the own properties of the two provided objects. If a key exists in both objects: * and both associated values are also objects then the values will be recursively merged. * otherwise the provided function is applied to the key and associated values using the resulting value as the new value associated with the key. If a key only exists in one object, the value will be associated with the key of the resulting object. See also `[mergeWithKey](#mergeWithKey)`, `[mergeDeepWith](#mergeDeepWith)`. ``` let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r R.mergeDeepWithKey(concatValues, { a: true, c: { thing: 'foo', values: [10, 20] }}, { b: true, c: { thing: 'bar', values: [15, 35] }}); //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }} ``` ### mergeLeft Added in v0.26.0 ``` {k: v} → {k: v} → {k: v} ``` #### Parameters * `l` * `r` #### Returns * Object Create a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects, the value from the first object will be used. See also `[mergeRight](#mergeRight)`, `[mergeDeepLeft](#mergeDeepLeft)`, `[mergeWith](#mergeWith)`, `[mergeWithKey](#mergeWithKey)`. ``` R.mergeLeft({ 'age': 40 }, { 'name': 'fred', 'age': 10 }); //=> { 'name': 'fred', 'age': 40 } const resetToDefault = R.mergeLeft({x: 0}); resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} ``` ### mergeRight Added in v0.26.0 ``` {k: v} → {k: v} → {k: v} ``` #### Parameters * `l` * `r` #### Returns * Object Create a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects, the value from the second object will be used. See also `[mergeLeft](#mergeLeft)`, `[mergeDeepRight](#mergeDeepRight)`, `[mergeWith](#mergeWith)`, `[mergeWithKey](#mergeWithKey)`. ``` R.mergeRight({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); //=> { 'name': 'fred', 'age': 40 } const withDefaults = R.mergeRight({x: 0, y: 0}); withDefaults({y: 2}); //=> {x: 0, y: 2} ``` ### mergeWith Added in v0.19.0 ``` ((a, a) → a) → {a} → {a} → {a} ``` #### Parameters * `fn` * `l` * `r` #### Returns * Object Creates a new object with the own properties of the two provided objects. If a key exists in both objects, the provided function is applied to the values associated with the key in each object, with the result being used as the value associated with the key in the returned object. See also `[mergeDeepWith](#mergeDeepWith)`, `[merge](#merge)`, `[mergeWithKey](#mergeWithKey)`. ``` R.mergeWith(R.concat, { a: true, values: [10, 20] }, { b: true, values: [15, 35] }); //=> { a: true, b: true, values: [10, 20, 15, 35] } ``` ### mergeWithKey Added in v0.19.0 ``` ((String, a, a) → a) → {a} → {a} → {a} ``` #### Parameters * `fn` * `l` * `r` #### Returns * Object Creates a new object with the own properties of the two provided objects. If a key exists in both objects, the provided function is applied to the key and the values associated with the key in each object, with the result being used as the value associated with the key in the returned object. See also `[mergeDeepWithKey](#mergeDeepWithKey)`, `[merge](#merge)`, `[mergeWith](#mergeWith)`. ``` let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r R.mergeWithKey(concatValues, { a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] } ``` ### min Added in v0.1.0 ``` Ord a => a → a → a ``` #### Parameters * `a` * `b` #### Returns * \* Returns the smaller of its two arguments. See also `[minBy](#minBy)`, `[max](#max)`. ``` R.min(789, 123); //=> 123 R.min('a', 'b'); //=> 'a' ``` ### minBy Added in v0.8.0 ``` Ord b => (a → b) → a → a → a ``` #### Parameters * `f` * `a` * `b` #### Returns * \* Takes a function and two values, and returns whichever value produces the smaller result when passed to the provided function. See also `[min](#min)`, `[maxBy](#maxBy)`. ``` // square :: Number -> Number const square = n => n * n; R.minBy(square, -3, 2); //=> 2 R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1 R.reduce(R.minBy(square), Infinity, []); //=> Infinity ``` ### modulo Added in v0.1.1 ``` Number → Number → Number ``` #### Parameters * `a` The value to the divide. * `b` The pseudo-modulus #### Returns * Number The result of `b % a`. Divides the first parameter by the second and returns the remainder. Note that this function preserves the JavaScript-style behavior for modulo. For mathematical modulo see [`mathMod`](#mathMod). See also `[mathMod](#mathMod)`. ``` R.modulo(17, 3); //=> 2 // JS behavior: R.modulo(-17, 3); //=> -2 R.modulo(17, -3); //=> 2 const isOdd = R.modulo(R.__, 2); isOdd(42); //=> 0 isOdd(21); //=> 1 ``` ### move Added in v0.27.0 ``` Number → Number → [a] → [a] ``` #### Parameters * `from` The source index * `to` The destination index * `list` The list which will serve to realise the move #### Returns * Array The new list reordered Move an item, at index `from`, to index `to`, in a list of elements. A new list will be created containing the new elements order. ``` R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation ``` ### multiply Added in v0.1.0 ``` Number → Number → Number ``` #### Parameters * `a` The first value. * `b` The second value. #### Returns * Number The result of `a \* b`. Multiplies two numbers. Equivalent to `a * b` but curried. See also `[divide](#divide)`. ``` const double = R.multiply(2); const triple = R.multiply(3); double(3); //=> 6 triple(4); //=> 12 R.multiply(2, 5); //=> 10 ``` ### nAry Added in v0.1.0 ``` Number → (* → a) → (* → a) ``` #### Parameters * `n` The desired arity of the new function. * `fn` The function to wrap. #### Returns * function A new function wrapping `fn`. The new function is guaranteed to be of arity `n`. Wraps a function of any arity (including nullary) in a function that accepts exactly `n` parameters. Any extraneous parameters will not be passed to the supplied function. See also `[binary](#binary)`, `[unary](#unary)`. ``` const takesTwoArgs = (a, b) => [a, b]; takesTwoArgs.length; //=> 2 takesTwoArgs(1, 2); //=> [1, 2] const takesOneArg = R.nAry(1, takesTwoArgs); takesOneArg.length; //=> 1 // Only `n` arguments are passed to the wrapped function takesOneArg(1, 2); //=> [1, undefined] ``` ### negate Added in v0.9.0 ``` Number → Number ``` #### Parameters * `n` #### Returns * Number Negates its argument. ``` R.negate(42); //=> -42 ``` ### none Added in v0.12.0 ``` (a → Boolean) → [a] → Boolean ``` #### Parameters * `fn` The predicate function. * `list` The array to consider. #### Returns * Boolean `true` if the predicate is not satisfied by every element, `false` otherwise. Returns `true` if no elements of the list match the predicate, `false` otherwise. Dispatches to the `all` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[all](#all)`, `[any](#any)`. ``` const isEven = n => n % 2 === 0; const isOdd = n => n % 2 === 1; R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true R.none(isOdd, [1, 3, 5, 7, 8, 11]); //=> false ``` ### not Added in v0.1.0 ``` * → Boolean ``` #### Parameters * `a` any value #### Returns * Boolean the logical inverse of passed argument. A function that returns the `!` of its argument. It will return `true` when passed false-y value, and `false` when passed a truth-y one. See also `[complement](#complement)`. ``` R.not(true); //=> false R.not(false); //=> true R.not(0); //=> true R.not(1); //=> false ``` ### nth Added in v0.1.0 ``` Number → [a] → a | Undefined ``` `Number → String → String` #### Parameters * `offset` * `list` #### Returns * \* Returns the nth element of the given list or string. If n is negative the element at index length + n is returned. ``` const list = ['foo', 'bar', 'baz', 'quux']; R.nth(1, list); //=> 'bar' R.nth(-1, list); //=> 'quux' R.nth(-99, list); //=> undefined R.nth(2, 'abc'); //=> 'c' R.nth(3, 'abc'); //=> '' ``` ### nthArg Added in v0.9.0 ``` Number → *… → * ``` #### Parameters * `n` #### Returns * function Returns a function which returns its nth argument. ``` R.nthArg(1)('a', 'b', 'c'); //=> 'b' R.nthArg(-1)('a', 'b', 'c'); //=> 'c' ``` ### o Added in v0.24.0 ``` (b → c) → (a → b) → a → c ``` #### Parameters * `f` * `g` #### Returns * function `o` is a curried composition function that returns a unary function. Like [`compose`](#compose), `o` performs right-to-left function composition. Unlike [`compose`](#compose), the rightmost function passed to `o` will be invoked with only one argument. Also, unlike [`compose`](#compose), `o` is limited to accepting only 2 unary functions. The name o was chosen because of its similarity to the mathematical composition operator ∘. See also `[compose](#compose)`, `[pipe](#pipe)`. ``` const classyGreeting = name => "The name's " + name.last + ", " + name.first + " " + name.last const yellGreeting = R.o(R.toUpper, classyGreeting); yellGreeting({first: 'James', last: 'Bond'}); //=> "THE NAME'S BOND, JAMES BOND" R.o(R.multiply(10), R.add(10))(-4) //=> 60 ``` ### objOf Added in v0.18.0 ``` String → a → {String:a} ``` #### Parameters * `key` * `val` #### Returns * Object Creates an object containing a single key:value pair. See also `[pair](#pair)`. ``` const matchPhrases = R.compose( R.objOf('must'), R.map(R.objOf('match_phrase')) ); matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]} ``` ### of Added in v0.3.0 ``` a → [a] ``` #### Parameters * `x` any value #### Returns * Array An array wrapping `x`. Returns a singleton array containing the value provided. Note this `of` is different from the ES6 `of`; See <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of> ``` R.of(null); //=> [null] R.of([42]); //=> [[42]] ``` ### omit Added in v0.1.0 ``` [String] → {String: *} → {String: *} ``` #### Parameters * `names` an array of String property names to omit from the new object * `obj` The object to copy from #### Returns * Object A new object with properties from `names` not on it. Returns a partial copy of an object omitting the keys specified. See also `[pick](#pick)`. ``` R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} ``` ### once Added in v0.1.0 ``` (a… → b) → (a… → b) ``` #### Parameters * `fn` The function to wrap in a call-only-once wrapper. #### Returns * function The wrapped function. Accepts a function `fn` and returns a function that guards invocation of `fn` such that `fn` can only ever be called once, no matter how many times the returned function is invoked. The first value calculated is returned in subsequent invocations. ``` const addOneOnce = R.once(x => x + 1); addOneOnce(10); //=> 11 addOneOnce(addOneOnce(50)); //=> 11 ``` ### or Added in v0.1.0 ``` a → b → a | b ``` #### Parameters * `a` * `b` #### Returns * Any the first argument if truthy, otherwise the second argument. Returns `true` if one or both of its arguments are `true`. Returns `false` if both arguments are `false`. See also `[either](#either)`, `[xor](#xor)`. ``` R.or(true, true); //=> true R.or(true, false); //=> true R.or(false, true); //=> true R.or(false, false); //=> false ``` ### otherwise Added in v0.26.0 ``` (e → b) → (Promise e a) → (Promise e b) ``` `(e → (Promise f b)) → (Promise e a) → (Promise f b)` #### Parameters * `onFailure` The function to apply. Can return a value or a promise of a value. * `p` #### Returns * Promise The result of calling `p.then(null, onFailure)` Returns the result of applying the onFailure function to the value inside a failed promise. This is useful for handling rejected promises inside function compositions. See also `[andThen](#andThen)`. ``` var failedFetch = (id) => Promise.reject('bad ID'); var useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' }) //recoverFromFailure :: String -> Promise ({firstName, lastName}) var recoverFromFailure = R.pipe( failedFetch, R.otherwise(useDefault), R.andThen(R.pick(['firstName', 'lastName'])), ); recoverFromFailure(12345).then(console.log) ``` ### over Added in v0.16.0 ``` Lens s a → (a → a) → s → s ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `lens` * `v` * `x` #### Returns * \* Returns the result of "setting" the portion of the given data structure focused by the given lens to the result of applying the given function to the focused value. See also `[prop](#prop)`, `[lensIndex](#lensIndex)`, `[lensProp](#lensProp)`. ``` const headLens = R.lensIndex(0); R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] ``` ### pair Added in v0.18.0 ``` a → b → (a,b) ``` #### Parameters * `fst` * `snd` #### Returns * Array Takes two arguments, `fst` and `snd`, and returns `[fst, snd]`. See also `[objOf](#objOf)`, `[of](#of)`. ``` R.pair('foo', 'bar'); //=> ['foo', 'bar'] ``` ### partial Added in v0.10.0 ``` ((a, b, c, …, n) → x) → [a, b, c, …] → ((d, e, f, …, n) → x) ``` #### Parameters * `f` * `args` #### Returns * function Takes a function `f` and a list of arguments, and returns a function `g`. When applied, `g` returns the result of applying `f` to the arguments provided initially followed by the arguments provided to `g`. See also `[partialRight](#partialRight)`, `[curry](#curry)`. ``` const multiply2 = (a, b) => a * b; const double = R.partial(multiply2, [2]); double(2); //=> 4 const greet = (salutation, title, firstName, lastName) => salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; const sayHello = R.partial(greet, ['Hello']); const sayHelloToMs = R.partial(sayHello, ['Ms.']); sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' ``` ### partialRight Added in v0.10.0 ``` ((a, b, c, …, n) → x) → [d, e, f, …, n] → ((a, b, c, …) → x) ``` #### Parameters * `f` * `args` #### Returns * function Takes a function `f` and a list of arguments, and returns a function `g`. When applied, `g` returns the result of applying `f` to the arguments provided to `g` followed by the arguments provided initially. See also `[partial](#partial)`. ``` const greet = (salutation, title, firstName, lastName) => salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; const greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']); greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' ``` ### partition Added in v0.1.4 ``` Filterable f => (a → Boolean) → f a → [f a, f a] ``` #### Parameters * `pred` A predicate to determine which side the element belongs to. * `filterable` the list (or other filterable) to partition. #### Returns * Array An array, containing first the subset of elements that satisfy the predicate, and second the subset of elements that do not satisfy. Takes a predicate and a list or other `Filterable` object and returns the pair of filterable objects of the same type of elements which do and do not satisfy, the predicate, respectively. Filterable objects include plain objects or any object that has a filter method such as `Array`. See also `[filter](#filter)`, `[reject](#reject)`. ``` R.partition(R.includes('s'), ['sss', 'ttt', 'foo', 'bars']); // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] R.partition(R.includes('s'), { a: 'sss', b: 'ttt', foo: 'bars' }); // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ] ``` ### path Added in v0.2.0 ``` [Idx] → {a} → a | Undefined ``` `Idx = String | Int` #### Parameters * `path` The path to use. * `obj` The object to retrieve the nested property from. #### Returns * \* The data at `path`. Retrieve the value at a given path. See also `[prop](#prop)`, `[nth](#nth)`. ``` R.path(['a', 'b'], {a: {b: 2}}); //=> 2 R.path(['a', 'b'], {c: {b: 2}}); //=> undefined R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1 R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2 ``` ### pathEq Added in v0.7.0 ``` [Idx] → a → {a} → Boolean ``` `Idx = String | Int` #### Parameters * `path` The path of the nested property to use * `val` The value to compare the nested property with * `obj` The object to check the nested property in #### Returns * Boolean `true` if the value equals the nested object property, `false` otherwise. Determines whether a nested path on an object has a specific value, in [`R.equals`](#equals) terms. Most likely used to filter a list. ``` const user1 = { address: { zipCode: 90210 } }; const user2 = { address: { zipCode: 55555 } }; const user3 = { name: 'Bob' }; const users = [ user1, user2, user3 ]; const isFamous = R.pathEq(['address', 'zipCode'], 90210); R.filter(isFamous, users); //=> [ user1 ] ``` ### pathOr Added in v0.18.0 ``` a → [Idx] → {a} → a ``` `Idx = String | Int` #### Parameters * `d` The default value. * `p` The path to use. * `obj` The object to retrieve the nested property from. #### Returns * \* The data at `path` of the supplied object or the default value. If the given, non-null object has a value at the given path, returns the value at that path. Otherwise returns the provided default value. ``` R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" ``` ### paths Added in v0.27.0 ``` [Idx] → {a} → [a | Undefined] ``` `Idx = [String | Int]` #### Parameters * `pathsArray` The array of paths to be fetched. * `obj` The object to retrieve the nested properties from. #### Returns * Array A list consisting of values at paths specified by "pathsArray". Retrieves the values at given paths of an object. See also `[path](#path)`. ``` R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3] R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined] ``` ### pathSatisfies Added in v0.19.0 ``` (a → Boolean) → [Idx] → {a} → Boolean ``` `Idx = String | Int` #### Parameters * `pred` * `propPath` * `obj` #### Returns * Boolean Returns `true` if the specified object property at given path satisfies the given predicate; `false` otherwise. See also `[propSatisfies](#propSatisfies)`, `[path](#path)`. ``` R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true R.pathSatisfies(R.is(Object), [], {x: {y: 2}}); //=> true ``` ### pick Added in v0.1.0 ``` [k] → {k: v} → {k: v} ``` #### Parameters * `names` an array of String property names to copy onto a new object * `obj` The object to copy from #### Returns * Object A new object with only properties from `names` on it. Returns a partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored. See also `[omit](#omit)`, `[props](#props)`. ``` R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} ``` ### pickAll Added in v0.1.0 ``` [k] → {k: v} → {k: v} ``` #### Parameters * `names` an array of String property names to copy onto a new object * `obj` The object to copy from #### Returns * Object A new object with only properties from `names` on it. Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. See also `[pick](#pick)`. ``` R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} ``` ### pickBy Added in v0.8.0 ``` ((v, k) → Boolean) → {k: v} → {k: v} ``` #### Parameters * `pred` A predicate to determine whether or not a key should be included on the output object. * `obj` The object to copy from #### Returns * Object A new object with only properties that satisfy `pred` on it. Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. See also `[pick](#pick)`, `[filter](#filter)`. ``` const isUpperCase = (val, key) => key.toUpperCase() === key; R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} ``` ### pipe Added in v0.1.0 ``` (((a, b, …, n) → o), (o → p), …, (x → y), (y → z)) → ((a, b, …, n) → z) ``` #### Parameters * `functions` #### Returns * function Performs left-to-right function composition. The first argument may have any arity; the remaining arguments must be unary. In some libraries this function is named `sequence`. **Note:** The result of pipe is not automatically curried. See also `[compose](#compose)`. ``` const f = R.pipe(Math.pow, R.negate, R.inc); f(3, 4); // -(3^4) + 1 ``` ### pipeK Added in v0.16.0 Deprecated since v0.26.0 `Chain m => ((a → m b), (b → m c), …, (y → m z)) → (a → m z)` #### Parameters #### Returns * function Returns the left-to-right Kleisli composition of the provided functions, each of which must return a value of a type supported by [`chain`](#chain). `R.pipeK(f, g, h)` is equivalent to `R.pipe(f, R.chain(g), R.chain(h))`. See also `[composeK](#composeK)`. ``` // parseJson :: String -> Maybe * // get :: String -> Object -> Maybe * // getStateCode :: Maybe String -> Maybe String const getStateCode = R.pipeK( parseJson, get('user'), get('address'), get('state'), R.compose(Maybe.of, R.toUpper) ); getStateCode('{"user":{"address":{"state":"ny"}}}'); //=> Just('NY') getStateCode('[Invalid JSON]'); //=> Nothing() ``` ### pipeP Added in v0.10.0 Deprecated since v0.26.0 `((a → Promise b), (b → Promise c), …, (y → Promise z)) → (a → Promise z)` #### Parameters * `functions` #### Returns * function Performs left-to-right composition of one or more Promise-returning functions. The first argument may have any arity; the remaining arguments must be unary. See also `[composeP](#composeP)`. ``` // followersForUser :: String -> Promise [User] const followersForUser = R.pipeP(db.getUserById, db.getFollowers); ``` ### pipeWith Added in v0.26.0 ``` ((* → *), [((a, b, …, n) → o), (o → p), …, (x → y), (y → z)]) → ((a, b, …, n) → z) ``` #### Parameters * `functions` #### Returns * function Performs left-to-right function composition using transforming function. The first argument may have any arity; the remaining arguments must be unary. **Note:** The result of pipeWith is not automatically curried. Transforming function is not used on the first argument. See also `[composeWith](#composeWith)`, `[pipe](#pipe)`. ``` const pipeWhileNotNil = R.pipeWith((f, res) => R.isNil(res) ? res : f(res)); const f = pipeWhileNotNil([Math.pow, R.negate, R.inc]) f(3, 4); // -(3^4) + 1 ``` ### pluck Added in v0.1.0 ``` Functor f => k → f {k: v} → f v ``` #### Parameters * `key` The key name to pluck off of each object. * `f` The array or functor to consider. #### Returns * Array The list of values for the given key. Returns a new list by plucking the same named property off all objects in the list supplied. `pluck` will work on any [functor](https://github.com/fantasyland/fantasy-land#functor) in addition to arrays, as it is equivalent to `R.map(R.prop(k), f)`. See also `[props](#props)`. ``` var getAges = R.pluck('age'); getAges([{name: 'fred', age: 29}, {name: 'wilma', age: 27}]); //=> [29, 27] R.pluck(0, [[1, 2], [3, 4]]); //=> [1, 3] R.pluck('val', {a: {val: 3}, b: {val: 5}}); //=> {a: 3, b: 5} ``` ### prepend Added in v0.1.0 ``` a → [a] → [a] ``` #### Parameters * `el` The item to add to the head of the output list. * `list` The array to add to the tail of the output list. #### Returns * Array A new array. Returns a new list with the given element at the front, followed by the contents of the list. See also `[append](#append)`. ``` R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] ``` ### product Added in v0.1.0 ``` [Number] → Number ``` #### Parameters * `list` An array of numbers #### Returns * Number The product of all the numbers in the list. Multiplies together all the elements of a list. See also `[reduce](#reduce)`. ``` R.product([2,4,6,8,100,1]); //=> 38400 ``` ### project Added in v0.1.0 ``` [k] → [{k: v}] → [{k: v}] ``` #### Parameters * `props` The property names to project * `objs` The objects to query #### Returns * Array An array of objects with just the `props` properties. Reasonable analog to SQL `select` statement. ``` const abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; const fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; const kids = [abby, fred]; R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] ``` ### prop Added in v0.1.0 ``` Idx → {s: a} → a | Undefined ``` `Idx = String | Int` #### Parameters * `p` The property name or array index * `obj` The object to query #### Returns * \* The value at `obj.p`. Returns a function that when supplied an object returns the indicated property of that object, if it exists. See also `[path](#path)`, `[nth](#nth)`. ``` R.prop('x', {x: 100}); //=> 100 R.prop('x', {}); //=> undefined R.prop(0, [100]); //=> 100 R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4 ``` ### propEq Added in v0.1.0 ``` String → a → Object → Boolean ``` #### Parameters * `name` * `val` * `obj` #### Returns * Boolean Returns `true` if the specified object property is equal, in [`R.equals`](#equals) terms, to the given value; `false` otherwise. You can test multiple properties with [`R.whereEq`](#whereEq). See also `[whereEq](#whereEq)`, `[propSatisfies](#propSatisfies)`, `[equals](#equals)`. ``` const abby = {name: 'Abby', age: 7, hair: 'blond'}; const fred = {name: 'Fred', age: 12, hair: 'brown'}; const rusty = {name: 'Rusty', age: 10, hair: 'brown'}; const alois = {name: 'Alois', age: 15, disposition: 'surly'}; const kids = [abby, fred, rusty, alois]; const hasBrownHair = R.propEq('hair', 'brown'); R.filter(hasBrownHair, kids); //=> [fred, rusty] ``` ### propIs Added in v0.16.0 ``` Type → String → Object → Boolean ``` #### Parameters * `type` * `name` * `obj` #### Returns * Boolean Returns `true` if the specified object property is of the given type; `false` otherwise. See also `[is](#is)`, `[propSatisfies](#propSatisfies)`. ``` R.propIs(Number, 'x', {x: 1, y: 2}); //=> true R.propIs(Number, 'x', {x: 'foo'}); //=> false R.propIs(Number, 'x', {}); //=> false ``` ### propOr Added in v0.6.0 ``` a → String → Object → a ``` #### Parameters * `val` The default value. * `p` The name of the property to return. * `obj` The object to query. #### Returns * \* The value of given property of the supplied object or the default value. If the given, non-null object has an own property with the specified name, returns the value of that property. Otherwise returns the provided default value. ``` const alice = { name: 'ALICE', age: 101 }; const favorite = R.prop('favoriteLibrary'); const favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); favorite(alice); //=> undefined favoriteWithDefault(alice); //=> 'Ramda' ``` ### props Added in v0.1.0 ``` [k] → {k: v} → [v] ``` #### Parameters * `ps` The property names to fetch * `obj` The object to query #### Returns * Array The corresponding values or partially applied function. Acts as multiple `prop`: array of keys in, array of values out. Preserves order. ``` R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] const fullName = R.compose(R.join(' '), R.props(['first', 'last'])); fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' ``` ### propSatisfies Added in v0.16.0 ``` (a → Boolean) → String → {String: a} → Boolean ``` #### Parameters * `pred` * `name` * `obj` #### Returns * Boolean Returns `true` if the specified object property satisfies the given predicate; `false` otherwise. You can test multiple properties with [`R.where`](#where). See also `[where](#where)`, `[propEq](#propEq)`, `[propIs](#propIs)`. ``` R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true ``` ### range Added in v0.1.0 ``` Number → Number → [Number] ``` #### Parameters * `from` The first number in the list. * `to` One more than the last number in the list. #### Returns * Array The list of numbers in the set `[a, b)`. Returns a list of numbers from `from` (inclusive) to `to` (exclusive). ``` R.range(1, 5); //=> [1, 2, 3, 4] R.range(50, 53); //=> [50, 51, 52] ``` ### reduce Added in v0.1.0 ``` ((a, b) → a) → a → [b] → a ``` #### Parameters * `fn` The iterator function. Receives two values, the accumulator and the current element from the array. * `acc` The accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. Returns a single item by iterating through the list, successively calling the iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call. The iterator function receives two values: *(acc, value)*. It may use [`R.reduced`](#reduced) to shortcut the iteration. The arguments' order of [`reduceRight`](#reduceRight)'s iterator function is *(value, acc)*. Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike the native `Array.prototype.reduce` method. For more details on this behavior, see: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description> Dispatches to the `reduce` method of the third argument, if present. When doing so, it is up to the user to handle the [`R.reduced`](#reduced) shortcuting, as this is not implemented by `reduce`. See also `[reduced](#reduced)`, `[addIndex](#addIndex)`, `[reduceRight](#reduceRight)`. ``` R.reduce(R.subtract, 0, [1, 2, 3, 4]) // => ((((0 - 1) - 2) - 3) - 4) = -10 // - -10 // / \ / \ // - 4 -6 4 // / \ / \ // - 3 ==> -3 3 // / \ / \ // - 2 -1 2 // / \ / \ // 0 1 0 1 ``` ### reduceBy Added in v0.20.0 ``` ((a, b) → a) → a → (b → String) → [b] → {String: a} ``` #### Parameters * `valueFn` The function that reduces the elements of each group to a single value. Receives two values, accumulator for a particular group and the current element. * `acc` The (initial) accumulator value for each group. * `keyFn` The function that maps the list's element into a key. * `list` The array to group. #### Returns * Object An object with the output of `keyFn` for keys, mapped to the output of `valueFn` for elements which produced that key when passed to `keyFn`. Groups the elements of the list according to the result of calling the String-returning function `keyFn` on each element and reduces the elements of each group to a single value via the reducer function `valueFn`. This function is basically a more general [`groupBy`](#groupBy) function. Acts as a transducer if a transformer is given in list position. See also `[groupBy](#groupBy)`, `[reduce](#reduce)`. ``` const groupNames = (acc, {name}) => acc.concat(name) const toGrade = ({score}) => score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A' var students = [ {name: 'Abby', score: 83}, {name: 'Bart', score: 62}, {name: 'Curt', score: 88}, {name: 'Dora', score: 92}, ] reduceBy(groupNames, [], toGrade, students) //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]} ``` ### reduced Added in v0.15.0 ``` a → * ``` #### Parameters * `x` The final value of the reduce. #### Returns * \* The wrapped value. Returns a value wrapped to indicate that it is the final value of the reduce and transduce functions. The returned value should be considered a black box: the internal structure is not guaranteed to be stable. Note: this optimization is only available to the below functions: * [`reduce`](#reduce) * [`reduceWhile`](#reduceWhile) * [`transduce`](#transduce) See also `[reduce](#reduce)`, `[reduceWhile](#reduceWhile)`, `[transduce](#transduce)`. ``` R.reduce( (acc, item) => item > 3 ? R.reduced(acc) : acc.concat(item), [], [1, 2, 3, 4, 5]) // [1, 2, 3] ``` ### reduceRight Added in v0.1.0 ``` ((a, b) → b) → b → [a] → b ``` #### Parameters * `fn` The iterator function. Receives two values, the current element from the array and the accumulator. * `acc` The accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. Returns a single item by iterating through the list, successively calling the iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call. Similar to [`reduce`](#reduce), except moves through the input list from the right to the left. The iterator function receives two values: *(value, acc)*, while the arguments' order of `reduce`'s iterator function is *(acc, value)*. Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse arrays), unlike the native `Array.prototype.reduceRight` method. For more details on this behavior, see: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description> See also `[reduce](#reduce)`, `[addIndex](#addIndex)`. ``` R.reduceRight(R.subtract, 0, [1, 2, 3, 4]) // => (1 - (2 - (3 - (4 - 0)))) = -2 // - -2 // / \ / \ // 1 - 1 3 // / \ / \ // 2 - ==> 2 -1 // / \ / \ // 3 - 3 4 // / \ / \ // 4 0 4 0 ``` ### reduceWhile Added in v0.22.0 ``` ((a, b) → Boolean) → ((a, b) → a) → a → [b] → a ``` #### Parameters * `pred` The predicate. It is passed the accumulator and the current element. * `fn` The iterator function. Receives two values, the accumulator and the current element. * `a` The accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. Like [`reduce`](#reduce), `reduceWhile` returns a single item by iterating through the list, successively calling the iterator function. `reduceWhile` also takes a predicate that is evaluated before each step. If the predicate returns `false`, it "short-circuits" the iteration and returns the current value of the accumulator. See also `[reduce](#reduce)`, `[reduced](#reduced)`. ``` const isOdd = (acc, x) => x % 2 === 1; const xs = [1, 3, 5, 60, 777, 800]; R.reduceWhile(isOdd, R.add, 0, xs); //=> 9 const ys = [2, 4, 6] R.reduceWhile(isOdd, R.add, 111, ys); //=> 111 ``` ### reject Added in v0.1.0 ``` Filterable f => (a → Boolean) → f a → f a ``` #### Parameters * `pred` * `filterable` #### Returns * Array The complement of [`filter`](#filter). Acts as a transducer if a transformer is given in list position. Filterable objects include plain objects or any object that has a filter method such as `Array`. See also `[filter](#filter)`, `[transduce](#transduce)`, `[addIndex](#addIndex)`. ``` const isOdd = (n) => n % 2 === 1; R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} ``` ### remove Added in v0.2.2 ``` Number → Number → [a] → [a] ``` #### Parameters * `start` The position to start removing elements * `count` The number of elements to remove * `list` The list to remove from #### Returns * Array A new Array with `count` elements from `start` removed. Removes the sub-list of `list` starting at index `start` and containing `count` elements. *Note that this is not destructive*: it returns a copy of the list with the changes. No lists have been harmed in the application of this function. See also `[without](#without)`. ``` R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] ``` ### repeat Added in v0.1.1 ``` a → n → [a] ``` #### Parameters * `value` The value to repeat. * `n` The desired size of the output list. #### Returns * Array A new array containing `n` `value`s. Returns a fixed list of size `n` containing a specified identical value. See also `[times](#times)`. ``` R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] const obj = {}; const repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] repeatedObjs[0] === repeatedObjs[1]; //=> true ``` ### replace Added in v0.7.0 ``` RegExp|String → String → String → String ``` #### Parameters * `pattern` A regular expression or a substring to match. * `replacement` The string to replace the matches with. * `str` The String to do the search and replacement in. #### Returns * String The result. Replace a substring or regex match in a string with a replacement. The first two parameters correspond to the parameters of the `String.prototype.replace()` function, so the second parameter can also be a function. ``` R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' // Use the "g" (global) flag to replace all occurrences: R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' ``` ### reverse Added in v0.1.0 ``` [a] → [a] ``` `String → String` #### Parameters * `list` #### Returns * Array Returns a new list or string with the elements or characters in reverse order. ``` R.reverse([1, 2, 3]); //=> [3, 2, 1] R.reverse([1, 2]); //=> [2, 1] R.reverse([1]); //=> [1] R.reverse([]); //=> [] R.reverse('abc'); //=> 'cba' R.reverse('ab'); //=> 'ba' R.reverse('a'); //=> 'a' R.reverse(''); //=> '' ``` ### scan Added in v0.10.0 ``` ((a, b) → a) → a → [b] → [a] ``` #### Parameters * `fn` The iterator function. Receives two values, the accumulator and the current element from the array * `acc` The accumulator value. * `list` The list to iterate over. #### Returns * Array A list of all intermediately reduced values. Scan is similar to [`reduce`](#reduce), but returns a list of successively reduced values from the left See also `[reduce](#reduce)`, `[mapAccum](#mapAccum)`. ``` const numbers = [1, 2, 3, 4]; const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] ``` ### sequence Added in v0.19.0 ``` (Applicative f, Traversable t) => (a → f a) → t (f a) → f (t a) ``` #### Parameters * `of` * `traversable` #### Returns * \* Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable) of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an Applicative of Traversable. Dispatches to the `sequence` method of the second argument, if present. See also `[traverse](#traverse)`. ``` R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3]) R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing() R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)] R.sequence(R.of, Nothing()); //=> [Nothing()] ``` ### set Added in v0.16.0 ``` Lens s a → a → s → s ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `lens` * `v` * `x` #### Returns * \* Returns the result of "setting" the portion of the given data structure focused by the given lens to the given value. See also `[prop](#prop)`, `[lensIndex](#lensIndex)`, `[lensProp](#lensProp)`. ``` const xLens = R.lensProp('x'); R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2} ``` ### slice Added in v0.1.4 ``` Number → Number → [a] → [a] ``` `Number → Number → String → String` #### Parameters * `fromIndex` The start index (inclusive). * `toIndex` The end index (exclusive). * `list` #### Returns * \* Returns the elements of the given list or string (or object with a `slice` method) from `fromIndex` (inclusive) to `toIndex` (exclusive). Dispatches to the `slice` method of the third argument, if present. ``` R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd'] R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c'] R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] R.slice(0, 3, 'ramda'); //=> 'ram' ``` ### sort Added in v0.1.0 ``` ((a, a) → Number) → [a] → [a] ``` #### Parameters * `comparator` A sorting function :: a -> b -> Int * `list` The list to sort #### Returns * Array a new array with its elements sorted by the comparator function. Returns a copy of the list, sorted according to the comparator function, which should accept two values at a time and return a negative number if the first value is smaller, a positive number if it's larger, and zero if they are equal. Please note that this is a **copy** of the list. It does not modify the original. ``` const diff = function(a, b) { return a - b; }; R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] ``` ### sortBy Added in v0.1.0 ``` Ord b => (a → b) → [a] → [a] ``` #### Parameters * `fn` * `list` The list to sort. #### Returns * Array A new list sorted by the keys generated by `fn`. Sorts the list according to the supplied function. ``` const sortByFirstItem = R.sortBy(R.prop(0)); const pairs = [[-1, 1], [-2, 2], [-3, 3]]; sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] const sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); const alice = { name: 'ALICE', age: 101 }; const bob = { name: 'Bob', age: -10 }; const clara = { name: 'clara', age: 314.159 }; const people = [clara, bob, alice]; sortByNameCaseInsensitive(people); //=> [alice, bob, clara] ``` ### sortWith Added in v0.23.0 ``` [(a, a) → Number] → [a] → [a] ``` #### Parameters * `functions` A list of comparator functions. * `list` The list to sort. #### Returns * Array A new list sorted according to the comarator functions. Sorts a list according to a list of comparators. ``` const alice = { name: 'alice', age: 40 }; const bob = { name: 'bob', age: 30 }; const clara = { name: 'clara', age: 40 }; const people = [clara, bob, alice]; const ageNameSort = R.sortWith([ R.descend(R.prop('age')), R.ascend(R.prop('name')) ]); ageNameSort(people); //=> [alice, clara, bob] ``` ### split Added in v0.1.0 ``` (String | RegExp) → String → [String] ``` #### Parameters * `sep` The pattern. * `str` The string to separate into an array. #### Returns * Array The array of strings from `str` separated by `sep`. Splits a string into an array of strings based on the given separator. See also `[join](#join)`. ``` const pathComponents = R.split('/'); R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node'] R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] ``` ### splitAt Added in v0.19.0 ``` Number → [a] → [[a], [a]] ``` `Number → String → [String, String]` #### Parameters * `index` The index where the array/string is split. * `array` The array/string to be split. #### Returns * Array Splits a given list or string at a given index. ``` R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] R.splitAt(5, 'hello world'); //=> ['hello', ' world'] R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] ``` ### splitEvery Added in v0.16.0 ``` Number → [a] → [[a]] ``` `Number → String → [String]` #### Parameters * `n` * `list` #### Returns * Array Splits a collection into slices of the specified length. ``` R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]] R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz'] ``` ### splitWhen Added in v0.19.0 ``` (a → Boolean) → [a] → [[a], [a]] ``` #### Parameters * `pred` The predicate that determines where the array is split. * `list` The array to be split. #### Returns * Array Takes a list and a predicate and returns a pair of lists with the following properties: * the result of concatenating the two output lists is equivalent to the input list; * none of the elements of the first output list satisfies the predicate; and * if the second output list is non-empty, its first element satisfies the predicate. ``` R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] ``` ### startsWith Added in v0.24.0 ``` [a] → [a] → Boolean ``` `String → String → Boolean` #### Parameters * `prefix` * `list` #### Returns * Boolean Checks if a list starts with the provided sublist. Similarly, checks if a string starts with the provided substring. See also `[endsWith](#endsWith)`. ``` R.startsWith('a', 'abc') //=> true R.startsWith('b', 'abc') //=> false R.startsWith(['a'], ['a', 'b', 'c']) //=> true R.startsWith(['b'], ['a', 'b', 'c']) //=> false ``` ### subtract Added in v0.1.0 ``` Number → Number → Number ``` #### Parameters * `a` The first value. * `b` The second value. #### Returns * Number The result of `a - b`. Subtracts its second argument from its first argument. See also `[add](#add)`. ``` R.subtract(10, 8); //=> 2 const minus5 = R.subtract(R.__, 5); minus5(17); //=> 12 const complementaryAngle = R.subtract(90); complementaryAngle(30); //=> 60 complementaryAngle(72); //=> 18 ``` ### sum Added in v0.1.0 ``` [Number] → Number ``` #### Parameters * `list` An array of numbers #### Returns * Number The sum of all the numbers in the list. Adds together all the elements of a list. See also `[reduce](#reduce)`. ``` R.sum([2,4,6,8,100,1]); //=> 121 ``` ### symmetricDifference Added in v0.19.0 ``` [*] → [*] → [*] ``` #### Parameters * `list1` The first list. * `list2` The second list. #### Returns * Array The elements in `list1` or `list2`, but not both. Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. See also `[symmetricDifferenceWith](#symmetricDifferenceWith)`, `[difference](#difference)`, `[differenceWith](#differenceWith)`. ``` R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2] ``` ### symmetricDifferenceWith Added in v0.19.0 ``` ((a, a) → Boolean) → [a] → [a] → [a] ``` #### Parameters * `pred` A predicate used to test whether two items are equal. * `list1` The first list. * `list2` The second list. #### Returns * Array The elements in `list1` or `list2`, but not both. Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. Duplication is determined according to the value returned by applying the supplied predicate to two list elements. See also `[symmetricDifference](#symmetricDifference)`, `[difference](#difference)`, `[differenceWith](#differenceWith)`. ``` const eqA = R.eqBy(R.prop('a')); const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] ``` ### T Added in v0.9.0 ``` * → Boolean ``` #### Parameters #### Returns * Boolean A function that always returns `true`. Any passed in parameters are ignored. See also `[F](#F)`. ``` R.T(); //=> true ``` ### tail Added in v0.1.0 ``` [a] → [a] ``` `String → String` #### Parameters * `list` #### Returns * \* Returns all but the first element of the given list or string (or object with a `tail` method). Dispatches to the `slice` method of the first argument, if present. See also `[head](#head)`, `[init](#init)`, `[last](#last)`. ``` R.tail([1, 2, 3]); //=> [2, 3] R.tail([1, 2]); //=> [2] R.tail([1]); //=> [] R.tail([]); //=> [] R.tail('abc'); //=> 'bc' R.tail('ab'); //=> 'b' R.tail('a'); //=> '' R.tail(''); //=> '' ``` ### take Added in v0.1.0 ``` Number → [a] → [a] ``` `Number → String → String` #### Parameters * `n` * `list` #### Returns * \* Returns the first `n` elements of the given list, string, or transducer/transformer (or object with a `take` method). Dispatches to the `take` method of the second argument, if present. See also `[drop](#drop)`. ``` R.take(1, ['foo', 'bar', 'baz']); //=> ['foo'] R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.take(3, 'ramda'); //=> 'ram' const personnel = [ 'Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan', 'Bob Bates', 'Joe Dodge', 'Ron Crotty' ]; const takeFive = R.take(5); takeFive(personnel); //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan'] ``` ### takeLast Added in v0.16.0 ``` Number → [a] → [a] ``` `Number → String → String` #### Parameters * `n` The number of elements to return. * `xs` The collection to consider. #### Returns * Array Returns a new list containing the last `n` elements of the given list. If `n > list.length`, returns a list of `list.length` elements. See also `[dropLast](#dropLast)`. ``` R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] R.takeLast(3, 'ramda'); //=> 'mda' ``` ### takeLastWhile Added in v0.16.0 ``` (a → Boolean) → [a] → [a] ``` `(a → Boolean) → String → String` #### Parameters * `fn` The function called per iteration. * `xs` The collection to iterate over. #### Returns * Array A new array. Returns a new list containing the last `n` elements of a given list, passing each value to the supplied predicate function, and terminating when the predicate function returns `false`. Excludes the element that caused the predicate function to fail. The predicate function is passed one argument: *(value)*. See also `[dropLastWhile](#dropLastWhile)`, `[addIndex](#addIndex)`. ``` const isNotOne = x => x !== 1; R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] R.takeLastWhile(x => x !== 'R' , 'Ramda'); //=> 'amda' ``` ### takeWhile Added in v0.1.0 ``` (a → Boolean) → [a] → [a] ``` `(a → Boolean) → String → String` #### Parameters * `fn` The function called per iteration. * `xs` The collection to iterate over. #### Returns * Array A new array. Returns a new list containing the first `n` elements of a given list, passing each value to the supplied predicate function, and terminating when the predicate function returns `false`. Excludes the element that caused the predicate function to fail. The predicate function is passed one argument: *(value)*. Dispatches to the `takeWhile` method of the second argument, if present. Acts as a transducer if a transformer is given in list position. See also `[dropWhile](#dropWhile)`, `[transduce](#transduce)`, `[addIndex](#addIndex)`. ``` const isNotFour = x => x !== 4; R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3] R.takeWhile(x => x !== 'd' , 'Ramda'); //=> 'Ram' ``` ### tap Added in v0.1.0 ``` (a → *) → a → a ``` #### Parameters * `fn` The function to call with `x`. The return value of `fn` will be thrown away. * `x` #### Returns * \* `x`. Runs the given function with the supplied object, then returns the object. Acts as a transducer if a transformer is given as second parameter. ``` const sayX = x => console.log('x is ' + x); R.tap(sayX, 100); //=> 100 // logs 'x is 100' ``` ### test Added in v0.12.0 ``` RegExp → String → Boolean ``` #### Parameters * `pattern` * `str` #### Returns * Boolean Determines whether a given string matches a given regular expression. See also `[match](#match)`. ``` R.test(/^x/, 'xyz'); //=> true R.test(/^y/, 'xyz'); //=> false ``` ### thunkify Added in v0.26.0 ``` ((a, b, …, j) → k) → (a, b, …, j) → (() → k) ``` #### Parameters * `fn` A function to wrap in a thunk #### Returns * function Expects arguments for `fn` and returns a new function that, when called, applies those arguments to `fn`. Creates a thunk out of a function. A thunk delays a calculation until its result is needed, providing lazy evaluation of arguments. See also `[partial](#partial)`, `[partialRight](#partialRight)`. ``` R.thunkify(R.identity)(42)(); //=> 42 R.thunkify((a, b) => a + b)(25, 17)(); //=> 42 ``` ### times Added in v0.2.3 ``` (Number → a) → Number → [a] ``` #### Parameters * `fn` The function to invoke. Passed one argument, the current value of `n`. * `n` A value between `0` and `n - 1`. Increments after each function call. #### Returns * Array An array containing the return values of all calls to `fn`. Calls an input function `n` times, returning an array containing the results of those function calls. `fn` is passed one argument: The current value of `n`, which begins at `0` and is gradually incremented to `n - 1`. See also `[repeat](#repeat)`. ``` R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] ``` ### toLower Added in v0.9.0 ``` String → String ``` #### Parameters * `str` The string to lower case. #### Returns * String The lower case version of `str`. The lower case version of a string. See also `[toUpper](#toUpper)`. ``` R.toLower('XYZ'); //=> 'xyz' ``` ### toPairs Added in v0.4.0 ``` {String: *} → [[String,*]] ``` #### Parameters * `obj` The object to extract from #### Returns * Array An array of key, value arrays from the object's own properties. Converts an object into an array of key, value arrays. Only the object's own properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. See also `[fromPairs](#fromPairs)`. ``` R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] ``` ### toPairsIn Added in v0.4.0 ``` {String: *} → [[String,*]] ``` #### Parameters * `obj` The object to extract from #### Returns * Array An array of key, value arrays from the object's own and prototype properties. Converts an object into an array of key, value arrays. The object's own properties and prototype properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. ``` const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.toPairsIn(f); //=> [['x','X'], ['y','Y']] ``` ### toString Added in v0.14.0 ``` * → String ``` #### Parameters * `val` #### Returns * String Returns the string representation of the given value. `eval`'ing the output should result in a value equivalent to the input value. Many of the built-in `toString` methods do not satisfy this requirement. If the given value is an `[object Object]` with a `toString` method other than `Object.prototype.toString`, this method is invoked with no arguments to produce the return value. This means user-defined constructor functions can provide a suitable `toString` method. For example: ``` function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function() { return 'new Point(' + this.x + ', ' + this.y + ')'; }; R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' ``` ``` R.toString(42); //=> '42' R.toString('abc'); //=> '"abc"' R.toString([1, 2, 3]); //=> '[1, 2, 3]' R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' ``` ### toUpper Added in v0.9.0 ``` String → String ``` #### Parameters * `str` The string to upper case. #### Returns * String The upper case version of `str`. The upper case version of a string. See also `[toLower](#toLower)`. ``` R.toUpper('abc'); //=> 'ABC' ``` ### transduce Added in v0.12.0 ``` (c → c) → ((a, b) → a) → a → [b] → a ``` #### Parameters * `xf` The transducer function. Receives a transformer and returns a transformer. * `fn` The iterator function. Receives two values, the accumulator and the current element from the array. Wrapped as transformer, if necessary, and used to initialize the transducer * `acc` The initial accumulator value. * `list` The list to iterate over. #### Returns * \* The final, accumulated value. Initializes a transducer using supplied iterator function. Returns a single item by iterating through the list, successively calling the transformed iterator function and passing it an accumulator value and the current value from the array, and then passing the result to the next call. The iterator function receives two values: *(acc, value)*. It will be wrapped as a transformer to initialize the transducer. A transformer can be passed directly in place of an iterator function. In both cases, iteration may be stopped early with the [`R.reduced`](#reduced) function. A transducer is a function that accepts a transformer and returns a transformer and can be composed directly. A transformer is an an object that provides a 2-arity reducing iterator function, step, 0-arity initial value function, init, and 1-arity result extraction function, result. The step function is used as the iterator function in reduce. The result function is used to convert the final accumulator into the return type and in most cases is [`R.identity`](#identity). The init function can be used to provide an initial accumulator, but is ignored by transduce. The iteration is performed with [`R.reduce`](#reduce) after initializing the transducer. See also `[reduce](#reduce)`, `[reduced](#reduced)`, `[into](#into)`. ``` const numbers = [1, 2, 3, 4]; const transducer = R.compose(R.map(R.add(1)), R.take(2)); R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3] const isOdd = (x) => x % 2 === 1; const firstOddTransducer = R.compose(R.filter(isOdd), R.take(1)); R.transduce(firstOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [1] ``` ### transpose Added in v0.19.0 ``` [[a]] → [[a]] ``` #### Parameters * `list` A 2D list #### Returns * Array A 2D list Transposes the rows and columns of a 2D list. When passed a list of `n` lists of length `x`, returns a list of `x` lists of length `n`. ``` R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] // If some of the rows are shorter than the following rows, their elements are skipped: R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] ``` ### traverse Added in v0.19.0 ``` (Applicative f, Traversable t) => (a → f a) → (a → f b) → t a → f (t b) ``` #### Parameters * `of` * `f` * `traversable` #### Returns * \* Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable), then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative into an Applicative of Traversable. Dispatches to the `traverse` method of the third argument, if present. See also `[sequence](#sequence)`. ``` // Returns `Maybe.Nothing` if the given divisor is `0` const safeDiv = n => d => d === 0 ? Maybe.Nothing() : Maybe.Just(n / d) R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Maybe.Just([5, 2.5, 2]) R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Maybe.Nothing ``` ### trim Added in v0.6.0 ``` String → String ``` #### Parameters * `str` The string to trim. #### Returns * String Trimmed version of `str`. Removes (strips) whitespace from both ends of the string. ``` R.trim(' xyz '); //=> 'xyz' R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z'] ``` ### tryCatch Added in v0.20.0 ``` (…x → a) → ((e, …x) → a) → (…x → a) ``` #### Parameters * `tryer` The function that may throw. * `catcher` The function that will be evaluated if `tryer` throws. #### Returns * function A new function that will catch exceptions and send then to the catcher. `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned function evaluates the `tryer`; if it does not throw, it simply returns the result. If the `tryer` *does* throw, the returned function evaluates the `catcher` function and returns its result. Note that for effective composition with this function, both the `tryer` and `catcher` functions must return the same type of results. ``` R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true R.tryCatch(() => { throw 'foo'}, R.always('catched'))('bar') // => 'catched' R.tryCatch(R.times(R.identity), R.always([]))('s') // => [] R.tryCatch(() => { throw 'this is not a valid value'}, (err, value)=>({error : err, value }))('bar') // => {'error': 'this is not a valid value', 'value': 'bar'} ``` ### type Added in v0.8.0 ``` (* → {*}) → String ``` #### Parameters * `val` The value to test #### Returns * String Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them all as 'Object'. ``` R.type({}); //=> "Object" R.type(1); //=> "Number" R.type(false); //=> "Boolean" R.type('s'); //=> "String" R.type(null); //=> "Null" R.type([]); //=> "Array" R.type(/[A-z]/); //=> "RegExp" R.type(() => {}); //=> "Function" R.type(undefined); //=> "Undefined" ``` ### unapply Added in v0.8.0 ``` ([*…] → a) → (*… → a) ``` #### Parameters * `fn` #### Returns * function Takes a function `fn`, which takes a single array argument, and returns a function which: * takes any number of positional arguments; * passes these arguments to `fn` as an array; and * returns the result. In other words, `R.unapply` derives a variadic function from a function which takes an array. `R.unapply` is the inverse of [`R.apply`](#apply). See also `[apply](#apply)`. ``` R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' ``` ### unary Added in v0.2.0 ``` (* → b) → (a → b) ``` #### Parameters * `fn` The function to wrap. #### Returns * function A new function wrapping `fn`. The new function is guaranteed to be of arity 1. Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. Any extraneous parameters will not be passed to the supplied function. See also `[binary](#binary)`, `[nAry](#nAry)`. ``` const takesTwoArgs = function(a, b) { return [a, b]; }; takesTwoArgs.length; //=> 2 takesTwoArgs(1, 2); //=> [1, 2] const takesOneArg = R.unary(takesTwoArgs); takesOneArg.length; //=> 1 // Only 1 argument is passed to the wrapped function takesOneArg(1, 2); //=> [1, undefined] ``` ### uncurryN Added in v0.14.0 ``` Number → (a → b) → (a → c) ``` #### Parameters * `length` The arity for the returned function. * `fn` The function to uncurry. #### Returns * function A new function. Returns a function of arity `n` from a (manually) curried function. See also `[curry](#curry)`. ``` const addFour = a => b => c => d => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); uncurriedAddFour(1, 2, 3, 4); //=> 10 ``` ### unfold Added in v0.10.0 ``` (a → [b]) → * → [b] ``` #### Parameters * `fn` The iterator function. receives one argument, `seed`, and returns either false to quit iteration or an array of length two to proceed. The element at index 0 of this array will be added to the resulting array, and the element at index 1 will be passed to the next call to `fn`. * `seed` The seed value. #### Returns * Array The final list. Builds a list from a seed value. Accepts an iterator function, which returns either false to stop iteration or an array of length 2 containing the value to add to the resulting list and the seed to be used in the next call to the iterator function. The iterator function receives one argument: *(seed)*. ``` const f = n => n > 50 ? false : [-n, n + 10]; R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] ``` ### union Added in v0.1.0 ``` [*] → [*] → [*] ``` #### Parameters * `as` The first list. * `bs` The second list. #### Returns * Array The first and second lists concatenated, with duplicates removed. Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. ``` R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] ``` ### unionWith Added in v0.1.0 ``` ((a, a) → Boolean) → [*] → [*] → [*] ``` #### Parameters * `pred` A predicate used to test whether two items are equal. * `list1` The first list. * `list2` The second list. #### Returns * Array The first and second lists concatenated, with duplicates removed. Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements. See also `[union](#union)`. ``` const l1 = [{a: 1}, {a: 2}]; const l2 = [{a: 1}, {a: 4}]; R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] ``` ### uniq Added in v0.1.0 ``` [a] → [a] ``` #### Parameters * `list` The array to consider. #### Returns * Array The list of unique items. Returns a new list containing only one copy of each element in the original list. [`R.equals`](#equals) is used to determine equality. ``` R.uniq([1, 1, 2, 1]); //=> [1, 2] R.uniq([1, '1']); //=> [1, '1'] R.uniq([[42], [42]]); //=> [[42]] ``` ### uniqBy Added in v0.16.0 ``` (a → b) → [a] → [a] ``` #### Parameters * `fn` A function used to produce a value to use during comparisons. * `list` The array to consider. #### Returns * Array The list of unique items. Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied function to each list element. Prefers the first item if the supplied function produces the same value on two items. [`R.equals`](#equals) is used for comparison. ``` R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] ``` ### uniqWith Added in v0.2.0 ``` ((a, a) → Boolean) → [a] → [a] ``` #### Parameters * `pred` A predicate used to test whether two items are equal. * `list` The array to consider. #### Returns * Array The list of unique items. Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied predicate to two list elements. Prefers the first item if two items compare equal based on the predicate. ``` const strEq = R.eqBy(String); R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] R.uniqWith(strEq)([{}, {}]); //=> [{}] R.uniqWith(strEq)([1, '1', 1]); //=> [1] R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] ``` ### unless Added in v0.18.0 ``` (a → Boolean) → (a → a) → a → a ``` #### Parameters * `pred` A predicate function * `whenFalseFn` A function to invoke when the `pred` evaluates to a falsy value. * `x` An object to test with the `pred` function and pass to `whenFalseFn` if necessary. #### Returns * \* Either `x` or the result of applying `x` to `whenFalseFn`. Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, the function will return the result of calling the `whenFalseFn` function with the same argument. If the predicate is satisfied, the argument is returned as is. See also `[ifElse](#ifElse)`, `[when](#when)`, `[cond](#cond)`. ``` let safeInc = R.unless(R.isNil, R.inc); safeInc(null); //=> null safeInc(1); //=> 2 ``` ### unnest Added in v0.3.0 ``` Chain c => c (c a) → c a ``` #### Parameters * `list` #### Returns * \* Shorthand for `R.chain(R.identity)`, which removes one level of nesting from any [Chain](https://github.com/fantasyland/fantasy-land#chain). See also `[flatten](#flatten)`, `[chain](#chain)`. ``` R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] ``` ### until Added in v0.20.0 ``` (a → Boolean) → (a → a) → a → a ``` #### Parameters * `pred` A predicate function * `fn` The iterator function * `init` Initial value #### Returns * \* Final value that satisfies predicate Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as the initial value. It does so by applying the transformation until the predicate is satisfied, at which point it returns the satisfactory value. ``` R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128 ``` ### update Added in v0.14.0 ``` Number → a → [a] → [a] ``` #### Parameters * `idx` The index to update. * `x` The value to exist at the given index of the returned array. * `list` The source array-like object to be updated. #### Returns * Array A copy of `list` with the value at index `idx` replaced with `x`. Returns a new copy of the array with the element at the provided index replaced with the given value. See also `[adjust](#adjust)`. ``` R.update(1, '_', ['a', 'b', 'c']); //=> ['a', '_', 'c'] R.update(-1, '_', ['a', 'b', 'c']); //=> ['a', 'b', '_'] ``` ### useWith Added in v0.1.0 ``` ((x1, x2, …) → z) → [(a → x1), (b → x2), …] → (a → b → … → z) ``` #### Parameters * `fn` The function to wrap. * `transformers` A list of transformer functions #### Returns * function The wrapped function. Accepts a function `fn` and a list of transformer functions and returns a new curried function. When the new function is invoked, it calls the function `fn` with parameters consisting of the result of calling each supplied handler on successive arguments to the new function. If more arguments are passed to the returned function than transformer functions, those arguments are passed directly to `fn` as additional parameters. If you expect additional arguments that don't need to be transformed, although you can ignore them, it's best to pass an identity function so that the new function reports the correct arity. See also `[converge](#converge)`. ``` R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81 R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81 R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32 R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32 ``` ### values Added in v0.1.0 ``` {k: v} → [v] ``` #### Parameters * `obj` The object to extract values from #### Returns * Array An array of the values of the object's own properties. Returns a list of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed across different JS platforms. See also `[valuesIn](#valuesIn)`, `[keys](#keys)`. ``` R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] ``` ### valuesIn Added in v0.2.0 ``` {k: v} → [v] ``` #### Parameters * `obj` The object to extract values from #### Returns * Array An array of the values of the object's own and prototype properties. Returns a list of all the properties, including prototype properties, of the supplied object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. See also `[values](#values)`, `[keysIn](#keysIn)`. ``` const F = function() { this.x = 'X'; }; F.prototype.y = 'Y'; const f = new F(); R.valuesIn(f); //=> ['X', 'Y'] ``` ### view Added in v0.16.0 ``` Lens s a → s → a ``` `Lens s a = Functor f => (a → f a) → s → f s` #### Parameters * `lens` * `x` #### Returns * \* Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which portion of the data structure is visible. See also `[prop](#prop)`, `[lensIndex](#lensIndex)`, `[lensProp](#lensProp)`. ``` const xLens = R.lensProp('x'); R.view(xLens, {x: 1, y: 2}); //=> 1 R.view(xLens, {x: 4, y: 2}); //=> 4 ``` ### when Added in v0.18.0 ``` (a → Boolean) → (a → a) → a → a ``` #### Parameters * `pred` A predicate function * `whenTrueFn` A function to invoke when the `condition` evaluates to a truthy value. * `x` An object to test with the `pred` function and pass to `whenTrueFn` if necessary. #### Returns * \* Either `x` or the result of applying `x` to `whenTrueFn`. Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function will return the result of calling the `whenTrueFn` function with the same argument. If the predicate is not satisfied, the argument is returned as is. See also `[ifElse](#ifElse)`, `[unless](#unless)`, `[cond](#cond)`. ``` // truncate :: String -> String const truncate = R.when( R.propSatisfies(R.gt(R.__, 10), 'length'), R.pipe(R.take(10), R.append('…'), R.join('')) ); truncate('12345'); //=> '12345' truncate('0123456789ABC'); //=> '0123456789…' ``` ### where Added in v0.1.1 ``` {String: (* → Boolean)} → {String: *} → Boolean ``` #### Parameters * `spec` * `testObj` #### Returns * Boolean Takes a spec object and a test object; returns true if the test satisfies the spec. Each of the spec's own properties must be a predicate function. Each predicate is applied to the value of the corresponding property of the test object. `where` returns true if all the predicates return true, false otherwise. `where` is well suited to declaratively expressing constraints for other functions such as [`filter`](#filter) and [`find`](#find). See also `[propSatisfies](#propSatisfies)`, `[whereEq](#whereEq)`. ``` // pred :: Object -> Boolean const pred = R.where({ a: R.equals('foo'), b: R.complement(R.equals('bar')), x: R.gt(R.__, 10), y: R.lt(R.__, 20) }); pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false ``` ### whereEq Added in v0.14.0 ``` {String: *} → {String: *} → Boolean ``` #### Parameters * `spec` * `testObj` #### Returns * Boolean Takes a spec object and a test object; returns true if the test satisfies the spec, false otherwise. An object satisfies the spec if, for each of the spec's own properties, accessing that property of the object gives the same value (in [`R.equals`](#equals) terms) as accessing that property of the spec. `whereEq` is a specialization of [`where`](#where). See also `[propEq](#propEq)`, `[where](#where)`. ``` // pred :: Object -> Boolean const pred = R.whereEq({a: 1, b: 2}); pred({a: 1}); //=> false pred({a: 1, b: 2}); //=> true pred({a: 1, b: 2, c: 3}); //=> true pred({a: 1, b: 1}); //=> false ``` ### without Added in v0.19.0 ``` [a] → [a] → [a] ``` #### Parameters * `list1` The values to be removed from `list2`. * `list2` The array to remove values from. #### Returns * Array The new array without values in `list1`. Returns a new list without values in the first argument. [`R.equals`](#equals) is used to determine equality. Acts as a transducer if a transformer is given in list position. See also `[transduce](#transduce)`, `[difference](#difference)`, `[remove](#remove)`. ``` R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] ``` ### xor Added in v0.27.0 ``` a → b → Boolean ``` #### Parameters * `a` * `b` #### Returns * Boolean true if one of the arguments is truthy and the other is falsy Exclusive disjunction logical operation. Returns `true` if one of the arguments is truthy and the other is falsy. Otherwise, it returns `false`. See also `[or](#or)`, `[and](#and)`. ``` R.xor(true, true); //=> false R.xor(true, false); //=> true R.xor(false, true); //=> true R.xor(false, false); //=> false ``` ### xprod Added in v0.1.0 ``` [a] → [b] → [[a,b]] ``` #### Parameters * `as` The first list. * `bs` The second list. #### Returns * Array The list made by combining each possible pair from `as` and `bs` into pairs (`[a, b]`). Creates a new list out of the two supplied by creating each possible pair from the lists. ``` R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] ``` ### zip Added in v0.1.0 ``` [a] → [b] → [[a,b]] ``` #### Parameters * `list1` The first array to consider. * `list2` The second array to consider. #### Returns * Array The list made by pairing up same-indexed elements of `list1` and `list2`. Creates a new list out of the two supplied by pairing up equally-positioned items from both lists. The returned list is truncated to the length of the shorter of the two input lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. ``` R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] ``` ### zipObj Added in v0.3.0 ``` [String] → [*] → {String: *} ``` #### Parameters * `keys` The array that will be properties on the output object. * `values` The list of values on the output object. #### Returns * Object The object made by pairing up same-indexed elements of `keys` and `values`. Creates a new object out of a list of keys and a list of values. Key/value pairing is truncated to the length of the shorter of the two lists. Note: `zipObj` is equivalent to `pipe(zip, fromPairs)`. ``` R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} ``` ### zipWith Added in v0.1.0 ``` ((a, b) → c) → [a] → [b] → [c] ``` #### Parameters * `fn` The function used to combine the two elements into one value. * `list1` The first array to consider. * `list2` The second array to consider. #### Returns * Array The list made by combining same-indexed elements of `list1` and `list2` using `fn`. Creates a new list out of the two supplied by applying the function to each equally-positioned pair in the lists. The returned list is truncated to the length of the shorter of the two input lists. ``` const f = (x, y) => { // ... }; R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] ```
programming_docs
jq jq 1.6 Manual jq 1.6 Manual ============= *The manual for the development version of jq can be found [here](https://stedolan.github.io/jq/manual).* A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks. Filters can be combined in various ways - you can pipe the output of one filter into another filter, or collect the output of a filter into an array. Some filters produce multiple results, for instance there's one that produces all the elements of its input array. Piping that filter into a second runs the second filter for each element of the array. Generally, things that would be done with loops and iteration in other languages are just done by gluing filters together in jq. It's important to remember that every filter has an input and an output. Even literals like "hello" or 42 are filters - they take an input but always produce the same literal as output. Operations that combine two filters, like addition, generally feed the same input to both and combine the results. So, you can implement an averaging filter as `add / length` - feeding the input array both to the `add` filter and the `length` filter and then performing the division. But that's getting ahead of ourselves. :) Let's start with something simpler: Invoking jq ----------- jq filters run on a stream of JSON data. The input to jq is parsed as a sequence of whitespace-separated JSON values which are passed through the provided filter one at a time. The output(s) of the filter are written to standard out, again as a sequence of whitespace-separated JSON data. Note: it is important to mind the shell's quoting rules. As a general rule it's best to always quote (with single-quote characters) the jq program, as too many characters with special meaning to jq are also shell meta-characters. For example, `jq "foo"` will fail on most Unix shells because that will be the same as `jq foo`, which will generally fail because `foo is not defined`. When using the Windows command shell (cmd.exe) it's best to use double quotes around your jq program when given on the command-line (instead of the `-f program-file` option), but then double-quotes in the jq program need backslash escaping. You can affect how jq reads and writes its input and output using some command-line options: * `--version`: Output the jq version and exit with zero. * `--seq`: Use the `application/json-seq` MIME type scheme for separating JSON texts in jq's input and output. This means that an ASCII RS (record separator) character is printed before each value on output and an ASCII LF (line feed) is printed after every output. Input JSON texts that fail to parse are ignored (but warned about), discarding all subsequent input until the next RS. This mode also parses the output of jq without the `--seq` option. * `--stream`: Parse the input in streaming fashion, outputting arrays of path and leaf values (scalars and empty arrays or empty objects). For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]` becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`. This is useful for processing very large inputs. Use this in conjunction with filtering and the `reduce` and `foreach` syntax to reduce large inputs incrementally. * `--slurp`/`-s`: Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once. * `--raw-input`/`-R`: Don't parse the input as JSON. Instead, each line of text is passed to the filter as a string. If combined with `--slurp`, then the entire input is passed to the filter as a single long string. * `--null-input`/`-n`: Don't read any input at all! Instead, the filter is run once using `null` as the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch. * `--compact-output` / `-c`: By default, jq pretty-prints JSON output. Using this option will result in more compact output by instead putting each JSON object on a single line. * `--tab`: Use a tab for each indentation level instead of two spaces. * `--indent n`: Use the given number of spaces (no more than 7) for indentation. * `--color-output` / `-C` and `--monochrome-output` / `-M`: By default, jq outputs colored JSON if writing to a terminal. You can force it to produce color even if writing to a pipe or a file using `-C`, and disable color with `-M`. Colors can be configured with the `JQ_COLORS` environment variable (see below). * `--ascii-output` / `-a`: jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence. * `--unbuffered` Flush the output after each JSON object is printed (useful if you're piping a slow data source into jq and piping jq's output elsewhere). * `--sort-keys` / `-S`: Output the fields of each object with the keys in sorted order. * `--raw-output` / `-r`: With this option, if the filter's result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems. * `--join-output` / `-j`: Like `-r` but jq won't print a newline after each output. * `-f filename` / `--from-file filename`: Read filter from the file rather than from a command line, like awk's -f option. You can also use '#' to make comments. * `-Ldirectory` / `-L directory`: Prepend `directory` to the search list for modules. If this option is used then no builtin search list is used. See the section on modules below. * `-e` / `--exit-status`: Sets the exit status of jq to 0 if the last output values was neither `false` nor `null`, 1 if the last output value was either `false` or `null`, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran. Another way to set the exit status is with the `halt_error` builtin function. * `--arg name value`: This option passes a value to the jq program as a predefined variable. If you run jq with `--arg foo bar`, then `$foo` is available in the program and has the value `"bar"`. Note that `value` will be treated as a string, so `--arg foo 123` will bind `$foo` to `"123"`. Named arguments are also available to the jq program as `$ARGS.named`. * `--argjson name JSON-text`: This option passes a JSON-encoded value to the jq program as a predefined variable. If you run jq with `--argjson foo 123`, then `$foo` is available in the program and has the value `123`. * `--slurpfile variable-name filename`: This option reads all the JSON texts in the named file and binds an array of the parsed JSON values to the given global variable. If you run jq with `--slurpfile foo bar`, then `$foo` is available in the program and has an array whose elements correspond to the texts in the file named `bar`. * `--rawfile variable-name filename`: This option reads in the named file and binds its contents to the given global variable. If you run jq with `--rawfile foo bar`, then `$foo` is available in the program and has a string whose contents are to the texs in the file named `bar`. * `--argfile variable-name filename`: Do not use. Use `--slurpfile` instead. (This option is like `--slurpfile`, but when the file has just one text, then that is used, else an array of texts is used as in `--slurpfile`.) * `--args`: Remaining arguments are positional string arguments. These are available to the jq program as `$ARGS.positional[]`. * `--jsonargs`: Remaining arguments are positional JSON text arguments. These are available to the jq program as `$ARGS.positional[]`. * `--run-tests [filename]`: Runs the tests in the given file or standard input. This must be the last option given and does not honor all preceding options. The input consists of comment lines, empty lines, and program lines followed by one input line, as many lines of output as are expected (one per output), and a terminating empty line. Compilation failure tests start with a line containing only "%%FAIL", then a line containing the program to compile, then a line containing an error message to compare to the actual. Be warned that this option can change backwards-incompatibly. Basic filters ------------- ### Identity: `.` The absolute simplest filter is `.` . This is a filter that takes its input and produces it unchanged as output. That is, this is the identity operator. Since jq by default pretty-prints all output, this trivial program can be a useful way of formatting JSON output from, say, `curl`. An important point about the identity filter is that it guarantees to preserve the literal decimal representation of values. This is particularly important when dealing with numbers which can't be losslessly converted to an IEEE754 double precision representation. jq doesn't truncate the literal numbers to double unless there is a need to make arithmetic operations with the number. Comparisons are carried out over the untruncated big decimal representation of the number. jq will also try to maintain the original decimal precision of the provided number literal. See below for examples. #### Examples | | | | --- | --- | | | jq '.' | | Input | "Hello, world!" | | Output | "Hello, world!" | | | | | --- | --- | | | jq '. | tojson' | | Input | 12345678909876543212345 | | Output | "12345678909876543212345" | | | | | --- | --- | | | jq 'map([., . == 1]) | tojson' | | Input | [1, 1.000, 1.0, 100e-2] | | Output | "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" | | | | | --- | --- | | | jq '. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000)' | | Input | 10000000000000000000000000000001 | | Output | [true, false] | ### Object Identifier-Index: `.foo`, `.foo.bar` The simplest *useful* filter is `.foo`. When given a JSON object (aka dictionary or hash) as input, it produces the value at the key "foo", or null if there's none present. A filter of the form `.foo.bar` is equivalent to `.foo|.bar`. This syntax only works for simple, identifier-like keys, that is, keys that are all made of alphanumeric characters and underscore, and which do not start with a digit. If the key contains special characters or starts with a digit, you need to surround it with double quotes like this: `."foo$"`, or else `.["foo$"]`. For example `.["foo::bar"]` and `.["foo.bar"]` work while `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`. #### Examples | | | | --- | --- | | | jq '.foo' | | Input | {"foo": 42, "bar": "less interesting data"} | | Output | 42 | | | | | --- | --- | | | jq '.foo' | | Input | {"notfoo": true, "alsonotfoo": false} | | Output | null | | | | | --- | --- | | | jq '.["foo"]' | | Input | {"foo": 42} | | Output | 42 | ### Optional Object Identifier-Index: `.foo?` Just like `.foo`, but does not output even an error when `.` is not an array or an object. #### Examples | | | | --- | --- | | | jq '.foo?' | | Input | {"foo": 42, "bar": "less interesting data"} | | Output | 42 | | | | | --- | --- | | | jq '.foo?' | | Input | {"notfoo": true, "alsonotfoo": false} | | Output | null | | | | | --- | --- | | | jq '.["foo"]?' | | Input | {"foo": 42} | | Output | 42 | | | | | --- | --- | | | jq '[.foo?]' | | Input | [1,2] | | Output | [] | ### Generic Object Index: `.[<string>]` You can also look up fields of an object using syntax like `.["foo"]` (.foo above is a shorthand version of this, but only for identifier-like strings). ### Array Index: `.[2]` When the index value is an integer, `.[<value>]` can index arrays. Arrays are zero-based, so `.[2]` returns the third element. Negative indices are allowed, with -1 referring to the last element, -2 referring to the next to last element, and so on. #### Examples | | | | --- | --- | | | jq '.[0]' | | Input | [{"name":"JSON", "good":true}, {"name":"XML", "good":false}] | | Output | {"name":"JSON", "good":true} | | | | | --- | --- | | | jq '.[2]' | | Input | [{"name":"JSON", "good":true}, {"name":"XML", "good":false}] | | Output | null | | | | | --- | --- | | | jq '.[-2]' | | Input | [1,2,3] | | Output | 2 | ### Array/String Slice: `.[10:15]` The `.[10:15]` syntax can be used to return a subarray of an array or substring of a string. The array returned by `.[10:15]` will be of length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive). Either index may be negative (in which case it counts backwards from the end of the array), or omitted (in which case it refers to the start or end of the array). #### Examples | | | | --- | --- | | | jq '.[2:4]' | | Input | ["a","b","c","d","e"] | | Output | ["c", "d"] | | | | | --- | --- | | | jq '.[2:4]' | | Input | "abcdefghi" | | Output | "cd" | | | | | --- | --- | | | jq '.[:3]' | | Input | ["a","b","c","d","e"] | | Output | ["a", "b", "c"] | | | | | --- | --- | | | jq '.[-2:]' | | Input | ["a","b","c","d","e"] | | Output | ["d", "e"] | ### Array/Object Value Iterator: `.[]` If you use the `.[index]` syntax, but omit the index entirely, it will return *all* of the elements of an array. Running `.[]` with the input `[1,2,3]` will produce the numbers as three separate results, rather than as a single array. You can also use this on an object, and it will return all the values of the object. #### Examples | | | | --- | --- | | | jq '.[]' | | Input | [{"name":"JSON", "good":true}, {"name":"XML", "good":false}] | | Output | {"name":"JSON", "good":true} | | | {"name":"XML", "good":false} | | | | | --- | --- | | | jq '.[]' | | Input | [] | | Output | *none* | | | | | --- | --- | | | jq '.[]' | | Input | {"a": 1, "b": 1} | | Output | 1 | | | 1 | ### `.[]?` Like `.[]`, but no errors will be output if . is not an array or object. ### Comma: `,` If two filters are separated by a comma, then the same input will be fed into both and the two filters' output value streams will be concatenated in order: first, all of the outputs produced by the left expression, and then all of the outputs produced by the right. For instance, filter `.foo, .bar`, produces both the "foo" fields and "bar" fields as separate outputs. #### Examples | | | | --- | --- | | | jq '.foo, .bar' | | Input | {"foo": 42, "bar": "something else", "baz": true} | | Output | 42 | | | "something else" | | | | | --- | --- | | | jq '.user, .projects[]' | | Input | {"user":"stedolan", "projects": ["jq", "wikiflow"]} | | Output | "stedolan" | | | "jq" | | | "wikiflow" | | | | | --- | --- | | | jq '.[4,2]' | | Input | ["a","b","c","d","e"] | | Output | "e" | | | "c" | ### Pipe: `|` The | operator combines two filters by feeding the output(s) of the one on the left into the input of the one on the right. It's pretty much the same as the Unix shell's pipe, if you're used to that. If the one on the left produces multiple results, the one on the right will be run for each of those results. So, the expression `.[] | .foo` retrieves the "foo" field of each element of the input array. Note that `.a.b.c` is the same as `.a | .b | .c`. Note too that `.` is the input value at the particular stage in a "pipeline", specifically: where the `.` expression appears. Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the middle refers to whatever value `.a` produced. #### Example | | | | --- | --- | | | jq '.[] | .name' | | Input | [{"name":"JSON", "good":true}, {"name":"XML", "good":false}] | | Output | "JSON" | | | "XML" | ### Parenthesis Parenthesis work as a grouping operator just as in any typical programming language. #### Example | | | | --- | --- | | | jq '(. + 2) \* 5' | | Input | 1 | | Output | 15 | Types and Values ---------------- jq supports the same set of datatypes as JSON - numbers, strings, booleans, arrays, objects (which in JSON-speak are hashes with only string keys), and "null". Booleans, null, strings and numbers are written the same way as in javascript. Just like everything else in jq, these simple values take an input and produce an output - `42` is a valid jq expression that takes an input, ignores it, and returns 42 instead. Numbers in jq are internally represented by their IEEE754 double precision approximation. Any arithmetic operation with numbers, whether they are literals or results of previous filters, will produce a double precision floating point result. However, when parsing a literal jq will store the original literal string. If no mutation is applied to this value then it will make to the output in its original form, even if conversion to double would result in a loss. ### Array construction: `[]` As in JSON, `[]` is used to construct arrays, as in `[1,2,3]`. The elements of the arrays can be any jq expression, including a pipeline. All of the results produced by all of the expressions are collected into one big array. You can use it to construct an array out of a known quantity of values (as in `[.foo, .bar, .baz]`) or to "collect" all the results of a filter into an array (as in `[.items[].name]`) Once you understand the "," operator, you can look at jq's array syntax in a different light: the expression `[1,2,3]` is not using a built-in syntax for comma-separated arrays, but is instead applying the `[]` operator (collect results) to the expression 1,2,3 (which produces three different results). If you have a filter `X` that produces four results, then the expression `[X]` will produce a single result, an array of four elements. #### Examples | | | | --- | --- | | | jq '[.user, .projects[]]' | | Input | {"user":"stedolan", "projects": ["jq", "wikiflow"]} | | Output | ["stedolan", "jq", "wikiflow"] | | | | | --- | --- | | | jq '[ .[] | . \* 2]' | | Input | [1, 2, 3] | | Output | [2, 4, 6] | ### Object Construction: `{}` Like JSON, `{}` is for constructing objects (aka dictionaries or hashes), as in: `{"a": 42, "b": 17}`. If the keys are "identifier-like", then the quotes can be left off, as in `{a:42, b:17}`. Keys generated by expressions need to be parenthesized, e.g., `{("a"+"b"):59}`. The value can be any expression (although you may need to wrap it in parentheses if it's a complicated one), which gets applied to the {} expression's input (remember, all filters have an input and an output). ``` {foo: .bar} ``` will produce the JSON object `{"foo": 42}` if given the JSON object `{"bar":42, "baz":43}` as its input. You can use this to select particular fields of an object: if the input is an object with "user", "title", "id", and "content" fields and you just want "user" and "title", you can write ``` {user: .user, title: .title} ``` Because that is so common, there's a shortcut syntax for it: `{user, title}`. If one of the expressions produces multiple results, multiple dictionaries will be produced. If the input's ``` {"user":"stedolan","titles":["JQ Primer", "More JQ"]} ``` then the expression ``` {user, title: .titles[]} ``` will produce two outputs: ``` {"user":"stedolan", "title": "JQ Primer"} {"user":"stedolan", "title": "More JQ"} ``` Putting parentheses around the key means it will be evaluated as an expression. With the same input as above, ``` {(.user): .titles} ``` produces ``` {"stedolan": ["JQ Primer", "More JQ"]} ``` #### Examples | | | | --- | --- | | | jq '{user, title: .titles[]}' | | Input | {"user":"stedolan","titles":["JQ Primer", "More JQ"]} | | Output | {"user":"stedolan", "title": "JQ Primer"} | | | {"user":"stedolan", "title": "More JQ"} | | | | | --- | --- | | | jq '{(.user): .titles}' | | Input | {"user":"stedolan","titles":["JQ Primer", "More JQ"]} | | Output | {"stedolan": ["JQ Primer", "More JQ"]} | ### Recursive Descent: `..` Recursively descends `.`, producing every value. This is the same as the zero-argument `recurse` builtin (see below). This is intended to resemble the XPath `//` operator. Note that `..a` does not work; use `..|.a` instead. In the example below we use `..|.a?` to find all the values of object keys "a" in any object found "below" `.`. This is particularly useful in conjunction with `path(EXP)` (also see below) and the `?` operator. #### Example | | | | --- | --- | | | jq '..|.a?' | | Input | [[{"a":1}]] | | Output | 1 | Builtin operators and functions ------------------------------- Some jq operators (for instance, `+`) do different things depending on the type of their arguments (arrays, numbers, etc.). However, jq never does implicit type conversions. If you try to add a string to an object you'll get an error message and no result. Please note that all numbers are converted to IEEE754 double precision floating point representation. Arithmetic and logical operators are working with these converted doubles. Results of all such operations are also limited to the double precision. The only exception to this behaviour of number is a snapshot of original number literal. When a number which originally was provided as a literal is never mutated until the end of the program then it is printed to the output in its original literal form. This also includes cases when the original literal would be truncated when converted to the IEEE754 double precision floating point number. ### Addition: `+` The operator `+` takes two filters, applies them both to the same input, and adds the results together. What "adding" means depends on the types involved: * **Numbers** are added by normal arithmetic. * **Arrays** are added by being concatenated into a larger array. * **Strings** are added by being joined into a larger string. * **Objects** are added by merging, that is, inserting all the key-value pairs from both objects into a single combined object. If both objects contain a value for the same key, the object on the right of the `+` wins. (For recursive merge use the `*` operator.) `null` can be added to any value, and returns the other value unchanged. #### Examples | | | | --- | --- | | | jq '.a + 1' | | Input | {"a": 7} | | Output | 8 | | | | | --- | --- | | | jq '.a + .b' | | Input | {"a": [1,2], "b": [3,4]} | | Output | [1,2,3,4] | | | | | --- | --- | | | jq '.a + null' | | Input | {"a": 1} | | Output | 1 | | | | | --- | --- | | | jq '.a + 1' | | Input | {} | | Output | 1 | | | | | --- | --- | | | jq '{a: 1} + {b: 2} + {c: 3} + {a: 42}' | | Input | null | | Output | {"a": 42, "b": 2, "c": 3} | ### Subtraction: `-` As well as normal arithmetic subtraction on numbers, the `-` operator can be used on arrays to remove all occurrences of the second array's elements from the first array. #### Examples | | | | --- | --- | | | jq '4 - .a' | | Input | {"a":3} | | Output | 1 | | | | | --- | --- | | | jq '. - ["xml", "yaml"]' | | Input | ["xml", "yaml", "json"] | | Output | ["json"] | ### Multiplication, division, modulo: `*`, `/`, and `%` These infix operators behave as expected when given two numbers. Division by zero raises an error. `x % y` computes x modulo y. Multiplying a string by a number produces the concatenation of that string that many times. `"x" * 0` produces **null**. Dividing a string by another splits the first using the second as separators. Multiplying two objects will merge them recursively: this works like addition but if both objects contain a value for the same key, and the values are objects, the two are merged with the same strategy. #### Examples | | | | --- | --- | | | jq '10 / . \* 3' | | Input | 5 | | Output | 6 | | | | | --- | --- | | | jq '. / ", "' | | Input | "a, b,c,d, e" | | Output | ["a","b,c,d","e"] | | | | | --- | --- | | | jq '{"k": {"a": 1, "b": 2}} \* {"k": {"a": 0,"c": 3}}' | | Input | null | | Output | {"k": {"a": 0, "b": 2, "c": 3}} | | | | | --- | --- | | | jq '.[] | (1 / .)?' | | Input | [1,0,-1] | | Output | 1 | | | -1 | ### `length` The builtin function `length` gets the length of various different types of value: * The length of a **string** is the number of Unicode codepoints it contains (which will be the same as its JSON-encoded length in bytes if it's pure ASCII). * The length of an **array** is the number of elements. * The length of an **object** is the number of key-value pairs. * The length of **null** is zero. #### Example | | | | --- | --- | | | jq '.[] | length' | | Input | [[1,2], "string", {"a":2}, null] | | Output | 2 | | | 6 | | | 1 | | | 0 | ### `utf8bytelength` The builtin function `utf8bytelength` outputs the number of bytes used to encode a string in UTF-8. #### Example | | | | --- | --- | | | jq 'utf8bytelength' | | Input | "\u03bc" | | Output | 2 | ### `keys`, `keys_unsorted` The builtin function `keys`, when given an object, returns its keys in an array. The keys are sorted "alphabetically", by unicode codepoint order. This is not an order that makes particular sense in any particular language, but you can count on it being the same for any two objects with the same set of keys, regardless of locale settings. When `keys` is given an array, it returns the valid indices for that array: the integers from 0 to length-1. The `keys_unsorted` function is just like `keys`, but if the input is an object then the keys will not be sorted, instead the keys will roughly be in insertion order. #### Examples | | | | --- | --- | | | jq 'keys' | | Input | {"abc": 1, "abcd": 2, "Foo": 3} | | Output | ["Foo", "abc", "abcd"] | | | | | --- | --- | | | jq 'keys' | | Input | [42,3,35] | | Output | [0,1,2] | ### `has(key)` The builtin function `has` returns whether the input object has the given key, or the input array has an element at the given index. `has($key)` has the same effect as checking whether `$key` is a member of the array returned by `keys`, although `has` will be faster. #### Examples | | | | --- | --- | | | jq 'map(has("foo"))' | | Input | [{"foo": 42}, {}] | | Output | [true, false] | | | | | --- | --- | | | jq 'map(has(2))' | | Input | [[0,1], ["a","b","c"]] | | Output | [false, true] | ### `in` The builtin function `in` returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inversed version of `has`. #### Examples | | | | --- | --- | | | jq '.[] | in({"foo": 42})' | | Input | ["foo", "bar"] | | Output | true | | | false | | | | | --- | --- | | | jq 'map(in([0,1]))' | | Input | [2, 0] | | Output | [false, true] | ### `map(x)`, `map_values(x)` For any filter `x`, `map(x)` will run that filter for each element of the input array, and return the outputs in a new array. `map(.+1)` will increment each element of an array of numbers. Similarly, `map_values(x)` will run that filter for each element, but it will return an object when an object is passed. `map(x)` is equivalent to `[.[] | x]`. In fact, this is how it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`. #### Examples | | | | --- | --- | | | jq 'map(.+1)' | | Input | [1,2,3] | | Output | [2,3,4] | | | | | --- | --- | | | jq 'map\_values(.+1)' | | Input | {"a": 1, "b": 2, "c": 3} | | Output | {"a": 2, "b": 3, "c": 4} | ### `path(path_expression)` Outputs array representations of the given path expression in `.`. The outputs are arrays of strings (object keys) and/or numbers (array indices). Path expressions are jq expressions like `.a`, but also `.[]`. There are two types of path expressions: ones that can match exactly, and ones that cannot. For example, `.a.b.c` is an exact match path expression, while `.a[].b` is not. `path(exact_path_expression)` will produce the array representation of the path expression even if it does not exist in `.`, if `.` is `null` or an array or an object. `path(pattern)` will produce array representations of the paths matching `pattern` if the paths exist in `.`. Note that the path expressions are not different from normal expressions. The expression `path(..|select(type=="boolean"))` outputs all the paths to boolean values in `.`, and only those paths. #### Examples | | | | --- | --- | | | jq 'path(.a[0].b)' | | Input | null | | Output | ["a",0,"b"] | | | | | --- | --- | | | jq '[path(..)]' | | Input | {"a":[{"b":1}]} | | Output | [[],["a"],["a",0],["a",0,"b"]] | ### `del(path_expression)` The builtin function `del` removes a key and its corresponding value from an object. #### Examples | | | | --- | --- | | | jq 'del(.foo)' | | Input | {"foo": 42, "bar": 9001, "baz": 42} | | Output | {"bar": 9001, "baz": 42} | | | | | --- | --- | | | jq 'del(.[1, 2])' | | Input | ["foo", "bar", "baz"] | | Output | ["foo"] | ### `getpath(PATHS)` The builtin function `getpath` outputs the values in `.` found at each path in `PATHS`. #### Examples | | | | --- | --- | | | jq 'getpath(["a","b"])' | | Input | null | | Output | null | | | | | --- | --- | | | jq '[getpath(["a","b"], ["a","c"])]' | | Input | {"a":{"b":0, "c":1}} | | Output | [0, 1] | ### `setpath(PATHS; VALUE)` The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`. #### Examples | | | | --- | --- | | | jq 'setpath(["a","b"]; 1)' | | Input | null | | Output | {"a": {"b": 1}} | | | | | --- | --- | | | jq 'setpath(["a","b"]; 1)' | | Input | {"a":{"b":0}} | | Output | {"a": {"b": 1}} | | | | | --- | --- | | | jq 'setpath([0,"a"]; 1)' | | Input | null | | Output | [{"a":1}] | ### `delpaths(PATHS)` The builtin function `delpaths` sets the `PATHS` in `.`. `PATHS` must be an array of paths, where each path is an array of strings and numbers. #### Example | | | | --- | --- | | | jq 'delpaths([["a","b"]])' | | Input | {"a":{"b":1},"x":{"y":2}} | | Output | {"a":{},"x":{"y":2}} | ### `to_entries`, `from_entries`, `with_entries` These functions convert between an object and an array of key-value pairs. If `to_entries` is passed an object, then for each `k: v` entry in the input, the output array includes `{"key": k, "value": v}`. `from_entries` does the opposite conversion, and `with_entries(foo)` is a shorthand for `to_entries | map(foo) | from_entries`, useful for doing some operation to all keys and values of an object. `from_entries` accepts key, Key, name, Name, value and Value as keys. #### Examples | | | | --- | --- | | | jq 'to\_entries' | | Input | {"a": 1, "b": 2} | | Output | [{"key":"a", "value":1}, {"key":"b", "value":2}] | | | | | --- | --- | | | jq 'from\_entries' | | Input | [{"key":"a", "value":1}, {"key":"b", "value":2}] | | Output | {"a": 1, "b": 2} | | | | | --- | --- | | | jq 'with\_entries(.key |= "KEY\_" + .)' | | Input | {"a": 1, "b": 2} | | Output | {"KEY\_a": 1, "KEY\_b": 2} | ### `select(boolean_expression)` The function `select(foo)` produces its input unchanged if `foo` returns true for that input, and produces no output otherwise. It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))` will give you `[2,3]`. #### Examples | | | | --- | --- | | | jq 'map(select(. >= 2))' | | Input | [1,5,3,0,7] | | Output | [5,3,7] | | | | | --- | --- | | | jq '.[] | select(.id == "second")' | | Input | [{"id": "first", "val": 1}, {"id": "second", "val": 2}] | | Output | {"id": "second", "val": 2} | ### `arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars` These built-ins select only inputs that are arrays, objects, iterables (arrays or objects), booleans, numbers, normal numbers, finite numbers, strings, null, non-null values, and non-iterables, respectively. #### Example | | | | --- | --- | | | jq '.[]|numbers' | | Input | [[],{},1,"foo",null,true,false] | | Output | 1 | ### `empty` `empty` returns no results. None at all. Not even `null`. It's useful on occasion. You'll know if you need it :) #### Examples | | | | --- | --- | | | jq '1, empty, 2' | | Input | null | | Output | 1 | | | 2 | | | | | --- | --- | | | jq '[1,2,empty,3]' | | Input | null | | Output | [1,2,3] | ### `error(message)` Produces an error, just like `.a` applied to values other than null and objects would, but with the given message as the error's value. Errors can be caught with try/catch; see below. ### `halt` Stops the jq program with no further outputs. jq will exit with exit status `0`. ### `halt_error`, `halt_error(exit_code)` Stops the jq program with no further outputs. The input will be printed on `stderr` as raw output (i.e., strings will not have double quotes) with no decoration, not even a newline. The given `exit_code` (defaulting to `5`) will be jq's exit status. For example, `"Error: somthing went wrong\n"|halt_error(1)`. ### `$__loc__` Produces an object with a "file" key and a "line" key, with the filename and line number where `$__loc__` occurs, as values. #### Example | | | | --- | --- | | | jq 'try error("\($\_\_loc\_\_)") catch .' | | Input | null | | Output | "{\"file\":\"<top-level>\",\"line\":1}" | ### `paths`, `paths(node_filter)`, `leaf_paths` `paths` outputs the paths to all the elements in its input (except it does not output the empty list, representing . itself). `paths(f)` outputs the paths to any values for which `f` is true. That is, `paths(numbers)` outputs the paths to all numeric values. `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is *deprecated* and will be removed in the next major release. #### Examples | | | | --- | --- | | | jq '[paths]' | | Input | [1,[[],{"a":2}]] | | Output | [[0],[1],[1,0],[1,1],[1,1,"a"]] | | | | | --- | --- | | | jq '[paths(scalars)]' | | Input | [1,[[],{"a":2}]] | | Output | [[0],[1,1,"a"]] | ### `add` The filter `add` takes as input an array, and produces as output the elements of the array added together. This might mean summed, concatenated or merged depending on the types of the elements of the input array - the rules are the same as those for the `+` operator (described above). If the input is an empty array, `add` returns `null`. #### Examples | | | | --- | --- | | | jq 'add' | | Input | ["a","b","c"] | | Output | "abc" | | | | | --- | --- | | | jq 'add' | | Input | [1, 2, 3] | | Output | 6 | | | | | --- | --- | | | jq 'add' | | Input | [] | | Output | null | ### `any`, `any(condition)`, `any(generator; condition)` The filter `any` takes as input an array of boolean values, and produces `true` as output if any of the elements of the array are `true`. If the input is an empty array, `any` returns `false`. The `any(condition)` form applies the given condition to the elements of the input array. The `any(generator; condition)` form applies the given condition to all the outputs of the given generator. #### Examples | | | | --- | --- | | | jq 'any' | | Input | [true, false] | | Output | true | | | | | --- | --- | | | jq 'any' | | Input | [false, false] | | Output | false | | | | | --- | --- | | | jq 'any' | | Input | [] | | Output | false | ### `all`, `all(condition)`, `all(generator; condition)` The filter `all` takes as input an array of boolean values, and produces `true` as output if all of the elements of the array are `true`. The `all(condition)` form applies the given condition to the elements of the input array. The `all(generator; condition)` form applies the given condition to all the outputs of the given generator. If the input is an empty array, `all` returns `true`. #### Examples | | | | --- | --- | | | jq 'all' | | Input | [true, false] | | Output | false | | | | | --- | --- | | | jq 'all' | | Input | [true, true] | | Output | true | | | | | --- | --- | | | jq 'all' | | Input | [] | | Output | true | ### `flatten`, `flatten(depth)` The filter `flatten` takes as input an array of nested arrays, and produces a flat array in which all arrays inside the original array have been recursively replaced by their values. You can pass an argument to it to specify how many levels of nesting to flatten. `flatten(2)` is like `flatten`, but going only up to two levels deep. #### Examples | | | | --- | --- | | | jq 'flatten' | | Input | [1, [2], [[3]]] | | Output | [1, 2, 3] | | | | | --- | --- | | | jq 'flatten(1)' | | Input | [1, [2], [[3]]] | | Output | [1, 2, [3]] | | | | | --- | --- | | | jq 'flatten' | | Input | [[]] | | Output | [] | | | | | --- | --- | | | jq 'flatten' | | Input | [{"foo": "bar"}, [{"foo": "baz"}]] | | Output | [{"foo": "bar"}, {"foo": "baz"}] | ### `range(upto)`, `range(from;upto)` `range(from;upto;by)` The `range` function produces a range of numbers. `range(4;10)` produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers are produced as separate outputs. Use `[range(4;10)]` to get a range as an array. The one argument form generates numbers from 0 to the given number, with an increment of 1. The two argument form generates numbers from `from` to `upto` with an increment of 1. The three argument form generates numbers `from` to `upto` with an increment of `by`. #### Examples | | | | --- | --- | | | jq 'range(2;4)' | | Input | null | | Output | 2 | | | 3 | | | | | --- | --- | | | jq '[range(2;4)]' | | Input | null | | Output | [2,3] | | | | | --- | --- | | | jq '[range(4)]' | | Input | null | | Output | [0,1,2,3] | | | | | --- | --- | | | jq '[range(0;10;3)]' | | Input | null | | Output | [0,3,6,9] | | | | | --- | --- | | | jq '[range(0;10;-1)]' | | Input | null | | Output | [] | | | | | --- | --- | | | jq '[range(0;-5;-1)]' | | Input | null | | Output | [0,-1,-2,-3,-4] | ### `floor` The `floor` function returns the floor of its numeric input. #### Example | | | | --- | --- | | | jq 'floor' | | Input | 3.14159 | | Output | 3 | ### `sqrt` The `sqrt` function returns the square root of its numeric input. #### Example | | | | --- | --- | | | jq 'sqrt' | | Input | 9 | | Output | 3 | ### `tonumber` The `tonumber` function parses its input as a number. It will convert correctly-formatted strings to their numeric equivalent, leave numbers alone, and give an error on all other input. #### Example | | | | --- | --- | | | jq '.[] | tonumber' | | Input | [1, "1"] | | Output | 1 | | | 1 | ### `tostring` The `tostring` function prints its input as a string. Strings are left unchanged, and all other values are JSON-encoded. #### Example | | | | --- | --- | | | jq '.[] | tostring' | | Input | [1, "1", [1]] | | Output | "1" | | | "1" | | | "[1]" | ### `type` The `type` function returns the type of its argument as a string, which is one of null, boolean, number, string, array or object. #### Example | | | | --- | --- | | | jq 'map(type)' | | Input | [0, false, [], {}, null, "hello"] | | Output | ["number", "boolean", "array", "object", "null", "string"] | ### `infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal` Some arithmetic operations can yield infinities and "not a number" (NaN) values. The `isinfinite` builtin returns `true` if its input is infinite. The `isnan` builtin returns `true` if its input is a NaN. The `infinite` builtin returns a positive infinite value. The `nan` builtin returns a NaN. The `isnormal` builtin returns true if its input is a normal number. Note that division by zero raises an error. Currently most arithmetic operations operating on infinities, NaNs, and sub-normals do not raise errors. #### Examples | | | | --- | --- | | | jq '.[] | (infinite \* .) < 0' | | Input | [-1, 1] | | Output | true | | | false | | | | | --- | --- | | | jq 'infinite, nan | type' | | Input | null | | Output | "number" | | | "number" | ### `sort, sort_by(path_expression)` The `sort` functions sorts its input, which must be an array. Values are sorted in the following order: * `null` * `false` * `true` * numbers * strings, in alphabetical order (by unicode codepoint value) * arrays, in lexical order * objects The ordering for objects is a little complex: first they're compared by comparing their sets of keys (as arrays in sorted order), and if their keys are equal then the values are compared key by key. `sort` may be used to sort by a particular field of an object, or by applying any jq filter. `sort_by(foo)` compares two elements by comparing the result of `foo` on each element. #### Examples | | | | --- | --- | | | jq 'sort' | | Input | [8,3,null,6] | | Output | [null,3,6,8] | | | | | --- | --- | | | jq 'sort\_by(.foo)' | | Input | [{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}] | | Output | [{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}] | ### `group_by(path_expression)` `group_by(.foo)` takes as input an array, groups the elements having the same `.foo` field into separate arrays, and produces all of these arrays as elements of a larger array, sorted by the value of the `.foo` field. Any jq expression, not just a field access, may be used in place of `.foo`. The sorting order is the same as described in the `sort` function above. #### Example | | | | --- | --- | | | jq 'group\_by(.foo)' | | Input | [{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}] | | Output | [[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]] | ### `min`, `max`, `min_by(path_exp)`, `max_by(path_exp)` Find the minimum or maximum element of the input array. The `min_by(path_exp)` and `max_by(path_exp)` functions allow you to specify a particular field or property to examine, e.g. `min_by(.foo)` finds the object with the smallest `foo` field. #### Examples | | | | --- | --- | | | jq 'min' | | Input | [5,4,2,7] | | Output | 2 | | | | | --- | --- | | | jq 'max\_by(.foo)' | | Input | [{"foo":1, "bar":14}, {"foo":2, "bar":3}] | | Output | {"foo":2, "bar":3} | ### `unique`, `unique_by(path_exp)` The `unique` function takes as input an array and produces an array of the same elements, in sorted order, with duplicates removed. The `unique_by(path_exp)` function will keep only one element for each value obtained by applying the argument. Think of it as making an array by taking one element out of every group produced by `group`. #### Examples | | | | --- | --- | | | jq 'unique' | | Input | [1,2,5,3,5,3,1,3] | | Output | [1,2,3,5] | | | | | --- | --- | | | jq 'unique\_by(.foo)' | | Input | [{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}] | | Output | [{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}] | | | | | --- | --- | | | jq 'unique\_by(length)' | | Input | ["chunky", "bacon", "kitten", "cicada", "asparagus"] | | Output | ["bacon", "chunky", "asparagus"] | ### `reverse` This function reverses an array. #### Example | | | | --- | --- | | | jq 'reverse' | | Input | [1,2,3,4] | | Output | [4,3,2,1] | ### `contains(element)` The filter `contains(b)` will produce true if b is completely contained within the input. String B is contained in a string A if B is a substring of A. An array B is contained in an array A if all elements in B are contained in any element in A. An object B is contained in object A if all of the values in B are contained in the value in A with the same key. All other types are assumed to be contained in each other if they are equal. #### Examples | | | | --- | --- | | | jq 'contains("bar")' | | Input | "foobar" | | Output | true | | | | | --- | --- | | | jq 'contains(["baz", "bar"])' | | Input | ["foobar", "foobaz", "blarp"] | | Output | true | | | | | --- | --- | | | jq 'contains(["bazzzzz", "bar"])' | | Input | ["foobar", "foobaz", "blarp"] | | Output | false | | | | | --- | --- | | | jq 'contains({foo: 12, bar: [{barp: 12}]})' | | Input | {"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]} | | Output | true | | | | | --- | --- | | | jq 'contains({foo: 12, bar: [{barp: 15}]})' | | Input | {"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]} | | Output | false | ### `indices(s)` Outputs an array containing the indices in `.` where `s` occurs. The input may be an array, in which case if `s` is an array then the indices output will be those where all elements in `.` match those of `s`. #### Examples | | | | --- | --- | | | jq 'indices(", ")' | | Input | "a,b, cd, efg, hijk" | | Output | [3,7,12] | | | | | --- | --- | | | jq 'indices(1)' | | Input | [0,1,2,1,3,1,4] | | Output | [1,3,5] | | | | | --- | --- | | | jq 'indices([1,2])' | | Input | [0,1,2,3,1,4,2,5,1,2,6,7] | | Output | [1,8] | ### `index(s)`, `rindex(s)` Outputs the index of the first (`index`) or last (`rindex`) occurrence of `s` in the input. #### Examples | | | | --- | --- | | | jq 'index(", ")' | | Input | "a,b, cd, efg, hijk" | | Output | 3 | | | | | --- | --- | | | jq 'rindex(", ")' | | Input | "a,b, cd, efg, hijk" | | Output | 12 | ### `inside` The filter `inside(b)` will produce true if the input is completely contained within b. It is, essentially, an inversed version of `contains`. #### Examples | | | | --- | --- | | | jq 'inside("foobar")' | | Input | "bar" | | Output | true | | | | | --- | --- | | | jq 'inside(["foobar", "foobaz", "blarp"])' | | Input | ["baz", "bar"] | | Output | true | | | | | --- | --- | | | jq 'inside(["foobar", "foobaz", "blarp"])' | | Input | ["bazzzzz", "bar"] | | Output | false | | | | | --- | --- | | | jq 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})' | | Input | {"foo": 12, "bar": [{"barp": 12}]} | | Output | true | | | | | --- | --- | | | jq 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})' | | Input | {"foo": 12, "bar": [{"barp": 15}]} | | Output | false | ### `startswith(str)` Outputs `true` if . starts with the given string argument. #### Example | | | | --- | --- | | | jq '[.[]|startswith("foo")]' | | Input | ["fo", "foo", "barfoo", "foobar", "barfoob"] | | Output | [false, true, false, true, false] | ### `endswith(str)` Outputs `true` if . ends with the given string argument. #### Example | | | | --- | --- | | | jq '[.[]|endswith("foo")]' | | Input | ["foobar", "barfoo"] | | Output | [false, true] | ### `combinations`, `combinations(n)` Outputs all combinations of the elements of the arrays in the input array. If given an argument `n`, it outputs all combinations of `n` repetitions of the input array. #### Examples | | | | --- | --- | | | jq 'combinations' | | Input | [[1,2], [3, 4]] | | Output | [1, 3] | | | [1, 4] | | | [2, 3] | | | [2, 4] | | | | | --- | --- | | | jq 'combinations(2)' | | Input | [0, 1] | | Output | [0, 0] | | | [0, 1] | | | [1, 0] | | | [1, 1] | ### `ltrimstr(str)` Outputs its input with the given prefix string removed, if it starts with it. #### Example | | | | --- | --- | | | jq '[.[]|ltrimstr("foo")]' | | Input | ["fo", "foo", "barfoo", "foobar", "afoo"] | | Output | ["fo","","barfoo","bar","afoo"] | ### `rtrimstr(str)` Outputs its input with the given suffix string removed, if it ends with it. #### Example | | | | --- | --- | | | jq '[.[]|rtrimstr("foo")]' | | Input | ["fo", "foo", "barfoo", "foobar", "foob"] | | Output | ["fo","","bar","foobar","foob"] | ### `explode` Converts an input string into an array of the string's codepoint numbers. #### Example | | | | --- | --- | | | jq 'explode' | | Input | "foobar" | | Output | [102,111,111,98,97,114] | ### `implode` The inverse of explode. #### Example | | | | --- | --- | | | jq 'implode' | | Input | [65, 66, 67] | | Output | "ABC" | ### `split(str)` Splits an input string on the separator argument. #### Example | | | | --- | --- | | | jq 'split(", ")' | | Input | "a, b,c,d, e, " | | Output | ["a","b,c,d","e",""] | ### `join(str)` Joins the array of elements given as input, using the argument as separator. It is the inverse of `split`: that is, running `split("foo") | join("foo")` over any input string returns said input string. Numbers and booleans in the input are converted to strings. Null values are treated as empty strings. Arrays and objects in the input are not supported. #### Examples | | | | --- | --- | | | jq 'join(", ")' | | Input | ["a","b,c,d","e"] | | Output | "a, b,c,d, e" | | | | | --- | --- | | | jq 'join(" ")' | | Input | ["a",1,2.3,true,null,false] | | Output | "a 1 2.3 true false" | ### `ascii_downcase`, `ascii_upcase` Emit a copy of the input string with its alphabetic characters (a-z and A-Z) converted to the specified case. ### `while(cond; update)` The `while(cond; update)` function allows you to repeatedly apply an update to `.` until `cond` is false. Note that `while(cond; update)` is internally defined as a recursive jq function. Recursive calls within `while` will not consume additional memory if `update` produces at most one output for each input. See advanced topics below. #### Example | | | | --- | --- | | | jq '[while(.<100; .\*2)]' | | Input | 1 | | Output | [1,2,4,8,16,32,64] | ### `until(cond; next)` The `until(cond; next)` function allows you to repeatedly apply the expression `next`, initially to `.` then to its own output, until `cond` is true. For example, this can be used to implement a factorial function (see below). Note that `until(cond; next)` is internally defined as a recursive jq function. Recursive calls within `until()` will not consume additional memory if `next` produces at most one output for each input. See advanced topics below. #### Example | | | | --- | --- | | | jq '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] \* .[0]])|.[1]' | | Input | 4 | | Output | 24 | ### `recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down` The `recurse(f)` function allows you to search through a recursive structure, and extract interesting data from all levels. Suppose your input represents a filesystem: ``` {"name": "/", "children": [ {"name": "/bin", "children": [ {"name": "/bin/ls", "children": []}, {"name": "/bin/sh", "children": []}]}, {"name": "/home", "children": [ {"name": "/home/stephen", "children": [ {"name": "/home/stephen/jq", "children": []}]}]}]} ``` Now suppose you want to extract all of the filenames present. You need to retrieve `.name`, `.children[].name`, `.children[].children[].name`, and so on. You can do this with: ``` recurse(.children[]) | .name ``` When called without an argument, `recurse` is equivalent to `recurse(.[]?)`. `recurse(f)` is identical to `recurse(f; . != null)` and can be used without concerns about recursion depth. `recurse(f; condition)` is a generator which begins by emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long as the computed value satisfies the condition. For example, to generate all the integers, at least in principle, one could write `recurse(.+1; true)`. For legacy reasons, `recurse_down` exists as an alias to calling `recurse` without arguments. This alias is considered *deprecated* and will be removed in the next major release. The recursive calls in `recurse` will not consume additional memory whenever `f` produces at most a single output for each input. #### Examples | | | | --- | --- | | | jq 'recurse(.foo[])' | | Input | {"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]} | | Output | {"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]} | | | {"foo":[]} | | | {"foo":[{"foo":[]}]} | | | {"foo":[]} | | | | | --- | --- | | | jq 'recurse' | | Input | {"a":0,"b":[1]} | | Output | {"a":0,"b":[1]} | | | 0 | | | [1] | | | 1 | | | | | --- | --- | | | jq 'recurse(. \* .; . < 20)' | | Input | 2 | | Output | 2 | | | 4 | | | 16 | ### `walk(f)` The `walk(f)` function applies f recursively to every component of the input entity. When an array is encountered, f is first applied to its elements and then to the array itself; when an object is encountered, f is first applied to all the values and then to the object. In practice, f will usually test the type of its input, as illustrated in the following examples. The first example highlights the usefulness of processing the elements of an array of arrays before processing the array itself. The second example shows how all the keys of all the objects within the input can be considered for alteration. #### Examples | | | | --- | --- | | | jq 'walk(if type == "array" then sort else . end)' | | Input | [[4, 1, 7], [8, 5, 2], [3, 6, 9]] | | Output | [[1,4,7],[2,5,8],[3,6,9]] | | | | | --- | --- | | | jq 'walk( if type == "object" then with\_entries( .key |= sub( "^\_+"; "") ) else . end )' | | Input | [ { "\_a": { "\_\_b": 2 } } ] | | Output | [{"a":{"b":2}}] | ### `$ENV`, `env` `$ENV` is an object representing the environment variables as set when the jq program started. `env` outputs an object representing jq's current environment. At the moment there is no builtin for setting environment variables. #### Examples | | | | --- | --- | | | jq '$ENV.PAGER' | | Input | null | | Output | "less" | | | | | --- | --- | | | jq 'env.PAGER' | | Input | null | | Output | "less" | ### `transpose` Transpose a possibly jagged matrix (an array of arrays). Rows are padded with nulls so the result is always rectangular. #### Example | | | | --- | --- | | | jq 'transpose' | | Input | [[1], [2,3]] | | Output | [[1,2],[null,3]] | ### `bsearch(x)` bsearch(x) conducts a binary search for x in the input array. If the input is sorted and contains x, then bsearch(x) will return its index in the array; otherwise, if the array is sorted, it will return (-1 - ix) where ix is an insertion point such that the array would still be sorted after the insertion of x at ix. If the array is not sorted, bsearch(x) will return an integer that is probably of no interest. #### Examples | | | | --- | --- | | | jq 'bsearch(0)' | | Input | [0,1] | | Output | 0 | | | | | --- | --- | | | jq 'bsearch(0)' | | Input | [1,2,3] | | Output | -1 | | | | | --- | --- | | | jq 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end' | | Input | [1,2,3] | | Output | [1,2,3,4] | ### String interpolation - `\(foo)` Inside a string, you can put an expression inside parens after a backslash. Whatever the expression returns will be interpolated into the string. #### Example | | | | --- | --- | | | jq '"The input was \(.), which is one less than \(.+1)"' | | Input | 42 | | Output | "The input was 42, which is one less than 43" | ### Convert to/from JSON The `tojson` and `fromjson` builtins dump values as JSON texts or parse JSON texts into values, respectively. The tojson builtin differs from tostring in that tostring returns strings unmodified, while tojson encodes strings as JSON strings. #### Examples | | | | --- | --- | | | jq '[.[]|tostring]' | | Input | [1, "foo", ["foo"]] | | Output | ["1","foo","[\"foo\"]"] | | | | | --- | --- | | | jq '[.[]|tojson]' | | Input | [1, "foo", ["foo"]] | | Output | ["1","\"foo\"","[\"foo\"]"] | | | | | --- | --- | | | jq '[.[]|tojson|fromjson]' | | Input | [1, "foo", ["foo"]] | | Output | [1,"foo",["foo"]] | ### Format strings and escaping The `@foo` syntax is used to format and escape strings, which is useful for building URLs, documents in a language like HTML or XML, and so forth. `@foo` can be used as a filter on its own, the possible escapings are: * `@text`: Calls `tostring`, see that function for details. * `@json`: Serializes the input as JSON. * `@html`: Applies HTML/XML escaping, by mapping the characters `<>&'"` to their entity equivalents `&lt;`, `&gt;`, `&amp;`, `&apos;`, `&quot;`. * `@uri`: Applies percent-encoding, by mapping all reserved URI characters to a `%XX` sequence. * `@csv`: The input must be an array, and it is rendered as CSV with double quotes for strings, and quotes escaped by repetition. * `@tsv`: The input must be an array, and it is rendered as TSV (tab-separated values). Each input array will be printed as a single line. Fields are separated by a single tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`), carriage-return (ascii `0x0d`), tab (ascii `0x09`) and backslash (ascii `0x5c`) will be output as escape sequences `\n`, `\r`, `\t`, `\\` respectively. * `@sh`: The input is escaped suitable for use in a command-line for a POSIX shell. If the input is an array, the output will be a series of space-separated strings. * `@base64`: The input is converted to base64 as specified by RFC 4648. * `@base64d`: The inverse of `@base64`, input is decoded as specified by RFC 4648. Note\: If the decoded string is not UTF-8, the results are undefined. This syntax can be combined with string interpolation in a useful way. You can follow a `@foo` token with a string literal. The contents of the string literal will *not* be escaped. However, all interpolations made inside that string literal will be escaped. For instance, ``` @uri "https://www.google.com/search?q=\(.search)" ``` will produce the following output for the input `{"search":"what is jq?"}`: ``` "https://www.google.com/search?q=what%20is%20jq%3F" ``` Note that the slashes, question mark, etc. in the URL are not escaped, as they were part of the string literal. #### Examples | | | | --- | --- | | | jq '@html' | | Input | "This works if x < y" | | Output | "This works if x &lt; y" | | | | | --- | --- | | | jq '@sh "echo \(.)"' | | Input | "O'Hara's Ale" | | Output | "echo 'O'\\''Hara'\\''s Ale'" | | | | | --- | --- | | | jq '@base64' | | Input | "This is a message" | | Output | "VGhpcyBpcyBhIG1lc3NhZ2U=" | | | | | --- | --- | | | jq '@base64d' | | Input | "VGhpcyBpcyBhIG1lc3NhZ2U=" | | Output | "This is a message" | ### Dates jq provides some basic date handling functionality, with some high-level and low-level builtins. In all cases these builtins deal exclusively with time in UTC. The `fromdateiso8601` builtin parses datetimes in the ISO 8601 format to a number of seconds since the Unix epoch (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the inverse. The `fromdate` builtin parses datetime strings. Currently `fromdate` only supports ISO 8601 datetime strings, but in the future it will attempt to parse datetime strings in more formats. The `todate` builtin is an alias for `todateiso8601`. The `now` builtin outputs the current time, in seconds since the Unix epoch. Low-level jq interfaces to the C-library time functions are also provided: `strptime`, `strftime`, `strflocaltime`, `mktime`, `gmtime`, and `localtime`. Refer to your host operating system's documentation for the format strings used by `strptime` and `strftime`. Note: these are not necessarily stable interfaces in jq, particularly as to their localization functionality. The `gmtime` builtin consumes a number of seconds since the Unix epoch and outputs a "broken down time" representation of Greenwhich Meridian time as an array of numbers representing (in this order): the year, the month (zero-based), the day of the month (one-based), the hour of the day, the minute of the hour, the second of the minute, the day of the week, and the day of the year -- all one-based unless otherwise stated. The day of the week number may be wrong on some systems for dates before March 1st 1900, or after December 31 2099. The `localtime` builtin works like the `gmtime` builtin, but using the local timezone setting. The `mktime` builtin consumes "broken down time" representations of time output by `gmtime` and `strptime`. The `strptime(fmt)` builtin parses input strings matching the `fmt` argument. The output is in the "broken down time" representation consumed by `gmtime` and output by `mktime`. The `strftime(fmt)` builtin formats a time (GMT) with the given format. The `strflocaltime` does the same, but using the local timezone setting. The format strings for `strptime` and `strftime` are described in typical C library documentation. The format string for ISO 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`. jq may not support some or all of this date functionality on some systems. In particular, the `%u` and `%j` specifiers for `strptime(fmt)` are not supported on macOS. #### Examples | | | | --- | --- | | | jq 'fromdate' | | Input | "2015-03-05T23:51:47Z" | | Output | 1425599507 | | | | | --- | --- | | | jq 'strptime("%Y-%m-%dT%H:%M:%SZ")' | | Input | "2015-03-05T23:51:47Z" | | Output | [2015,2,5,23,51,47,4,63] | | | | | --- | --- | | | jq 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime' | | Input | "2015-03-05T23:51:47Z" | | Output | 1425599507 | ### SQL-Style Operators jq provides a few SQL-style operators. * INDEX(stream; index\_expression): This builtin produces an object whose keys are computed by the given index expression applied to each value from the given stream. * JOIN($idx; stream; idx\_expr; join\_expr): This builtin joins the values from the given stream to the given index. The index's keys are computed by applying the given index expression to each value from the given stream. An array of the value in the stream and the corresponding value from the index is fed to the given join expression to produce each result. * JOIN($idx; stream; idx\_expr): Same as `JOIN($idx; stream; idx_expr; .)`. * JOIN($idx; idx\_expr): This builtin joins the input `.` to the given index, applying the given index expression to `.` to compute the index key. The join operation is as described above. * IN(s): This builtin outputs `true` if `.` appears in the given stream, otherwise it outputs `false`. * IN(source; s): This builtin outputs `true` if any value in the source stream appears in the second stream, otherwise it outputs `false`. ### `builtins` Returns a list of all builtin functions in the format `name/arity`. Since functions with the same name but different arities are considered separate functions, `all/0`, `all/1`, and `all/2` would all be present in the list. Conditionals and Comparisons ---------------------------- ### `==`, `!=` The expression 'a == b' will produce 'true' if the result of a and b are equal (that is, if they represent equivalent JSON documents) and 'false' otherwise. In particular, strings are never considered equal to numbers. If you're coming from Javascript, jq's == is like Javascript's === - considering values equal only when they have the same type as well as the same value. != is "not equal", and 'a != b' returns the opposite value of 'a == b' #### Example | | | | --- | --- | | | jq '.[] == 1' | | Input | [1, 1.0, "1", "banana"] | | Output | true | | | true | | | false | | | false | ### if-then-else `if A then B else C end` will act the same as `B` if `A` produces a value other than false or null, but act the same as `C` otherwise. Checking for false or null is a simpler notion of "truthiness" than is found in Javascript or Python, but it means that you'll sometimes have to be more explicit about the condition you want: you can't test whether, e.g. a string is empty using `if .name then A else B end`, you'll need something more like `if (.name | length) > 0 then A else B end` instead. If the condition `A` produces multiple results, then `B` is evaluated once for each result that is not false or null, and `C` is evaluated once for each false or null. More cases can be added to an if using `elif A then B` syntax. #### Example | | | | --- | --- | | | jq 'if . == 0 then "zero" elif . == 1 then "one" else "many" end' | | Input | 2 | | Output | "many" | ### `>, >=, <=, <` The comparison operators `>`, `>=`, `<=`, `<` return whether their left argument is greater than, greater than or equal to, less than or equal to or less than their right argument (respectively). The ordering is the same as that described for `sort`, above. #### Example | | | | --- | --- | | | jq '. < 5' | | Input | 2 | | Output | true | ### and/or/not jq supports the normal Boolean operators and/or/not. They have the same standard of truth as if expressions - false and null are considered "false values", and anything else is a "true value". If an operand of one of these operators produces multiple results, the operator itself will produce a result for each input. `not` is in fact a builtin function rather than an operator, so it is called as a filter to which things can be piped rather than with special syntax, as in `.foo and .bar | not`. These three only produce the values "true" and "false", and so are only useful for genuine Boolean operations, rather than the common Perl/Python/Ruby idiom of "value\_that\_may\_be\_null or default". If you want to use this form of "or", picking between two values rather than evaluating a condition, see the "//" operator below. #### Examples | | | | --- | --- | | | jq '42 and "a string"' | | Input | null | | Output | true | | | | | --- | --- | | | jq '(true, false) or false' | | Input | null | | Output | true | | | false | | | | | --- | --- | | | jq '(true, true) and (true, false)' | | Input | null | | Output | true | | | false | | | true | | | false | | | | | --- | --- | | | jq '[true, false | not]' | | Input | null | | Output | [false, true] | ### Alternative operator: `//` A filter of the form `a // b` produces the same results as `a`, if `a` produces results other than `false` and `null`. Otherwise, `a // b` produces the same results as `b`. This is useful for providing defaults: `.foo // 1` will evaluate to `1` if there's no `.foo` element in the input. It's similar to how `or` is sometimes used in Python (jq's `or` operator is reserved for strictly Boolean operations). #### Examples | | | | --- | --- | | | jq '.foo // 42' | | Input | {"foo": 19} | | Output | 19 | | | | | --- | --- | | | jq '.foo // 42' | | Input | {} | | Output | 42 | ### try-catch Errors can be caught by using `try EXP catch EXP`. The first expression is executed, and if it fails then the second is executed with the error message. The output of the handler, if any, is output as if it had been the output of the expression to try. The `try EXP` form uses `empty` as the exception handler. #### Examples | | | | --- | --- | | | jq 'try .a catch ". is not an object"' | | Input | true | | Output | ". is not an object" | | | | | --- | --- | | | jq '[.[]|try .a]' | | Input | [{}, true, {"a":1}] | | Output | [null, 1] | | | | | --- | --- | | | jq 'try error("some exception") catch .' | | Input | true | | Output | "some exception" | ### Breaking out of control structures A convenient use of try/catch is to break out of control structures like `reduce`, `foreach`, `while`, and so on. For example: ``` # Repeat an expression until it raises "break" as an # error, then stop repeating without re-raising the error. # But if the error caught is not "break" then re-raise it. try repeat(exp) catch .=="break" then empty else error; ``` jq has a syntax for named lexical labels to "break" or "go (back) to": ``` label $out | ... break $out ... ``` The `break $label_name` expression will cause the program to to act as though the nearest (to the left) `label $label_name` produced `empty`. The relationship between the `break` and corresponding `label` is lexical: the label has to be "visible" from the break. To break out of a `reduce`, for example: ``` label $out | reduce .[] as $item (null; if .==false then break $out else ... end) ``` The following jq program produces a syntax error: ``` break $out ``` because no label `$out` is visible. ### Error Suppression / Optional Operator: `?` The `?` operator, used as `EXP?`, is shorthand for `try EXP`. #### Example | | | | --- | --- | | | jq '[.[]|(.a)?]' | | Input | [{}, true, {"a":1}] | | Output | [null, 1] | Regular expressions (PCRE) -------------------------- jq uses the Oniguruma regular expression library, as do php, ruby, TextMate, Sublime Text, etc, so the description here will focus on jq specifics. The jq regex filters are defined so that they can be used using one of these patterns: ``` STRING | FILTER( REGEX ) STRING | FILTER( REGEX; FLAGS ) STRING | FILTER( [REGEX] ) STRING | FILTER( [REGEX, FLAGS] ) ``` where: *STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;* REGEX, after string interpolation, should be a valid PCRE regex; \* FILTER is one of `test`, `match`, or `capture`, as described below. FLAGS is a string consisting of one of more of the supported flags: * `g` - Global search (find all matches, not just the first) * `i` - Case insensitive search * `m` - Multi line mode ('.' will match newlines) * `n` - Ignore empty matches * `p` - Both s and m modes are enabled * `s` - Single line mode ('^' -> '\A', '$' -> '\Z') * `l` - Find longest possible matches * `x` - Extended regex format (ignore whitespace and comments) To match whitespace in an x pattern use an escape such as \s, e.g. * test( "a\sb", "x" ). Note that certain flags may also be specified within REGEX, e.g. * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )' evaluates to: true, true, false, false. ### `test(val)`, `test(regex; flags)` Like `match`, but does not return match objects, only `true` or `false` for whether or not the regex matches the input. #### Examples | | | | --- | --- | | | jq 'test("foo")' | | Input | "foo" | | Output | true | | | | | --- | --- | | | jq '.[] | test("a b c # spaces are ignored"; "ix")' | | Input | ["xabcd", "ABC"] | | Output | true | | | true | ### `match(val)`, `match(regex; flags)` **match** outputs an object for each match it finds. Matches have the following fields: * `offset` - offset in UTF-8 codepoints from the beginning of the input * `length` - length in UTF-8 codepoints of the match * `string` - the string that it matched * `captures` - an array of objects representing capturing groups. Capturing group objects have the following fields: * `offset` - offset in UTF-8 codepoints from the beginning of the input * `length` - length in UTF-8 codepoints of this capturing group * `string` - the string that was captured * `name` - the name of the capturing group (or `null` if it was unnamed) Capturing groups that did not match anything return an offset of -1 #### Examples | | | | --- | --- | | | jq 'match("(abc)+"; "g")' | | Input | "abc abc" | | Output | {"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]} | | | {"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]} | | | | | --- | --- | | | jq 'match("foo")' | | Input | "foo bar foo" | | Output | {"offset": 0, "length": 3, "string": "foo", "captures": []} | | | | | --- | --- | | | jq 'match(["foo", "ig"])' | | Input | "foo bar FOO" | | Output | {"offset": 0, "length": 3, "string": "foo", "captures": []} | | | {"offset": 8, "length": 3, "string": "FOO", "captures": []} | | | | | --- | --- | | | jq 'match("foo (?<bar123>bar)? foo"; "ig")' | | Input | "foo bar foo foo foo" | | Output | {"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]} | | | {"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]} | | | | | --- | --- | | | jq '[ match("."; "g")] | length' | | Input | "abc" | | Output | 3 | ### `capture(val)`, `capture(regex; flags)` Collects the named captures in a JSON object, with the name of each capture as the key, and the matched string as the corresponding value. #### Example | | | | --- | --- | | | jq 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")' | | Input | "xyzzy-14" | | Output | { "a": "xyzzy", "n": "14" } | ### `scan(regex)`, `scan(regex; flags)` Emit a stream of the non-overlapping substrings of the input that match the regex in accordance with the flags, if any have been specified. If there is no match, the stream is empty. To capture all the matches for each input string, use the idiom `[ expr ]`, e.g. `[ scan(regex) ]`. ### `split(regex; flags)` For backwards compatibility, `split` splits on a string, not a regex. ### `splits(regex)`, `splits(regex; flags)` These provide the same results as their `split` counterparts, but as a stream instead of an array. ### `sub(regex; tostring)` `sub(regex; string; flags)` Emit the string obtained by replacing the first match of regex in the input string with `tostring`, after interpolation. `tostring` should be a jq string, and may contain references to named captures. The named captures are, in effect, presented as a JSON object (as constructed by `capture`) to `tostring`, so a reference to a captured variable named "x" would take the form: "(.x)". ### `gsub(regex; string)`, `gsub(regex; string; flags)` `gsub` is like `sub` but all the non-overlapping occurrences of the regex are replaced by the string, after interpolation. Advanced features ----------------- Variables are an absolute necessity in most programming languages, but they're relegated to an "advanced feature" in jq. In most languages, variables are the only means of passing around data. If you calculate a value, and you want to use it more than once, you'll need to store it in a variable. To pass a value to another part of the program, you'll need that part of the program to define a variable (as a function parameter, object member, or whatever) in which to place the data. It is also possible to define functions in jq, although this is is a feature whose biggest use is defining jq's standard library (many jq functions such as `map` and `find` are in fact written in jq). jq has reduction operators, which are very powerful but a bit tricky. Again, these are mostly used internally, to define some useful bits of jq's standard library. It may not be obvious at first, but jq is all about generators (yes, as often found in other languages). Some utilities are provided to help deal with generators. Some minimal I/O support (besides reading JSON from standard input, and writing JSON to standard output) is available. Finally, there is a module/library system. ### Variable / Symbolic Binding Operator: `... as $identifier | ...` In jq, all filters have an input and an output, so manual plumbing is not necessary to pass a value from one part of a program to the next. Many expressions, for instance `a + b`, pass their input to two distinct subexpressions (here `a` and `b` are both passed the same input), so variables aren't usually necessary in order to use a value twice. For instance, calculating the average value of an array of numbers requires a few variables in most languages - at least one to hold the array, perhaps one for each element or for a loop counter. In jq, it's simply `add / length` - the `add` expression is given the array and produces its sum, and the `length` expression is given the array and produces its length. So, there's generally a cleaner way to solve most problems in jq than defining variables. Still, sometimes they do make things easier, so jq lets you define variables using `expression as $variable`. All variable names start with `$`. Here's a slightly uglier version of the array-averaging example: ``` length as $array_length | add / $array_length ``` We'll need a more complicated problem to find a situation where using variables actually makes our lives easier. Suppose we have an array of blog posts, with "author" and "title" fields, and another object which is used to map author usernames to real names. Our input looks like: ``` {"posts": [{"title": "Frist psot", "author": "anon"}, {"title": "A well-written article", "author": "person1"}], "realnames": {"anon": "Anonymous Coward", "person1": "Person McPherson"}} ``` We want to produce the posts with the author field containing a real name, as in: ``` {"title": "Frist psot", "author": "Anonymous Coward"} {"title": "A well-written article", "author": "Person McPherson"} ``` We use a variable, $names, to store the realnames object, so that we can refer to it later when looking up author usernames: ``` .realnames as $names | .posts[] | {title, author: $names[.author]} ``` The expression `exp as $x | ...` means: for each value of expression `exp`, run the rest of the pipeline with the entire original input, and with `$x` set to that value. Thus `as` functions as something of a foreach loop. Just as `{foo}` is a handy way of writing `{foo: .foo}`, so `{$foo}` is a handy way of writing `{foo:$foo}`. Multiple variables may be declared using a single `as` expression by providing a pattern that matches the structure of the input (this is known as "destructuring"): ``` . as {realnames: $names, posts: [$first, $second]} | ... ``` The variable declarations in array patterns (e.g., `. as [$first, $second]`) bind to the elements of the array in from the element at index zero on up, in order. When there is no value at the index for an array pattern element, `null` is bound to that variable. Variables are scoped over the rest of the expression that defines them, so ``` .realnames as $names | (.posts[] | {title, author: $names[.author]}) ``` will work, but ``` (.realnames as $names | .posts[]) | {title, author: $names[.author]} ``` won't. For programming language theorists, it's more accurate to say that jq variables are lexically-scoped bindings. In particular there's no way to change the value of a binding; one can only setup a new binding with the same name, but which will not be visible where the old one was. #### Examples | | | | --- | --- | | | jq '.bar as $x | .foo | . + $x' | | Input | {"foo":10, "bar":200} | | Output | 210 | | | | | --- | --- | | | jq '. as $i|[(.\*2|. as $i| $i), $i]' | | Input | 5 | | Output | [10,5] | | | | | --- | --- | | | jq '. as [$a, $b, {c: $c}] | $a + $b + $c' | | Input | [2, 3, {"c": 4, "d": 5}] | | Output | 9 | | | | | --- | --- | | | jq '.[] as [$a, $b] | {a: $a, b: $b}' | | Input | [[0], [0, 1], [2, 1, 0]] | | Output | {"a":0,"b":null} | | | {"a":0,"b":1} | | | {"a":2,"b":1} | ### Destructuring Alternative Operator: `?//` The destructuring alternative operator provides a concise mechanism for destructuring an input that can take one of several forms. Suppose we have an API that returns a list of resources and events associated with them, and we want to get the user\_id and timestamp of the first event for each resource. The API (having been clumsily converted from XML) will only wrap the events in an array if the resource has multiple events: ``` {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}}, {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]} ``` We can use the destructuring alternative operator to handle this structural change simply: ``` .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts} ``` Or, if we aren't sure if the input is an array of values or an object: ``` .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ... ``` Each alternative need not define all of the same variables, but all named variables will be available to the subsequent expression. Variables not matched in the alternative that succeeded will be `null`: ``` .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts} ``` Additionally, if the subsequent expression returns an error, the alternative operator will attempt to try the next binding. Errors that occur during the final alternative are passed through. ``` [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end ``` #### Examples | | | | --- | --- | | | jq '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}' | | Input | [{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}] | | Output | {"a":1,"b":2,"d":3,"e":4} | | | {"a":1,"b":2,"d":3,"e":4} | | | | | --- | --- | | | jq '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}' | | Input | [{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}] | | Output | {"a":1,"b":2,"d":3,"e":null} | | | {"a":1,"b":2,"d":null,"e":4} | | | | | --- | --- | | | jq '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end' | | Input | [[3]] | | Output | {"a":null,"b":3} | ### Defining Functions You can give a filter a name using "def" syntax: ``` def increment: . + 1; ``` From then on, `increment` is usable as a filter just like a builtin function (in fact, this is how many of the builtins are defined). A function may take arguments: ``` def map(f): [.[] | f]; ``` Arguments are passed as *filters* (functions with no arguments), *not* as values. The same argument may be referenced multiple times with different inputs (here `f` is run for each element of the input array). Arguments to a function work more like callbacks than like value arguments. This is important to understand. Consider: ``` def foo(f): f|f; 5|foo(.*2) ``` The result will be 20 because `f` is `.*2`, and during the first invocation of `f` `.` will be 5, and the second time it will be 10 (5 \* 2), so the result will be 20. Function arguments are filters, and filters expect an input when invoked. If you want the value-argument behaviour for defining simple functions, you can just use a variable: ``` def addvalue(f): f as $f | map(. + $f); ``` Or use the short-hand: ``` def addvalue($f): ...; ``` With either definition, `addvalue(.foo)` will add the current input's `.foo` field to each element of the array. Do note that calling `addvalue(.[])` will cause the `map(. + $f)` part to be evaluated once per value in the value of `.` at the call site. Multiple definitions using the same function name are allowed. Each re-definition replaces the previous one for the same number of function arguments, but only for references from functions (or main program) subsequent to the re-definition. See also the section below on scoping. #### Examples | | | | --- | --- | | | jq 'def addvalue(f): . + [f]; map(addvalue(.[0]))' | | Input | [[1,2],[10,20]] | | Output | [[1,2,1], [10,20,10]] | | | | | --- | --- | | | jq 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])' | | Input | [[1,2],[10,20]] | | Output | [[1,2,1,2], [10,20,1,2]] | ### Scoping There are two types of symbols in jq: value bindings (a.k.a., "variables"), and functions. Both are scoped lexically, with expressions being able to refer only to symbols that have been defined "to the left" of them. The only exception to this rule is that functions can refer to themselves so as to be able to create recursive functions. For example, in the following expression there is a binding which is visible "to the right" of it, `... | .*3 as $times_three | [. + $times_three] | ...`, but not "to the left". Consider this expression now, `... | (.*3 as $times_three | [.+ $times_three]) | ...`: here the binding `$times_three` is *not* visible past the closing parenthesis. ### Reduce The `reduce` syntax in jq allows you to combine all of the results of an expression by accumulating them into a single answer. As an example, we'll pass `[3,2,1]` to this expression: ``` reduce .[] as $item (0; . + $item) ``` For each result that `.[]` produces, `. + $item` is run to accumulate a running total, starting from 0. In this example, `.[]` produces the results 3, 2, and 1, so the effect is similar to running something like this: ``` 0 | (3 as $item | . + $item) | (2 as $item | . + $item) | (1 as $item | . + $item) ``` #### Example | | | | --- | --- | | | jq 'reduce .[] as $item (0; . + $item)' | | Input | [10,2,5,3] | | Output | 20 | ### `isempty(exp)` Returns true if `exp` produces no outputs, false otherwise. #### Example | | | | --- | --- | | | jq 'isempty(empty)' | | Input | null | | Output | true | ### `limit(n; exp)` The `limit` function extracts up to `n` outputs from `exp`. #### Example | | | | --- | --- | | | jq '[limit(3;.[])]' | | Input | [0,1,2,3,4,5,6,7,8,9] | | Output | [0,1,2] | ### `first(expr)`, `last(expr)`, `nth(n; expr)` The `first(expr)` and `last(expr)` functions extract the first and last values from `expr`, respectively. The `nth(n; expr)` function extracts the nth value output by `expr`. This can be defined as `def nth(n; expr): last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't support negative values of `n`. #### Example | | | | --- | --- | | | jq '[first(range(.)), last(range(.)), nth(./2; range(.))]' | | Input | 10 | | Output | [0,9,5] | ### `first`, `last`, `nth(n)` The `first` and `last` functions extract the first and last values from any array at `.`. The `nth(n)` function extracts the nth value of any array at `.`. #### Example | | | | --- | --- | | | jq '[range(.)]|[first, last, nth(5)]' | | Input | 10 | | Output | [0,9,5] | ### `foreach` The `foreach` syntax is similar to `reduce`, but intended to allow the construction of `limit` and reducers that produce intermediate results (see example). The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`. Like `reduce`, `INIT` is evaluated once to produce a state value, then each output of `EXP` is bound to `$var`, `UPDATE` is evaluated for each output of `EXP` with the current state and with `$var` visible. Each value output by `UPDATE` replaces the previous state. Finally, `EXTRACT` is evaluated for each new state to extract an output of `foreach`. This is mostly useful only for constructing `reduce`- and `limit`-like functions. But it is much more general, as it allows for partial reductions (see the example below). #### Example | | | | --- | --- | | | jq '[foreach .[] as $item ([[],[]]; if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end; if $item == null then .[1] else empty end)]' | | Input | [1,2,3,4,null,"a","b",null] | | Output | [[1,2,3,4],["a","b"]] | ### Recursion As described above, `recurse` uses recursion, and any jq function can be recursive. The `while` builtin is also implemented in terms of recursion. Tail calls are optimized whenever the expression to the left of the recursive call outputs its last value. In practice this means that the expression to the left of the recursive call should not produce more than one output for each input. For example: ``` def recurse(f): def r: ., (f | select(. != null) | r); r; def while(cond; update): def _while: if cond then ., (update | _while) else empty end; _while; def repeat(exp): def _repeat: exp, _repeat; _repeat; ``` ### Generators and iterators Some jq operators and functions are actually generators in that they can produce zero, one, or more values for each input, just as one might expect in other programming languages that have generators. For example, `.[]` generates all the values in its input (which must be an array or an object), `range(0; 10)` generates the integers between 0 and 10, and so on. Even the comma operator is a generator, generating first the values generated by the expression to the left of the comma, then for each of those, the values generate by the expression on the right of the comma. The `empty` builtin is the generator that produces zero outputs. The `empty` builtin backtracks to the preceding generator expression. All jq functions can be generators just by using builtin generators. It is also possible to define new generators using only recursion and the comma operator. If the recursive call(s) is(are) "in tail position" then the generator will be efficient. In the example below the recursive call by `_range` to itself is in tail position. The example shows off three advanced topics: tail recursion, generator construction, and sub-functions. #### Examples | | | | --- | --- | | | jq 'def range(init; upto; by): def \_range: if (by > 0 and . < upto) or (by < 0 and . > upto) then ., ((.+by)|\_range) else . end; if by == 0 then init else init|\_range end | select((by > 0 and . < upto) or (by < 0 and . > upto)); range(0; 10; 3)' | | Input | null | | Output | 0 | | | 3 | | | 6 | | | 9 | | | | | --- | --- | | | jq 'def while(cond; update): def \_while: if cond then ., (update | \_while) else empty end; \_while; [while(.<100; .\*2)]' | | Input | 1 | | Output | [1,2,4,8,16,32,64] | Math ---- jq currently only has IEEE754 double-precision (64-bit) floating point number support. Besides simple arithmetic operators such as `+`, jq also has most standard math functions from the C math library. C math functions that take a single input argument (e.g., `sin()`) are available as zero-argument jq functions. C math functions that take two input arguments (e.g., `pow()`) are available as two-argument jq functions that ignore `.`. C math functions that take three input arguments are available as three-argument jq functions that ignore `.`. Availability of standard math functions depends on the availability of the corresponding math functions in your operating system and C math library. Unavailable math functions will be defined but will raise an error. One-input C math functions: `acos` `acosh` `asin` `asinh` `atan` `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10` `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log` `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round` `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc` `y0` `y1`. Two-input C math functions: `atan2` `copysign` `drem` `fdim` `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf` `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`. Three-input C math functions: `fma`. See your system's manual for more information on each of these. I/O --- At this time jq has minimal support for I/O, mostly in the form of control over when inputs are read. Two builtins functions are provided for this, `input` and `inputs`, that read from the same sources (e.g., `stdin`, files named on the command-line) as jq itself. These two builtins, and jq's own reading actions, can be interleaved with each other. Two builtins provide minimal output capabilities, `debug`, and `stderr`. (Recall that a jq program's output values are always output as JSON texts on `stdout`.) The `debug` builtin can have application-specific behavior, such as for executables that use the libjq C API but aren't the jq executable itself. The `stderr` builtin outputs its input in raw mode to stder with no additional decoration, not even a newline. Most jq builtins are referentially transparent, and yield constant and repeatable value streams when applied to constant inputs. This is not true of I/O builtins. ### `input` Outputs one new input. ### `inputs` Outputs all remaining inputs, one by one. This is primarily useful for reductions over a program's inputs. ### `debug` Causes a debug message based on the input value to be produced. The jq executable wraps the input value with `["DEBUG:", <input-value>]` and prints that and a newline on stderr, compactly. This may change in the future. ### `stderr` Prints its input in raw and compact mode to stderr with no additional decoration, not even a newline. ### `input_filename` Returns the name of the file whose input is currently being filtered. Note that this will not work well unless jq is running in a UTF-8 locale. ### `input_line_number` Returns the line number of the input currently being filtered. Streaming --------- With the `--stream` option jq can parse input texts in a streaming fashion, allowing jq programs to start processing large JSON texts immediately rather than after the parse completes. If you have a single JSON text that is 1GB in size, streaming it will allow you to process it much more quickly. However, streaming isn't easy to deal with as the jq program will have `[<path>, <leaf-value>]` (and a few other forms) as inputs. Several builtins are provided to make handling streams easier. The examples below use the streamed form of `[0,[1]]`, which is `[[0],0],[[1,0],1],[[1,0]],[[1]]`. Streaming forms include `[<path>, <leaf-value>]` (to indicate any scalar value, empty array, or empty object), and `[<path>]` (to indicate the end of an array or object). Future versions of jq run with `--stream` and `-seq` may output additional forms such as `["error message"]` when an input text fails to parse. ### `truncate_stream(stream_expression)` Consumes a number as input and truncates the corresponding number of path elements from the left of the outputs of the given streaming expression. #### Example | | | | --- | --- | | | jq '[1|truncate\_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]' | | Input | 1 | | Output | [[[0],2],[[0]]] | ### `fromstream(stream_expression)` Outputs values corresponding to the stream expression's outputs. #### Example | | | | --- | --- | | | jq 'fromstream(1|truncate\_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))' | | Input | null | | Output | [2] | ### `tostream` The `tostream` builtin outputs the streamed form of its input. #### Example | | | | --- | --- | | | jq '. as $dot|fromstream($dot|tostream)|.==$dot' | | Input | [0,[1,{"a":1},{"b":2}]] | | Output | true | Assignment ---------- Assignment works a little differently in jq than in most programming languages. jq doesn't distinguish between references to and copies of something - two objects or arrays are either equal or not equal, without any further notion of being "the same object" or "not the same object". If an object has two fields which are arrays, `.foo` and `.bar`, and you append something to `.foo`, then `.bar` will not get bigger, even if you've previously set `.bar = .foo`. If you're used to programming in languages like Python, Java, Ruby, Javascript, etc. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance it doesn't actually do that, but that's the general idea). This means that it's impossible to build circular values in jq (such as an array whose first element is itself). This is quite intentional, and ensures that anything a jq program can produce can be represented in JSON. All the assignment operators in jq have path expressions on the left-hand side (LHS). The right-hand side (RHS) provides values to set to the paths named by the LHS path expressions. Values in jq are always immutable. Internally, assignment works by using a reduction to compute new, replacement values for `.` that have had all the desired assignments applied to `.`, then outputting the modified value. This might be made clear by this example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last sub-expression, `.`, sees the original value, not the modified value. Most users will want to use modification assignment operators, such as `|=` or `+=`, rather than `=`. Note that the LHS of assignment operators refers to a value in `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is not a valid or useful path expression in `.`); use `$var | .foo = 1` instead. Note too that `.a,.b=0` does not set `.a` and `.b`, but `(.a,.b)=0` sets both. ### Update-assignment: `|=` This is the "update" operator '|='. It takes a filter on the right-hand side and works out the new value for the property of `.` being assigned to by running the old value through this expression. For instance, (.foo, .bar) |= .+1 will build an object with the "foo" field set to the input's "foo" plus 1, and the "bar" field set to the input's "bar" plus 1. The left-hand side can be any general path expression; see `path()`. Note that the left-hand side of '|=' refers to a value in `.`. Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is not a valid or useful path expression in `.`); use `$var | .foo |= . + 1` instead. If the right-hand side outputs no values (i.e., `empty`), then the left-hand side path will be deleted, as with `del(path)`. If the right-hand side outputs multiple values, only the first one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier releases, it used to be that only the last one was used). #### Example | | | | --- | --- | | | jq '(..|select(type=="boolean")) |= if . then 1 else 0 end' | | Input | [true,false,[5,true,[true,[false]],false]] | | Output | [1,0,[5,1,[1,[0]],0]] | ### Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=` jq has a few operators of the form `a op= b`, which are all equivalent to `a |= . op b`. So, `+= 1` can be used to increment values, being the same as `|= . + 1`. #### Example | | | | --- | --- | | | jq '.foo += 1' | | Input | {"foo": 42} | | Output | {"foo": 43} | ### Plain assignment: `=` This is the plain assignment operator. Unlike the others, the input to the right-hand-side (RHS) is the same as the input to the left-hand-side (LHS) rather than the value at the LHS path, and all values output by the RHS will be used (as shown below). If the RHS of '=' produces multiple values, then for each such value jq will set the paths on the left-hand side to the value and then it will output the modified `.`. For example, `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then `{"a":1,"b":1}`. The "update" assignment forms (see above) do not do this. This example should show the difference between '=' and '|=': Provide input '{"a": {"b": 10}, "b": 20}' to the programs: .a = .b .a |= .b The former will set the "a" field of the input to the "b" field of the input, and produce the output {"a": 20, "b": 20}. The latter will set the "a" field of the input to the "a" field's "b" field, producing {"a": 10, "b": 20}. Another example of the difference between '=' and '|=': null|(.a,.b)=range(3) outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}', while null|(.a,.b)|=range(3) outputs just '{"a":0,"b":0}'. ### Complex assignments Lots more things are allowed on the left-hand side of a jq assignment than in most languages. We've already seen simple field accesses on the left hand side, and it's no surprise that array accesses work just as well: ``` .posts[0].title = "JQ Manual" ``` What may come as a surprise is that the expression on the left may produce multiple results, referring to different points in the input document: ``` .posts[].comments |= . + ["this is great"] ``` That example appends the string "this is great" to the "comments" array of each post in the input (where the input is an object with a field "posts" which is an array of posts). When jq encounters an assignment like 'a = b', it records the "path" taken to select a part of the input document while executing a. This path is then used to find which part of the input to change while executing the assignment. Any filter may be used on the left-hand side of an equals - whichever paths it selects from the input will be where the assignment is performed. This is a very powerful operation. Suppose we wanted to add a comment to blog posts, using the same "blog" input above. This time, we only want to comment on the posts written by "stedolan". We can find those posts using the "select" function described earlier: ``` .posts[] | select(.author == "stedolan") ``` The paths provided by this operation point to each of the posts that "stedolan" wrote, and we can comment on each of them in the same way that we did before: ``` (.posts[] | select(.author == "stedolan") | .comments) |= . + ["terrible."] ``` Modules ------- jq has a library/module system. Modules are files whose names end in `.jq`. Modules imported by a program are searched for in a default search path (see below). The `import` and `include` directives allow the importer to alter this path. Paths in the a search path are subject to various substitutions. For paths starting with "~/", the user's home directory is substituted for "~". For paths starting with "$ORIGIN/", the path of the jq executable is substituted for "$ORIGIN". For paths starting with "./" or paths that are ".", the path of the including file is substituted for ".". For top-level programs given on the command-line, the current directory is used. Import directives can optionally specify a search path to which the default is appended. The default search path is the search path given to the `-L` command-line option, else `["~/.jq", "$ORIGIN/../lib/jq", "$ORIGIN/../lib"]`. Null and empty string path elements terminate search path processing. A dependency with relative path "foo/bar" would be searched for in "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This is intended to allow modules to be placed in a directory along with, for example, version control files, README files, and so on, but also to allow for single-file modules. Consecutive components with the same name are not allowed to avoid ambiguities (e.g., "foo/foo"). For example, with `-L$HOME/.jq` a module `foo` can be found in `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`. If "$HOME/.jq" is a file, it is sourced into the main program. ### `import RelativePathString as NAME [<metadata>];` Imports a module found at the given path relative to a directory in a search path. A ".jq" suffix will be added to the relative path string. The module's symbols are prefixed with "NAME::". The optional metadata must be a constant jq expression. It should be an object with keys like "homepage" and so on. At this time jq only uses the "search" key/value of the metadata. The metadata is also made available to users via the `modulemeta` builtin. The "search" key in the metadata, if present, should have a string or array value (array of strings); this is the search path to be prefixed to the top-level search path. ### `include RelativePathString [<metadata>];` Imports a module found at the given path relative to a directory in a search path as if it were included in place. A ".jq" suffix will be added to the relative path string. The module's symbols are imported into the caller's namespace as if the module's content had been included directly. The optional metadata must be a constant jq expression. It should be an object with keys like "homepage" and so on. At this time jq only uses the "search" key/value of the metadata. The metadata is also made available to users via the `modulemeta` builtin. ### `import RelativePathString as $NAME [<metadata>];` Imports a JSON file found at the given path relative to a directory in a search path. A ".json" suffix will be added to the relative path string. The file's data will be available as `$NAME::NAME`. The optional metadata must be a constant jq expression. It should be an object with keys like "homepage" and so on. At this time jq only uses the "search" key/value of the metadata. The metadata is also made available to users via the `modulemeta` builtin. The "search" key in the metadata, if present, should have a string or array value (array of strings); this is the search path to be prefixed to the top-level search path. ### `module <metadata>;` This directive is entirely optional. It's not required for proper operation. It serves only the purpose of providing metadata that can be read with the `modulemeta` builtin. The metadata must be a constant jq expression. It should be an object with keys like "homepage". At this time jq doesn't use this metadata, but it is made available to users via the `modulemeta` builtin. ### `modulemeta` Takes a module name as input and outputs the module's metadata as an object, with the module's imports (including metadata) as an array value for the "deps" key. Programs can use this to query a module's metadata, which they could then use to, for example, search for, download, and install missing dependencies. Colors ------ To configure alternative colors just set the `JQ_COLORS` environment variable to colon-delimited list of partial terminal escape sequences like `"1;31"`, in this order: * color for `null` * color for `false` * color for `true` * color for numbers * color for strings * color for arrays * color for objects The default color scheme is the same as setting `"JQ_COLORS=1;30:0;37:0;37:0;37:0;32:1;37:1;37"`. This is not a manual for VT100/ANSI escapes. However, each of these color specifications should consist of two numbers separated by a semi-colon, where the first number is one of these: * 1 (bright) * 2 (dim) * 4 (underscore) * 5 (blink) * 7 (reverse) * 8 (hidden) and the second is one of these: * 30 (black) * 31 (red) * 32 (green) * 33 (yellow) * 34 (blue) * 35 (magenta) * 36 (cyan) * 37 (white)
programming_docs
python Python Python ====== Welcome! This is the official documentation for Python 3.9.14. **Parts of the documentation:** | | | | --- | --- | | [What's new in Python 3.9?](https://docs.python.org/3.9/whatsnew/3.9.html) or [all "What's new" documents](https://docs.python.org/3.9/whatsnew/index.html) since 2.0 [Tutorial](tutorial/index) start here [Library Reference](library/index) keep this under your pillow [Language Reference](reference/index) describes syntax and language elements [Python Setup and Usage](using/index) how to use Python on different platforms [Python HOWTOs](howto/index) in-depth documents on specific topics | [Installing Python Modules](installing/index) installing from the Python Package Index & other sources [Distributing Python Modules](distributing/index) publishing modules for installation by others [Extending and Embedding](extending/index) tutorial for C/C++ programmers [Python/C API](c-api/index) reference for C/C++ programmers [FAQs](faq/index) frequently asked questions (with answers!) | **Indices and tables:** | | | | --- | --- | | [Global Module Index](py-modindex) quick access to all modules [General Index](genindex) all functions, classes, terms [Glossary](glossary) the most important terms explained | [Search page](search) search this documentation [Complete Table of Contents](contents) lists all sections and subsections | **Meta information:** | | | | --- | --- | | [Reporting bugs](bugs) [Contributing to Docs](https://devguide.python.org/docquality/#helping-with-documentation) [About the documentation](about) | [History and License of Python](license) [Copyright](copyright) | python About these documents About these documents ===================== These documents are generated from [reStructuredText](http://docutils.sourceforge.net/rst.html) sources by [Sphinx](http://sphinx-doc.org/), a document processor specifically written for the Python documentation. Development of the documentation and its toolchain is an entirely volunteer effort, just like Python itself. If you want to contribute, please take a look at the [Dealing with Bugs](bugs#reporting-bugs) page for information on how to do so. New volunteers are always welcome! Many thanks go to: * Fred L. Drake, Jr., the creator of the original Python documentation toolset and writer of much of the content; * the [Docutils](http://docutils.sourceforge.net/) project for creating reStructuredText and the Docutils suite; * Fredrik Lundh for his Alternative Python Reference project from which Sphinx got many good ideas. Contributors to the Python Documentation ---------------------------------------- Many people have contributed to the Python language, the Python standard library, and the Python documentation. See [Misc/ACKS](https://github.com/python/cpython/tree/3.9/Misc/ACKS) in the Python source distribution for a partial list of contributors. It is only with the input and contributions of the Python community that Python has such wonderful documentation – Thank You! python History and License History and License =================== History of the software ----------------------- Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see <https://www.cwi.nl/>) in the Netherlands as a successor of a language called ABC. Guido remains Python’s principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see <https://www.cnri.reston.va.us/>) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation; see <https://www.zope.org/>). In 2001, the Python Software Foundation (PSF, see <https://www.python.org/psf/>) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see <https://opensource.org/> for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. | Release | Derived from | Year | Owner | GPL compatible? | | --- | --- | --- | --- | --- | | 0.9.0 thru 1.2 | n/a | 1991-1995 | CWI | yes | | 1.3 thru 1.5.2 | 1.2 | 1995-1999 | CNRI | yes | | 1.6 | 1.5.2 | 2000 | CNRI | no | | 2.0 | 1.6 | 2000 | BeOpen.com | no | | 1.6.1 | 1.6 | 2001 | CNRI | no | | 2.1 | 2.0+1.6.1 | 2001 | PSF | no | | 2.0.1 | 2.0+1.6.1 | 2001 | PSF | yes | | 2.1.1 | 2.1+2.0.1 | 2001 | PSF | yes | | 2.1.2 | 2.1.1 | 2002 | PSF | yes | | 2.1.3 | 2.1.2 | 2002 | PSF | yes | | 2.2 and above | 2.1.1 | 2001-now | PSF | yes | Note GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don’t. Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases possible. Terms and conditions for accessing or otherwise using Python ------------------------------------------------------------ Python software and documentation are licensed under the [PSF License Agreement](#psf-license). Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the [Zero-Clause BSD license](#bsd0). Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See [Licenses and Acknowledgements for Incorporated Software](#otherlicenses) for an incomplete list of these licenses. ### PSF LICENSE AGREEMENT FOR PYTHON 3.9.14 ``` 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 3.9.14 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 3.9.14 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright © 2001-2022 Python Software Foundation; All Rights Reserved" are retained in Python 3.9.14 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 3.9.14 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 3.9.14. 4. PSF is making Python 3.9.14 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 3.9.14 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.9.14 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.9.14, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python 3.9.14, Licensee agrees to be bound by the terms and conditions of this License Agreement. ``` ### BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 ``` 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. ``` ### CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 ``` 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013." 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ``` ### CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 ``` Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ``` ### ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.14 DOCUMENTATION ``` Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ``` Licenses and Acknowledgements for Incorporated Software ------------------------------------------------------- This section is an incomplete, but growing list of licenses and acknowledgements for third-party software incorporated in the Python distribution. ### Mersenne Twister The `_random` module includes code based on a download from <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html>. The following are the verbatim comments from the original code: ``` A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) ``` ### Sockets The [`socket`](library/socket#module-socket "socket: Low-level networking interface.") module uses the functions, `getaddrinfo()`, and `getnameinfo()`, which are coded in separate source files from the WIDE Project, <http://www.wide.ad.jp/>. ``` Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` ### Asynchronous socket services The [`asynchat`](library/asynchat#module-asynchat "asynchat: Support for asynchronous command/response protocols. (deprecated)") and [`asyncore`](library/asyncore#module-asyncore "asyncore: A base class for developing asynchronous socket handling services. (deprecated)") modules contain the following notice: ``` Copyright 1996 by Sam Rushing All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Sam Rushing not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ``` ### Cookie management The [`http.cookies`](library/http.cookies#module-http.cookies "http.cookies: Support for HTTP state management (cookies).") module contains the following notice: ``` Copyright 2000 by Timothy O'Malley <[email protected]> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Timothy O'Malley not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ``` ### Execution tracing The [`trace`](library/trace#module-trace "trace: Trace or track Python statement execution.") module contains the following notice: ``` portions copyright 2001, Autonomous Zones Industries, Inc., all rights... err... reserved and offered to the public under the terms of the Python 2.2 license. Author: Zooko O'Whielacronx http://zooko.com/ mailto:[email protected] Copyright 2000, Mojam Media, Inc., all rights reserved. Author: Skip Montanaro Copyright 1999, Bioreason, Inc., all rights reserved. Author: Andrew Dalke Copyright 1995-1997, Automatrix, Inc., all rights reserved. Author: Skip Montanaro Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. Permission to use, copy, modify, and distribute this Python software and its associated documentation for any purpose without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of neither Automatrix, Bioreason or Mojam Media be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. ``` ### UUencode and UUdecode functions The [`uu`](library/uu#module-uu "uu: Encode and decode files in uuencode format. (deprecated)") module contains the following notice: ``` Copyright 1994 by Lance Ellinghouse Cathedral City, California Republic, United States of America. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Lance Ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Modified by Jack Jansen, CWI, July 1995: - Use binascii module to do the actual line-by-line conversion between ascii and binary. This results in a 1000-fold speedup. The C version is still 5 times faster, though. - Arguments more compliant with Python standard ``` ### XML Remote Procedure Calls The [`xmlrpc.client`](library/xmlrpc.client#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") module contains the following notice: ``` The XML-RPC client interface is Copyright (c) 1999-2002 by Secret Labs AB Copyright (c) 1999-2002 by Fredrik Lundh By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ``` ### test\_epoll The `test_epoll` module contains the following notice: ``` Copyright (c) 2001-2006 Twisted Matrix Laboratories. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### Select kqueue The [`select`](library/select#module-select "select: Wait for I/O completion on multiple streams.") module contains the following notice for the kqueue interface: ``` Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` ### SipHash24 The file `Python/pyhash.c` contains Marek Majkowski’ implementation of Dan Bernstein’s SipHash24 algorithm. It contains the following note: ``` <MIT License> Copyright (c) 2013 Marek Majkowski <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. </MIT License> Original location: https://github.com/majek/csiphash/ Solution inspired by code from: Samuel Neves (supercop/crypto_auth/siphash24/little) djb (supercop/crypto_auth/siphash24/little2) Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c) ``` ### strtod and dtoa The file `Python/dtoa.c`, which supplies C functions dtoa and strtod for conversion of C doubles to and from strings, is derived from the file of the same name by David M. Gay, currently available from <http://www.netlib.org/fp/>. The original file, as retrieved on March 16, 2009, contains the following copyright and licensing notice: ``` /**************************************************************** * * The author of this software is David M. Gay. * * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. * * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. * ***************************************************************/ ``` ### OpenSSL The modules [`hashlib`](library/hashlib#module-hashlib "hashlib: Secure hash and message digest algorithms."), [`posix`](library/posix#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)"), [`ssl`](library/ssl#module-ssl "ssl: TLS/SSL wrapper for socket objects"), [`crypt`](library/crypt#module-crypt "crypt: The crypt() function used to check Unix passwords. (deprecated) (Unix)") use the OpenSSL library for added performance if made available by the operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL libraries, so we include a copy of the OpenSSL license here: ``` LICENSE ISSUES ============== The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually both licenses are BSD-style Open Source licenses. In case of any license issues related to OpenSSL please contact [email protected]. OpenSSL License --------------- /* ==================================================================== * Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ Original SSLeay License ----------------------- /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ ``` ### expat The `pyexpat` extension is built using an included copy of the expat sources unless the build is configured `--with-system-expat`: ``` Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### libffi The `_ctypes` extension is built using an included copy of the libffi sources unless the build is configured `--with-system-libffi`: ``` Copyright (c) 1996-2008 Red Hat, Inc and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ### zlib The [`zlib`](library/zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.") extension is built using an included copy of the zlib sources if the zlib version found on the system is too old to be used for the build: ``` Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler [email protected] [email protected] ``` ### cfuhash The implementation of the hash table used by the [`tracemalloc`](library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") is based on the cfuhash project: ``` Copyright (c) 2005 Don Owens All rights reserved. This code is released under the BSD license: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` ### libmpdec The `_decimal` module is built using an included copy of the libmpdec library unless the build is configured `--with-system-libmpdec`: ``` Copyright (c) 2008-2020 Stefan Krah. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` ### W3C C14N test suite The C14N 2.0 test suite in the [`test`](library/test#module-test "test: Regression tests package containing the testing suite for Python.") package (`Lib/test/xmltestdata/c14n-20/`) was retrieved from the W3C website at <https://www.w3.org/TR/xml-c14n2-testcases/> and is distributed under the 3-clause BSD license: ``` Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang), All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ```
programming_docs
python Python Documentation contents Python Documentation contents ============================= * [What’s New in Python](https://docs.python.org/3.9/whatsnew/index.html) + [What’s New In Python 3.9](https://docs.python.org/3.9/whatsnew/3.9.html) - [Summary – Release highlights](https://docs.python.org/3.9/whatsnew/3.9.html#summary-release-highlights) - [You should check for DeprecationWarning in your code](https://docs.python.org/3.9/whatsnew/3.9.html#you-should-check-for-deprecationwarning-in-your-code) - [New Features](https://docs.python.org/3.9/whatsnew/3.9.html#new-features) * [Dictionary Merge & Update Operators](https://docs.python.org/3.9/whatsnew/3.9.html#dictionary-merge-update-operators) * [New String Methods to Remove Prefixes and Suffixes](https://docs.python.org/3.9/whatsnew/3.9.html#new-string-methods-to-remove-prefixes-and-suffixes) * [Type Hinting Generics in Standard Collections](https://docs.python.org/3.9/whatsnew/3.9.html#type-hinting-generics-in-standard-collections) * [New Parser](https://docs.python.org/3.9/whatsnew/3.9.html#new-parser) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.9.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.9.html#new-modules) * [zoneinfo](https://docs.python.org/3.9/whatsnew/3.9.html#zoneinfo) * [graphlib](https://docs.python.org/3.9/whatsnew/3.9.html#graphlib) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.9.html#improved-modules) * [ast](https://docs.python.org/3.9/whatsnew/3.9.html#ast) * [asyncio](https://docs.python.org/3.9/whatsnew/3.9.html#asyncio) * [compileall](https://docs.python.org/3.9/whatsnew/3.9.html#compileall) * [concurrent.futures](https://docs.python.org/3.9/whatsnew/3.9.html#concurrent-futures) * [curses](https://docs.python.org/3.9/whatsnew/3.9.html#curses) * [datetime](https://docs.python.org/3.9/whatsnew/3.9.html#datetime) * [distutils](https://docs.python.org/3.9/whatsnew/3.9.html#distutils) * [fcntl](https://docs.python.org/3.9/whatsnew/3.9.html#fcntl) * [ftplib](https://docs.python.org/3.9/whatsnew/3.9.html#ftplib) * [gc](https://docs.python.org/3.9/whatsnew/3.9.html#gc) * [hashlib](https://docs.python.org/3.9/whatsnew/3.9.html#hashlib) * [http](https://docs.python.org/3.9/whatsnew/3.9.html#http) * [IDLE and idlelib](https://docs.python.org/3.9/whatsnew/3.9.html#idle-and-idlelib) * [imaplib](https://docs.python.org/3.9/whatsnew/3.9.html#imaplib) * [importlib](https://docs.python.org/3.9/whatsnew/3.9.html#importlib) * [inspect](https://docs.python.org/3.9/whatsnew/3.9.html#inspect) * [ipaddress](https://docs.python.org/3.9/whatsnew/3.9.html#ipaddress) * [math](https://docs.python.org/3.9/whatsnew/3.9.html#math) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.9.html#multiprocessing) * [nntplib](https://docs.python.org/3.9/whatsnew/3.9.html#nntplib) * [os](https://docs.python.org/3.9/whatsnew/3.9.html#os) * [pathlib](https://docs.python.org/3.9/whatsnew/3.9.html#pathlib) * [pdb](https://docs.python.org/3.9/whatsnew/3.9.html#pdb) * [poplib](https://docs.python.org/3.9/whatsnew/3.9.html#poplib) * [pprint](https://docs.python.org/3.9/whatsnew/3.9.html#pprint) * [pydoc](https://docs.python.org/3.9/whatsnew/3.9.html#pydoc) * [random](https://docs.python.org/3.9/whatsnew/3.9.html#random) * [signal](https://docs.python.org/3.9/whatsnew/3.9.html#signal) * [smtplib](https://docs.python.org/3.9/whatsnew/3.9.html#smtplib) * [socket](https://docs.python.org/3.9/whatsnew/3.9.html#socket) * [time](https://docs.python.org/3.9/whatsnew/3.9.html#time) * [sys](https://docs.python.org/3.9/whatsnew/3.9.html#sys) * [tracemalloc](https://docs.python.org/3.9/whatsnew/3.9.html#tracemalloc) * [typing](https://docs.python.org/3.9/whatsnew/3.9.html#typing) * [unicodedata](https://docs.python.org/3.9/whatsnew/3.9.html#unicodedata) * [venv](https://docs.python.org/3.9/whatsnew/3.9.html#venv) * [xml](https://docs.python.org/3.9/whatsnew/3.9.html#xml) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.9.html#optimizations) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.9.html#deprecated) - [Removed](https://docs.python.org/3.9/whatsnew/3.9.html#removed) - [Porting to Python 3.9](https://docs.python.org/3.9/whatsnew/3.9.html#porting-to-python-3-9) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.9.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.9.html#changes-in-the-c-api) * [CPython bytecode changes](https://docs.python.org/3.9/whatsnew/3.9.html#cpython-bytecode-changes) - [Build Changes](https://docs.python.org/3.9/whatsnew/3.9.html#build-changes) - [C API Changes](https://docs.python.org/3.9/whatsnew/3.9.html#c-api-changes) * [New Features](https://docs.python.org/3.9/whatsnew/3.9.html#id1) * [Porting to Python 3.9](https://docs.python.org/3.9/whatsnew/3.9.html#id2) * [Removed](https://docs.python.org/3.9/whatsnew/3.9.html#id3) - [Notable changes in Python 3.9.1](https://docs.python.org/3.9/whatsnew/3.9.html#notable-changes-in-python-3-9-1) * [typing](https://docs.python.org/3.9/whatsnew/3.9.html#id4) * [macOS 11.0 (Big Sur) and Apple Silicon Mac support](https://docs.python.org/3.9/whatsnew/3.9.html#macos-11-0-big-sur-and-apple-silicon-mac-support) - [Notable changes in Python 3.9.2](https://docs.python.org/3.9/whatsnew/3.9.html#notable-changes-in-python-3-9-2) * [collections.abc](https://docs.python.org/3.9/whatsnew/3.9.html#collections-abc) * [urllib.parse](https://docs.python.org/3.9/whatsnew/3.9.html#urllib-parse) - [Notable changes in Python 3.9.3](https://docs.python.org/3.9/whatsnew/3.9.html#notable-changes-in-python-3-9-3) - [Notable changes in Python 3.9.5](https://docs.python.org/3.9/whatsnew/3.9.html#notable-changes-in-python-3-9-5) * [urllib.parse](https://docs.python.org/3.9/whatsnew/3.9.html#id5) - [Notable security feature in 3.9.14](https://docs.python.org/3.9/whatsnew/3.9.html#notable-security-feature-in-3-9-14) + [What’s New In Python 3.8](https://docs.python.org/3.9/whatsnew/3.8.html) - [Summary – Release highlights](https://docs.python.org/3.9/whatsnew/3.8.html#summary-release-highlights) - [New Features](https://docs.python.org/3.9/whatsnew/3.8.html#new-features) * [Assignment expressions](https://docs.python.org/3.9/whatsnew/3.8.html#assignment-expressions) * [Positional-only parameters](https://docs.python.org/3.9/whatsnew/3.8.html#positional-only-parameters) * [Parallel filesystem cache for compiled bytecode files](https://docs.python.org/3.9/whatsnew/3.8.html#parallel-filesystem-cache-for-compiled-bytecode-files) * [Debug build uses the same ABI as release build](https://docs.python.org/3.9/whatsnew/3.8.html#debug-build-uses-the-same-abi-as-release-build) * [f-strings support `=` for self-documenting expressions and debugging](https://docs.python.org/3.9/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging) * [PEP 578: Python Runtime Audit Hooks](https://docs.python.org/3.9/whatsnew/3.8.html#pep-578-python-runtime-audit-hooks) * [PEP 587: Python Initialization Configuration](https://docs.python.org/3.9/whatsnew/3.8.html#pep-587-python-initialization-configuration) * [PEP 590: Vectorcall: a fast calling protocol for CPython](https://docs.python.org/3.9/whatsnew/3.8.html#pep-590-vectorcall-a-fast-calling-protocol-for-cpython) * [Pickle protocol 5 with out-of-band data buffers](https://docs.python.org/3.9/whatsnew/3.8.html#pickle-protocol-5-with-out-of-band-data-buffers) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.8.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.8.html#new-modules) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.8.html#improved-modules) * [ast](https://docs.python.org/3.9/whatsnew/3.8.html#ast) * [asyncio](https://docs.python.org/3.9/whatsnew/3.8.html#asyncio) * [builtins](https://docs.python.org/3.9/whatsnew/3.8.html#builtins) * [collections](https://docs.python.org/3.9/whatsnew/3.8.html#collections) * [cProfile](https://docs.python.org/3.9/whatsnew/3.8.html#cprofile) * [csv](https://docs.python.org/3.9/whatsnew/3.8.html#csv) * [curses](https://docs.python.org/3.9/whatsnew/3.8.html#curses) * [ctypes](https://docs.python.org/3.9/whatsnew/3.8.html#ctypes) * [datetime](https://docs.python.org/3.9/whatsnew/3.8.html#datetime) * [functools](https://docs.python.org/3.9/whatsnew/3.8.html#functools) * [gc](https://docs.python.org/3.9/whatsnew/3.8.html#gc) * [gettext](https://docs.python.org/3.9/whatsnew/3.8.html#gettext) * [gzip](https://docs.python.org/3.9/whatsnew/3.8.html#gzip) * [IDLE and idlelib](https://docs.python.org/3.9/whatsnew/3.8.html#idle-and-idlelib) * [inspect](https://docs.python.org/3.9/whatsnew/3.8.html#inspect) * [io](https://docs.python.org/3.9/whatsnew/3.8.html#io) * [itertools](https://docs.python.org/3.9/whatsnew/3.8.html#itertools) * [json.tool](https://docs.python.org/3.9/whatsnew/3.8.html#json-tool) * [logging](https://docs.python.org/3.9/whatsnew/3.8.html#logging) * [math](https://docs.python.org/3.9/whatsnew/3.8.html#math) * [mmap](https://docs.python.org/3.9/whatsnew/3.8.html#mmap) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.8.html#multiprocessing) * [os](https://docs.python.org/3.9/whatsnew/3.8.html#os) * [os.path](https://docs.python.org/3.9/whatsnew/3.8.html#os-path) * [pathlib](https://docs.python.org/3.9/whatsnew/3.8.html#pathlib) * [pickle](https://docs.python.org/3.9/whatsnew/3.8.html#pickle) * [plistlib](https://docs.python.org/3.9/whatsnew/3.8.html#plistlib) * [pprint](https://docs.python.org/3.9/whatsnew/3.8.html#pprint) * [py\_compile](https://docs.python.org/3.9/whatsnew/3.8.html#py-compile) * [shlex](https://docs.python.org/3.9/whatsnew/3.8.html#shlex) * [shutil](https://docs.python.org/3.9/whatsnew/3.8.html#shutil) * [socket](https://docs.python.org/3.9/whatsnew/3.8.html#socket) * [ssl](https://docs.python.org/3.9/whatsnew/3.8.html#ssl) * [statistics](https://docs.python.org/3.9/whatsnew/3.8.html#statistics) * [sys](https://docs.python.org/3.9/whatsnew/3.8.html#sys) * [tarfile](https://docs.python.org/3.9/whatsnew/3.8.html#tarfile) * [threading](https://docs.python.org/3.9/whatsnew/3.8.html#threading) * [tokenize](https://docs.python.org/3.9/whatsnew/3.8.html#tokenize) * [tkinter](https://docs.python.org/3.9/whatsnew/3.8.html#tkinter) * [time](https://docs.python.org/3.9/whatsnew/3.8.html#time) * [typing](https://docs.python.org/3.9/whatsnew/3.8.html#typing) * [unicodedata](https://docs.python.org/3.9/whatsnew/3.8.html#unicodedata) * [unittest](https://docs.python.org/3.9/whatsnew/3.8.html#unittest) * [venv](https://docs.python.org/3.9/whatsnew/3.8.html#venv) * [weakref](https://docs.python.org/3.9/whatsnew/3.8.html#weakref) * [xml](https://docs.python.org/3.9/whatsnew/3.8.html#xml) * [xmlrpc](https://docs.python.org/3.9/whatsnew/3.8.html#xmlrpc) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.8.html#optimizations) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.8.html#build-and-c-api-changes) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.8.html#deprecated) - [API and Feature Removals](https://docs.python.org/3.9/whatsnew/3.8.html#api-and-feature-removals) - [Porting to Python 3.8](https://docs.python.org/3.9/whatsnew/3.8.html#porting-to-python-3-8) * [Changes in Python behavior](https://docs.python.org/3.9/whatsnew/3.8.html#changes-in-python-behavior) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.8.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.8.html#changes-in-the-c-api) * [CPython bytecode changes](https://docs.python.org/3.9/whatsnew/3.8.html#cpython-bytecode-changes) * [Demos and Tools](https://docs.python.org/3.9/whatsnew/3.8.html#demos-and-tools) - [Notable changes in Python 3.8.1](https://docs.python.org/3.9/whatsnew/3.8.html#notable-changes-in-python-3-8-1) - [Notable changes in Python 3.8.8](https://docs.python.org/3.9/whatsnew/3.8.html#notable-changes-in-python-3-8-8) - [Notable changes in Python 3.8.12](https://docs.python.org/3.9/whatsnew/3.8.html#notable-changes-in-python-3-8-12) + [What’s New In Python 3.7](https://docs.python.org/3.9/whatsnew/3.7.html) - [Summary – Release Highlights](https://docs.python.org/3.9/whatsnew/3.7.html#summary-release-highlights) - [New Features](https://docs.python.org/3.9/whatsnew/3.7.html#new-features) * [PEP 563: Postponed Evaluation of Annotations](https://docs.python.org/3.9/whatsnew/3.7.html#pep-563-postponed-evaluation-of-annotations) * [PEP 538: Legacy C Locale Coercion](https://docs.python.org/3.9/whatsnew/3.7.html#pep-538-legacy-c-locale-coercion) * [PEP 540: Forced UTF-8 Runtime Mode](https://docs.python.org/3.9/whatsnew/3.7.html#pep-540-forced-utf-8-runtime-mode) * [PEP 553: Built-in `breakpoint()`](https://docs.python.org/3.9/whatsnew/3.7.html#pep-553-built-in-breakpoint) * [PEP 539: New C API for Thread-Local Storage](https://docs.python.org/3.9/whatsnew/3.7.html#pep-539-new-c-api-for-thread-local-storage) * [PEP 562: Customization of Access to Module Attributes](https://docs.python.org/3.9/whatsnew/3.7.html#pep-562-customization-of-access-to-module-attributes) * [PEP 564: New Time Functions With Nanosecond Resolution](https://docs.python.org/3.9/whatsnew/3.7.html#pep-564-new-time-functions-with-nanosecond-resolution) * [PEP 565: Show DeprecationWarning in `__main__`](https://docs.python.org/3.9/whatsnew/3.7.html#pep-565-show-deprecationwarning-in-main) * [PEP 560: Core Support for `typing` module and Generic Types](https://docs.python.org/3.9/whatsnew/3.7.html#pep-560-core-support-for-typing-module-and-generic-types) * [PEP 552: Hash-based .pyc Files](https://docs.python.org/3.9/whatsnew/3.7.html#pep-552-hash-based-pyc-files) * [PEP 545: Python Documentation Translations](https://docs.python.org/3.9/whatsnew/3.7.html#pep-545-python-documentation-translations) * [Python Development Mode (-X dev)](https://docs.python.org/3.9/whatsnew/3.7.html#python-development-mode-x-dev) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.7.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.7.html#new-modules) * [contextvars](https://docs.python.org/3.9/whatsnew/3.7.html#contextvars) * [dataclasses](https://docs.python.org/3.9/whatsnew/3.7.html#dataclasses) * [importlib.resources](https://docs.python.org/3.9/whatsnew/3.7.html#importlib-resources) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.7.html#improved-modules) * [argparse](https://docs.python.org/3.9/whatsnew/3.7.html#argparse) * [asyncio](https://docs.python.org/3.9/whatsnew/3.7.html#asyncio) * [binascii](https://docs.python.org/3.9/whatsnew/3.7.html#binascii) * [calendar](https://docs.python.org/3.9/whatsnew/3.7.html#calendar) * [collections](https://docs.python.org/3.9/whatsnew/3.7.html#collections) * [compileall](https://docs.python.org/3.9/whatsnew/3.7.html#compileall) * [concurrent.futures](https://docs.python.org/3.9/whatsnew/3.7.html#concurrent-futures) * [contextlib](https://docs.python.org/3.9/whatsnew/3.7.html#contextlib) * [cProfile](https://docs.python.org/3.9/whatsnew/3.7.html#cprofile) * [crypt](https://docs.python.org/3.9/whatsnew/3.7.html#crypt) * [datetime](https://docs.python.org/3.9/whatsnew/3.7.html#datetime) * [dbm](https://docs.python.org/3.9/whatsnew/3.7.html#dbm) * [decimal](https://docs.python.org/3.9/whatsnew/3.7.html#decimal) * [dis](https://docs.python.org/3.9/whatsnew/3.7.html#dis) * [distutils](https://docs.python.org/3.9/whatsnew/3.7.html#distutils) * [enum](https://docs.python.org/3.9/whatsnew/3.7.html#enum) * [functools](https://docs.python.org/3.9/whatsnew/3.7.html#functools) * [gc](https://docs.python.org/3.9/whatsnew/3.7.html#gc) * [hmac](https://docs.python.org/3.9/whatsnew/3.7.html#hmac) * [http.client](https://docs.python.org/3.9/whatsnew/3.7.html#http-client) * [http.server](https://docs.python.org/3.9/whatsnew/3.7.html#http-server) * [idlelib and IDLE](https://docs.python.org/3.9/whatsnew/3.7.html#idlelib-and-idle) * [importlib](https://docs.python.org/3.9/whatsnew/3.7.html#importlib) * [io](https://docs.python.org/3.9/whatsnew/3.7.html#io) * [ipaddress](https://docs.python.org/3.9/whatsnew/3.7.html#ipaddress) * [itertools](https://docs.python.org/3.9/whatsnew/3.7.html#itertools) * [locale](https://docs.python.org/3.9/whatsnew/3.7.html#locale) * [logging](https://docs.python.org/3.9/whatsnew/3.7.html#logging) * [math](https://docs.python.org/3.9/whatsnew/3.7.html#math) * [mimetypes](https://docs.python.org/3.9/whatsnew/3.7.html#mimetypes) * [msilib](https://docs.python.org/3.9/whatsnew/3.7.html#msilib) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.7.html#multiprocessing) * [os](https://docs.python.org/3.9/whatsnew/3.7.html#os) * [pathlib](https://docs.python.org/3.9/whatsnew/3.7.html#pathlib) * [pdb](https://docs.python.org/3.9/whatsnew/3.7.html#pdb) * [py\_compile](https://docs.python.org/3.9/whatsnew/3.7.html#py-compile) * [pydoc](https://docs.python.org/3.9/whatsnew/3.7.html#pydoc) * [queue](https://docs.python.org/3.9/whatsnew/3.7.html#queue) * [re](https://docs.python.org/3.9/whatsnew/3.7.html#re) * [signal](https://docs.python.org/3.9/whatsnew/3.7.html#signal) * [socket](https://docs.python.org/3.9/whatsnew/3.7.html#socket) * [socketserver](https://docs.python.org/3.9/whatsnew/3.7.html#socketserver) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.7.html#sqlite3) * [ssl](https://docs.python.org/3.9/whatsnew/3.7.html#ssl) * [string](https://docs.python.org/3.9/whatsnew/3.7.html#string) * [subprocess](https://docs.python.org/3.9/whatsnew/3.7.html#subprocess) * [sys](https://docs.python.org/3.9/whatsnew/3.7.html#sys) * [time](https://docs.python.org/3.9/whatsnew/3.7.html#time) * [tkinter](https://docs.python.org/3.9/whatsnew/3.7.html#tkinter) * [tracemalloc](https://docs.python.org/3.9/whatsnew/3.7.html#tracemalloc) * [types](https://docs.python.org/3.9/whatsnew/3.7.html#types) * [unicodedata](https://docs.python.org/3.9/whatsnew/3.7.html#unicodedata) * [unittest](https://docs.python.org/3.9/whatsnew/3.7.html#unittest) * [unittest.mock](https://docs.python.org/3.9/whatsnew/3.7.html#unittest-mock) * [urllib.parse](https://docs.python.org/3.9/whatsnew/3.7.html#urllib-parse) * [uu](https://docs.python.org/3.9/whatsnew/3.7.html#uu) * [uuid](https://docs.python.org/3.9/whatsnew/3.7.html#uuid) * [warnings](https://docs.python.org/3.9/whatsnew/3.7.html#warnings) * [xml.etree](https://docs.python.org/3.9/whatsnew/3.7.html#xml-etree) * [xmlrpc.server](https://docs.python.org/3.9/whatsnew/3.7.html#xmlrpc-server) * [zipapp](https://docs.python.org/3.9/whatsnew/3.7.html#zipapp) * [zipfile](https://docs.python.org/3.9/whatsnew/3.7.html#zipfile) - [C API Changes](https://docs.python.org/3.9/whatsnew/3.7.html#c-api-changes) - [Build Changes](https://docs.python.org/3.9/whatsnew/3.7.html#build-changes) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.7.html#optimizations) - [Other CPython Implementation Changes](https://docs.python.org/3.9/whatsnew/3.7.html#other-cpython-implementation-changes) - [Deprecated Python Behavior](https://docs.python.org/3.9/whatsnew/3.7.html#deprecated-python-behavior) - [Deprecated Python modules, functions and methods](https://docs.python.org/3.9/whatsnew/3.7.html#deprecated-python-modules-functions-and-methods) * [aifc](https://docs.python.org/3.9/whatsnew/3.7.html#aifc) * [asyncio](https://docs.python.org/3.9/whatsnew/3.7.html#whatsnew37-asyncio-deprecated) * [collections](https://docs.python.org/3.9/whatsnew/3.7.html#id3) * [dbm](https://docs.python.org/3.9/whatsnew/3.7.html#id4) * [enum](https://docs.python.org/3.9/whatsnew/3.7.html#id5) * [gettext](https://docs.python.org/3.9/whatsnew/3.7.html#gettext) * [importlib](https://docs.python.org/3.9/whatsnew/3.7.html#id6) * [locale](https://docs.python.org/3.9/whatsnew/3.7.html#id7) * [macpath](https://docs.python.org/3.9/whatsnew/3.7.html#macpath) * [threading](https://docs.python.org/3.9/whatsnew/3.7.html#threading) * [socket](https://docs.python.org/3.9/whatsnew/3.7.html#id8) * [ssl](https://docs.python.org/3.9/whatsnew/3.7.html#id9) * [sunau](https://docs.python.org/3.9/whatsnew/3.7.html#sunau) * [sys](https://docs.python.org/3.9/whatsnew/3.7.html#id10) * [wave](https://docs.python.org/3.9/whatsnew/3.7.html#wave) - [Deprecated functions and types of the C API](https://docs.python.org/3.9/whatsnew/3.7.html#deprecated-functions-and-types-of-the-c-api) - [Platform Support Removals](https://docs.python.org/3.9/whatsnew/3.7.html#platform-support-removals) - [API and Feature Removals](https://docs.python.org/3.9/whatsnew/3.7.html#api-and-feature-removals) - [Module Removals](https://docs.python.org/3.9/whatsnew/3.7.html#module-removals) - [Windows-only Changes](https://docs.python.org/3.9/whatsnew/3.7.html#windows-only-changes) - [Porting to Python 3.7](https://docs.python.org/3.9/whatsnew/3.7.html#porting-to-python-3-7) * [Changes in Python Behavior](https://docs.python.org/3.9/whatsnew/3.7.html#changes-in-python-behavior) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.7.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.7.html#changes-in-the-c-api) * [CPython bytecode changes](https://docs.python.org/3.9/whatsnew/3.7.html#cpython-bytecode-changes) * [Windows-only Changes](https://docs.python.org/3.9/whatsnew/3.7.html#id12) * [Other CPython implementation changes](https://docs.python.org/3.9/whatsnew/3.7.html#id13) - [Notable changes in Python 3.7.1](https://docs.python.org/3.9/whatsnew/3.7.html#notable-changes-in-python-3-7-1) - [Notable changes in Python 3.7.2](https://docs.python.org/3.9/whatsnew/3.7.html#notable-changes-in-python-3-7-2) - [Notable changes in Python 3.7.6](https://docs.python.org/3.9/whatsnew/3.7.html#notable-changes-in-python-3-7-6) - [Notable changes in Python 3.7.10](https://docs.python.org/3.9/whatsnew/3.7.html#notable-changes-in-python-3-7-10) + [What’s New In Python 3.6](https://docs.python.org/3.9/whatsnew/3.6.html) - [Summary – Release highlights](https://docs.python.org/3.9/whatsnew/3.6.html#summary-release-highlights) - [New Features](https://docs.python.org/3.9/whatsnew/3.6.html#new-features) * [PEP 498: Formatted string literals](https://docs.python.org/3.9/whatsnew/3.6.html#pep-498-formatted-string-literals) * [PEP 526: Syntax for variable annotations](https://docs.python.org/3.9/whatsnew/3.6.html#pep-526-syntax-for-variable-annotations) * [PEP 515: Underscores in Numeric Literals](https://docs.python.org/3.9/whatsnew/3.6.html#pep-515-underscores-in-numeric-literals) * [PEP 525: Asynchronous Generators](https://docs.python.org/3.9/whatsnew/3.6.html#pep-525-asynchronous-generators) * [PEP 530: Asynchronous Comprehensions](https://docs.python.org/3.9/whatsnew/3.6.html#pep-530-asynchronous-comprehensions) * [PEP 487: Simpler customization of class creation](https://docs.python.org/3.9/whatsnew/3.6.html#pep-487-simpler-customization-of-class-creation) * [PEP 487: Descriptor Protocol Enhancements](https://docs.python.org/3.9/whatsnew/3.6.html#pep-487-descriptor-protocol-enhancements) * [PEP 519: Adding a file system path protocol](https://docs.python.org/3.9/whatsnew/3.6.html#pep-519-adding-a-file-system-path-protocol) * [PEP 495: Local Time Disambiguation](https://docs.python.org/3.9/whatsnew/3.6.html#pep-495-local-time-disambiguation) * [PEP 529: Change Windows filesystem encoding to UTF-8](https://docs.python.org/3.9/whatsnew/3.6.html#pep-529-change-windows-filesystem-encoding-to-utf-8) * [PEP 528: Change Windows console encoding to UTF-8](https://docs.python.org/3.9/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8) * [PEP 520: Preserving Class Attribute Definition Order](https://docs.python.org/3.9/whatsnew/3.6.html#pep-520-preserving-class-attribute-definition-order) * [PEP 468: Preserving Keyword Argument Order](https://docs.python.org/3.9/whatsnew/3.6.html#pep-468-preserving-keyword-argument-order) * [New dict implementation](https://docs.python.org/3.9/whatsnew/3.6.html#new-dict-implementation) * [PEP 523: Adding a frame evaluation API to CPython](https://docs.python.org/3.9/whatsnew/3.6.html#pep-523-adding-a-frame-evaluation-api-to-cpython) * [PYTHONMALLOC environment variable](https://docs.python.org/3.9/whatsnew/3.6.html#pythonmalloc-environment-variable) * [DTrace and SystemTap probing support](https://docs.python.org/3.9/whatsnew/3.6.html#dtrace-and-systemtap-probing-support) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.6.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.6.html#new-modules) * [secrets](https://docs.python.org/3.9/whatsnew/3.6.html#secrets) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.6.html#improved-modules) * [array](https://docs.python.org/3.9/whatsnew/3.6.html#array) * [ast](https://docs.python.org/3.9/whatsnew/3.6.html#ast) * [asyncio](https://docs.python.org/3.9/whatsnew/3.6.html#asyncio) * [binascii](https://docs.python.org/3.9/whatsnew/3.6.html#binascii) * [cmath](https://docs.python.org/3.9/whatsnew/3.6.html#cmath) * [collections](https://docs.python.org/3.9/whatsnew/3.6.html#collections) * [concurrent.futures](https://docs.python.org/3.9/whatsnew/3.6.html#concurrent-futures) * [contextlib](https://docs.python.org/3.9/whatsnew/3.6.html#contextlib) * [datetime](https://docs.python.org/3.9/whatsnew/3.6.html#datetime) * [decimal](https://docs.python.org/3.9/whatsnew/3.6.html#decimal) * [distutils](https://docs.python.org/3.9/whatsnew/3.6.html#distutils) * [email](https://docs.python.org/3.9/whatsnew/3.6.html#email) * [encodings](https://docs.python.org/3.9/whatsnew/3.6.html#encodings) * [enum](https://docs.python.org/3.9/whatsnew/3.6.html#enum) * [faulthandler](https://docs.python.org/3.9/whatsnew/3.6.html#faulthandler) * [fileinput](https://docs.python.org/3.9/whatsnew/3.6.html#fileinput) * [hashlib](https://docs.python.org/3.9/whatsnew/3.6.html#hashlib) * [http.client](https://docs.python.org/3.9/whatsnew/3.6.html#http-client) * [idlelib and IDLE](https://docs.python.org/3.9/whatsnew/3.6.html#idlelib-and-idle) * [importlib](https://docs.python.org/3.9/whatsnew/3.6.html#importlib) * [inspect](https://docs.python.org/3.9/whatsnew/3.6.html#inspect) * [json](https://docs.python.org/3.9/whatsnew/3.6.html#json) * [logging](https://docs.python.org/3.9/whatsnew/3.6.html#logging) * [math](https://docs.python.org/3.9/whatsnew/3.6.html#math) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.6.html#multiprocessing) * [os](https://docs.python.org/3.9/whatsnew/3.6.html#os) * [pathlib](https://docs.python.org/3.9/whatsnew/3.6.html#pathlib) * [pdb](https://docs.python.org/3.9/whatsnew/3.6.html#pdb) * [pickle](https://docs.python.org/3.9/whatsnew/3.6.html#pickle) * [pickletools](https://docs.python.org/3.9/whatsnew/3.6.html#pickletools) * [pydoc](https://docs.python.org/3.9/whatsnew/3.6.html#pydoc) * [random](https://docs.python.org/3.9/whatsnew/3.6.html#random) * [re](https://docs.python.org/3.9/whatsnew/3.6.html#re) * [readline](https://docs.python.org/3.9/whatsnew/3.6.html#readline) * [rlcompleter](https://docs.python.org/3.9/whatsnew/3.6.html#rlcompleter) * [shlex](https://docs.python.org/3.9/whatsnew/3.6.html#shlex) * [site](https://docs.python.org/3.9/whatsnew/3.6.html#site) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.6.html#sqlite3) * [socket](https://docs.python.org/3.9/whatsnew/3.6.html#socket) * [socketserver](https://docs.python.org/3.9/whatsnew/3.6.html#socketserver) * [ssl](https://docs.python.org/3.9/whatsnew/3.6.html#ssl) * [statistics](https://docs.python.org/3.9/whatsnew/3.6.html#statistics) * [struct](https://docs.python.org/3.9/whatsnew/3.6.html#struct) * [subprocess](https://docs.python.org/3.9/whatsnew/3.6.html#subprocess) * [sys](https://docs.python.org/3.9/whatsnew/3.6.html#sys) * [telnetlib](https://docs.python.org/3.9/whatsnew/3.6.html#telnetlib) * [time](https://docs.python.org/3.9/whatsnew/3.6.html#time) * [timeit](https://docs.python.org/3.9/whatsnew/3.6.html#timeit) * [tkinter](https://docs.python.org/3.9/whatsnew/3.6.html#tkinter) * [traceback](https://docs.python.org/3.9/whatsnew/3.6.html#traceback) * [tracemalloc](https://docs.python.org/3.9/whatsnew/3.6.html#tracemalloc) * [typing](https://docs.python.org/3.9/whatsnew/3.6.html#typing) * [unicodedata](https://docs.python.org/3.9/whatsnew/3.6.html#unicodedata) * [unittest.mock](https://docs.python.org/3.9/whatsnew/3.6.html#unittest-mock) * [urllib.request](https://docs.python.org/3.9/whatsnew/3.6.html#urllib-request) * [urllib.robotparser](https://docs.python.org/3.9/whatsnew/3.6.html#urllib-robotparser) * [venv](https://docs.python.org/3.9/whatsnew/3.6.html#venv) * [warnings](https://docs.python.org/3.9/whatsnew/3.6.html#warnings) * [winreg](https://docs.python.org/3.9/whatsnew/3.6.html#winreg) * [winsound](https://docs.python.org/3.9/whatsnew/3.6.html#winsound) * [xmlrpc.client](https://docs.python.org/3.9/whatsnew/3.6.html#xmlrpc-client) * [zipfile](https://docs.python.org/3.9/whatsnew/3.6.html#zipfile) * [zlib](https://docs.python.org/3.9/whatsnew/3.6.html#zlib) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.6.html#optimizations) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.6.html#build-and-c-api-changes) - [Other Improvements](https://docs.python.org/3.9/whatsnew/3.6.html#other-improvements) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.6.html#deprecated) * [New Keywords](https://docs.python.org/3.9/whatsnew/3.6.html#new-keywords) * [Deprecated Python behavior](https://docs.python.org/3.9/whatsnew/3.6.html#deprecated-python-behavior) * [Deprecated Python modules, functions and methods](https://docs.python.org/3.9/whatsnew/3.6.html#deprecated-python-modules-functions-and-methods) + [asynchat](https://docs.python.org/3.9/whatsnew/3.6.html#asynchat) + [asyncore](https://docs.python.org/3.9/whatsnew/3.6.html#asyncore) + [dbm](https://docs.python.org/3.9/whatsnew/3.6.html#dbm) + [distutils](https://docs.python.org/3.9/whatsnew/3.6.html#id2) + [grp](https://docs.python.org/3.9/whatsnew/3.6.html#grp) + [importlib](https://docs.python.org/3.9/whatsnew/3.6.html#id3) + [os](https://docs.python.org/3.9/whatsnew/3.6.html#id4) + [re](https://docs.python.org/3.9/whatsnew/3.6.html#id5) + [ssl](https://docs.python.org/3.9/whatsnew/3.6.html#id6) + [tkinter](https://docs.python.org/3.9/whatsnew/3.6.html#id7) + [venv](https://docs.python.org/3.9/whatsnew/3.6.html#id8) * [Deprecated functions and types of the C API](https://docs.python.org/3.9/whatsnew/3.6.html#deprecated-functions-and-types-of-the-c-api) * [Deprecated Build Options](https://docs.python.org/3.9/whatsnew/3.6.html#deprecated-build-options) - [Removed](https://docs.python.org/3.9/whatsnew/3.6.html#removed) * [API and Feature Removals](https://docs.python.org/3.9/whatsnew/3.6.html#api-and-feature-removals) - [Porting to Python 3.6](https://docs.python.org/3.9/whatsnew/3.6.html#porting-to-python-3-6) * [Changes in ‘python’ Command Behavior](https://docs.python.org/3.9/whatsnew/3.6.html#changes-in-python-command-behavior) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.6.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.6.html#changes-in-the-c-api) * [CPython bytecode changes](https://docs.python.org/3.9/whatsnew/3.6.html#cpython-bytecode-changes) - [Notable changes in Python 3.6.2](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-2) * [New `make regen-all` build target](https://docs.python.org/3.9/whatsnew/3.6.html#new-make-regen-all-build-target) * [Removal of `make touch` build target](https://docs.python.org/3.9/whatsnew/3.6.html#removal-of-make-touch-build-target) - [Notable changes in Python 3.6.4](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-4) - [Notable changes in Python 3.6.5](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-5) - [Notable changes in Python 3.6.7](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-7) - [Notable changes in Python 3.6.10](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-10) - [Notable changes in Python 3.6.13](https://docs.python.org/3.9/whatsnew/3.6.html#notable-changes-in-python-3-6-13) + [What’s New In Python 3.5](https://docs.python.org/3.9/whatsnew/3.5.html) - [Summary – Release highlights](https://docs.python.org/3.9/whatsnew/3.5.html#summary-release-highlights) - [New Features](https://docs.python.org/3.9/whatsnew/3.5.html#new-features) * [PEP 492 - Coroutines with async and await syntax](https://docs.python.org/3.9/whatsnew/3.5.html#pep-492-coroutines-with-async-and-await-syntax) * [PEP 465 - A dedicated infix operator for matrix multiplication](https://docs.python.org/3.9/whatsnew/3.5.html#pep-465-a-dedicated-infix-operator-for-matrix-multiplication) * [PEP 448 - Additional Unpacking Generalizations](https://docs.python.org/3.9/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations) * [PEP 461 - percent formatting support for bytes and bytearray](https://docs.python.org/3.9/whatsnew/3.5.html#pep-461-percent-formatting-support-for-bytes-and-bytearray) * [PEP 484 - Type Hints](https://docs.python.org/3.9/whatsnew/3.5.html#pep-484-type-hints) * [PEP 471 - os.scandir() function – a better and faster directory iterator](https://docs.python.org/3.9/whatsnew/3.5.html#pep-471-os-scandir-function-a-better-and-faster-directory-iterator) * [PEP 475: Retry system calls failing with EINTR](https://docs.python.org/3.9/whatsnew/3.5.html#pep-475-retry-system-calls-failing-with-eintr) * [PEP 479: Change StopIteration handling inside generators](https://docs.python.org/3.9/whatsnew/3.5.html#pep-479-change-stopiteration-handling-inside-generators) * [PEP 485: A function for testing approximate equality](https://docs.python.org/3.9/whatsnew/3.5.html#pep-485-a-function-for-testing-approximate-equality) * [PEP 486: Make the Python Launcher aware of virtual environments](https://docs.python.org/3.9/whatsnew/3.5.html#pep-486-make-the-python-launcher-aware-of-virtual-environments) * [PEP 488: Elimination of PYO files](https://docs.python.org/3.9/whatsnew/3.5.html#pep-488-elimination-of-pyo-files) * [PEP 489: Multi-phase extension module initialization](https://docs.python.org/3.9/whatsnew/3.5.html#pep-489-multi-phase-extension-module-initialization) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.5.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.5.html#new-modules) * [typing](https://docs.python.org/3.9/whatsnew/3.5.html#typing) * [zipapp](https://docs.python.org/3.9/whatsnew/3.5.html#zipapp) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.5.html#improved-modules) * [argparse](https://docs.python.org/3.9/whatsnew/3.5.html#argparse) * [asyncio](https://docs.python.org/3.9/whatsnew/3.5.html#asyncio) * [bz2](https://docs.python.org/3.9/whatsnew/3.5.html#bz2) * [cgi](https://docs.python.org/3.9/whatsnew/3.5.html#cgi) * [cmath](https://docs.python.org/3.9/whatsnew/3.5.html#cmath) * [code](https://docs.python.org/3.9/whatsnew/3.5.html#code) * [collections](https://docs.python.org/3.9/whatsnew/3.5.html#collections) * [collections.abc](https://docs.python.org/3.9/whatsnew/3.5.html#collections-abc) * [compileall](https://docs.python.org/3.9/whatsnew/3.5.html#compileall) * [concurrent.futures](https://docs.python.org/3.9/whatsnew/3.5.html#concurrent-futures) * [configparser](https://docs.python.org/3.9/whatsnew/3.5.html#configparser) * [contextlib](https://docs.python.org/3.9/whatsnew/3.5.html#contextlib) * [csv](https://docs.python.org/3.9/whatsnew/3.5.html#csv) * [curses](https://docs.python.org/3.9/whatsnew/3.5.html#curses) * [dbm](https://docs.python.org/3.9/whatsnew/3.5.html#dbm) * [difflib](https://docs.python.org/3.9/whatsnew/3.5.html#difflib) * [distutils](https://docs.python.org/3.9/whatsnew/3.5.html#distutils) * [doctest](https://docs.python.org/3.9/whatsnew/3.5.html#doctest) * [email](https://docs.python.org/3.9/whatsnew/3.5.html#email) * [enum](https://docs.python.org/3.9/whatsnew/3.5.html#enum) * [faulthandler](https://docs.python.org/3.9/whatsnew/3.5.html#faulthandler) * [functools](https://docs.python.org/3.9/whatsnew/3.5.html#functools) * [glob](https://docs.python.org/3.9/whatsnew/3.5.html#glob) * [gzip](https://docs.python.org/3.9/whatsnew/3.5.html#gzip) * [heapq](https://docs.python.org/3.9/whatsnew/3.5.html#heapq) * [http](https://docs.python.org/3.9/whatsnew/3.5.html#http) * [http.client](https://docs.python.org/3.9/whatsnew/3.5.html#http-client) * [idlelib and IDLE](https://docs.python.org/3.9/whatsnew/3.5.html#idlelib-and-idle) * [imaplib](https://docs.python.org/3.9/whatsnew/3.5.html#imaplib) * [imghdr](https://docs.python.org/3.9/whatsnew/3.5.html#imghdr) * [importlib](https://docs.python.org/3.9/whatsnew/3.5.html#importlib) * [inspect](https://docs.python.org/3.9/whatsnew/3.5.html#inspect) * [io](https://docs.python.org/3.9/whatsnew/3.5.html#io) * [ipaddress](https://docs.python.org/3.9/whatsnew/3.5.html#ipaddress) * [json](https://docs.python.org/3.9/whatsnew/3.5.html#json) * [linecache](https://docs.python.org/3.9/whatsnew/3.5.html#linecache) * [locale](https://docs.python.org/3.9/whatsnew/3.5.html#locale) * [logging](https://docs.python.org/3.9/whatsnew/3.5.html#logging) * [lzma](https://docs.python.org/3.9/whatsnew/3.5.html#lzma) * [math](https://docs.python.org/3.9/whatsnew/3.5.html#math) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.5.html#multiprocessing) * [operator](https://docs.python.org/3.9/whatsnew/3.5.html#operator) * [os](https://docs.python.org/3.9/whatsnew/3.5.html#os) * [pathlib](https://docs.python.org/3.9/whatsnew/3.5.html#pathlib) * [pickle](https://docs.python.org/3.9/whatsnew/3.5.html#pickle) * [poplib](https://docs.python.org/3.9/whatsnew/3.5.html#poplib) * [re](https://docs.python.org/3.9/whatsnew/3.5.html#re) * [readline](https://docs.python.org/3.9/whatsnew/3.5.html#readline) * [selectors](https://docs.python.org/3.9/whatsnew/3.5.html#selectors) * [shutil](https://docs.python.org/3.9/whatsnew/3.5.html#shutil) * [signal](https://docs.python.org/3.9/whatsnew/3.5.html#signal) * [smtpd](https://docs.python.org/3.9/whatsnew/3.5.html#smtpd) * [smtplib](https://docs.python.org/3.9/whatsnew/3.5.html#smtplib) * [sndhdr](https://docs.python.org/3.9/whatsnew/3.5.html#sndhdr) * [socket](https://docs.python.org/3.9/whatsnew/3.5.html#socket) * [ssl](https://docs.python.org/3.9/whatsnew/3.5.html#ssl) + [Memory BIO Support](https://docs.python.org/3.9/whatsnew/3.5.html#memory-bio-support) + [Application-Layer Protocol Negotiation Support](https://docs.python.org/3.9/whatsnew/3.5.html#application-layer-protocol-negotiation-support) + [Other Changes](https://docs.python.org/3.9/whatsnew/3.5.html#other-changes) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.5.html#sqlite3) * [subprocess](https://docs.python.org/3.9/whatsnew/3.5.html#subprocess) * [sys](https://docs.python.org/3.9/whatsnew/3.5.html#sys) * [sysconfig](https://docs.python.org/3.9/whatsnew/3.5.html#sysconfig) * [tarfile](https://docs.python.org/3.9/whatsnew/3.5.html#tarfile) * [threading](https://docs.python.org/3.9/whatsnew/3.5.html#threading) * [time](https://docs.python.org/3.9/whatsnew/3.5.html#time) * [timeit](https://docs.python.org/3.9/whatsnew/3.5.html#timeit) * [tkinter](https://docs.python.org/3.9/whatsnew/3.5.html#tkinter) * [traceback](https://docs.python.org/3.9/whatsnew/3.5.html#traceback) * [types](https://docs.python.org/3.9/whatsnew/3.5.html#types) * [unicodedata](https://docs.python.org/3.9/whatsnew/3.5.html#unicodedata) * [unittest](https://docs.python.org/3.9/whatsnew/3.5.html#unittest) * [unittest.mock](https://docs.python.org/3.9/whatsnew/3.5.html#unittest-mock) * [urllib](https://docs.python.org/3.9/whatsnew/3.5.html#urllib) * [wsgiref](https://docs.python.org/3.9/whatsnew/3.5.html#wsgiref) * [xmlrpc](https://docs.python.org/3.9/whatsnew/3.5.html#xmlrpc) * [xml.sax](https://docs.python.org/3.9/whatsnew/3.5.html#xml-sax) * [zipfile](https://docs.python.org/3.9/whatsnew/3.5.html#zipfile) - [Other module-level changes](https://docs.python.org/3.9/whatsnew/3.5.html#other-module-level-changes) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.5.html#optimizations) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.5.html#build-and-c-api-changes) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.5.html#deprecated) * [New Keywords](https://docs.python.org/3.9/whatsnew/3.5.html#new-keywords) * [Deprecated Python Behavior](https://docs.python.org/3.9/whatsnew/3.5.html#deprecated-python-behavior) * [Unsupported Operating Systems](https://docs.python.org/3.9/whatsnew/3.5.html#unsupported-operating-systems) * [Deprecated Python modules, functions and methods](https://docs.python.org/3.9/whatsnew/3.5.html#deprecated-python-modules-functions-and-methods) - [Removed](https://docs.python.org/3.9/whatsnew/3.5.html#removed) * [API and Feature Removals](https://docs.python.org/3.9/whatsnew/3.5.html#api-and-feature-removals) - [Porting to Python 3.5](https://docs.python.org/3.9/whatsnew/3.5.html#porting-to-python-3-5) * [Changes in Python behavior](https://docs.python.org/3.9/whatsnew/3.5.html#changes-in-python-behavior) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.5.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.5.html#changes-in-the-c-api) - [Notable changes in Python 3.5.4](https://docs.python.org/3.9/whatsnew/3.5.html#notable-changes-in-python-3-5-4) * [New `make regen-all` build target](https://docs.python.org/3.9/whatsnew/3.5.html#new-make-regen-all-build-target) * [Removal of `make touch` build target](https://docs.python.org/3.9/whatsnew/3.5.html#removal-of-make-touch-build-target) + [What’s New In Python 3.4](https://docs.python.org/3.9/whatsnew/3.4.html) - [Summary – Release Highlights](https://docs.python.org/3.9/whatsnew/3.4.html#summary-release-highlights) - [New Features](https://docs.python.org/3.9/whatsnew/3.4.html#new-features) * [PEP 453: Explicit Bootstrapping of PIP in Python Installations](https://docs.python.org/3.9/whatsnew/3.4.html#pep-453-explicit-bootstrapping-of-pip-in-python-installations) + [Bootstrapping pip By Default](https://docs.python.org/3.9/whatsnew/3.4.html#bootstrapping-pip-by-default) + [Documentation Changes](https://docs.python.org/3.9/whatsnew/3.4.html#documentation-changes) * [PEP 446: Newly Created File Descriptors Are Non-Inheritable](https://docs.python.org/3.9/whatsnew/3.4.html#pep-446-newly-created-file-descriptors-are-non-inheritable) * [Improvements to Codec Handling](https://docs.python.org/3.9/whatsnew/3.4.html#improvements-to-codec-handling) * [PEP 451: A ModuleSpec Type for the Import System](https://docs.python.org/3.9/whatsnew/3.4.html#pep-451-a-modulespec-type-for-the-import-system) * [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.4.html#other-language-changes) - [New Modules](https://docs.python.org/3.9/whatsnew/3.4.html#new-modules) * [asyncio](https://docs.python.org/3.9/whatsnew/3.4.html#asyncio) * [ensurepip](https://docs.python.org/3.9/whatsnew/3.4.html#ensurepip) * [enum](https://docs.python.org/3.9/whatsnew/3.4.html#enum) * [pathlib](https://docs.python.org/3.9/whatsnew/3.4.html#pathlib) * [selectors](https://docs.python.org/3.9/whatsnew/3.4.html#selectors) * [statistics](https://docs.python.org/3.9/whatsnew/3.4.html#statistics) * [tracemalloc](https://docs.python.org/3.9/whatsnew/3.4.html#tracemalloc) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.4.html#improved-modules) * [abc](https://docs.python.org/3.9/whatsnew/3.4.html#abc) * [aifc](https://docs.python.org/3.9/whatsnew/3.4.html#aifc) * [argparse](https://docs.python.org/3.9/whatsnew/3.4.html#argparse) * [audioop](https://docs.python.org/3.9/whatsnew/3.4.html#audioop) * [base64](https://docs.python.org/3.9/whatsnew/3.4.html#base64) * [collections](https://docs.python.org/3.9/whatsnew/3.4.html#collections) * [colorsys](https://docs.python.org/3.9/whatsnew/3.4.html#colorsys) * [contextlib](https://docs.python.org/3.9/whatsnew/3.4.html#contextlib) * [dbm](https://docs.python.org/3.9/whatsnew/3.4.html#dbm) * [dis](https://docs.python.org/3.9/whatsnew/3.4.html#dis) * [doctest](https://docs.python.org/3.9/whatsnew/3.4.html#doctest) * [email](https://docs.python.org/3.9/whatsnew/3.4.html#email) * [filecmp](https://docs.python.org/3.9/whatsnew/3.4.html#filecmp) * [functools](https://docs.python.org/3.9/whatsnew/3.4.html#functools) * [gc](https://docs.python.org/3.9/whatsnew/3.4.html#gc) * [glob](https://docs.python.org/3.9/whatsnew/3.4.html#glob) * [hashlib](https://docs.python.org/3.9/whatsnew/3.4.html#hashlib) * [hmac](https://docs.python.org/3.9/whatsnew/3.4.html#hmac) * [html](https://docs.python.org/3.9/whatsnew/3.4.html#html) * [http](https://docs.python.org/3.9/whatsnew/3.4.html#http) * [idlelib and IDLE](https://docs.python.org/3.9/whatsnew/3.4.html#idlelib-and-idle) * [importlib](https://docs.python.org/3.9/whatsnew/3.4.html#importlib) * [inspect](https://docs.python.org/3.9/whatsnew/3.4.html#inspect) * [ipaddress](https://docs.python.org/3.9/whatsnew/3.4.html#ipaddress) * [logging](https://docs.python.org/3.9/whatsnew/3.4.html#logging) * [marshal](https://docs.python.org/3.9/whatsnew/3.4.html#marshal) * [mmap](https://docs.python.org/3.9/whatsnew/3.4.html#mmap) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.4.html#multiprocessing) * [operator](https://docs.python.org/3.9/whatsnew/3.4.html#operator) * [os](https://docs.python.org/3.9/whatsnew/3.4.html#os) * [pdb](https://docs.python.org/3.9/whatsnew/3.4.html#pdb) * [pickle](https://docs.python.org/3.9/whatsnew/3.4.html#pickle) * [plistlib](https://docs.python.org/3.9/whatsnew/3.4.html#plistlib) * [poplib](https://docs.python.org/3.9/whatsnew/3.4.html#poplib) * [pprint](https://docs.python.org/3.9/whatsnew/3.4.html#pprint) * [pty](https://docs.python.org/3.9/whatsnew/3.4.html#pty) * [pydoc](https://docs.python.org/3.9/whatsnew/3.4.html#pydoc) * [re](https://docs.python.org/3.9/whatsnew/3.4.html#re) * [resource](https://docs.python.org/3.9/whatsnew/3.4.html#resource) * [select](https://docs.python.org/3.9/whatsnew/3.4.html#select) * [shelve](https://docs.python.org/3.9/whatsnew/3.4.html#shelve) * [shutil](https://docs.python.org/3.9/whatsnew/3.4.html#shutil) * [smtpd](https://docs.python.org/3.9/whatsnew/3.4.html#smtpd) * [smtplib](https://docs.python.org/3.9/whatsnew/3.4.html#smtplib) * [socket](https://docs.python.org/3.9/whatsnew/3.4.html#socket) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.4.html#sqlite3) * [ssl](https://docs.python.org/3.9/whatsnew/3.4.html#ssl) * [stat](https://docs.python.org/3.9/whatsnew/3.4.html#stat) * [struct](https://docs.python.org/3.9/whatsnew/3.4.html#struct) * [subprocess](https://docs.python.org/3.9/whatsnew/3.4.html#subprocess) * [sunau](https://docs.python.org/3.9/whatsnew/3.4.html#sunau) * [sys](https://docs.python.org/3.9/whatsnew/3.4.html#sys) * [tarfile](https://docs.python.org/3.9/whatsnew/3.4.html#tarfile) * [textwrap](https://docs.python.org/3.9/whatsnew/3.4.html#textwrap) * [threading](https://docs.python.org/3.9/whatsnew/3.4.html#threading) * [traceback](https://docs.python.org/3.9/whatsnew/3.4.html#traceback) * [types](https://docs.python.org/3.9/whatsnew/3.4.html#types) * [urllib](https://docs.python.org/3.9/whatsnew/3.4.html#urllib) * [unittest](https://docs.python.org/3.9/whatsnew/3.4.html#unittest) * [venv](https://docs.python.org/3.9/whatsnew/3.4.html#venv) * [wave](https://docs.python.org/3.9/whatsnew/3.4.html#wave) * [weakref](https://docs.python.org/3.9/whatsnew/3.4.html#weakref) * [xml.etree](https://docs.python.org/3.9/whatsnew/3.4.html#xml-etree) * [zipfile](https://docs.python.org/3.9/whatsnew/3.4.html#zipfile) - [CPython Implementation Changes](https://docs.python.org/3.9/whatsnew/3.4.html#cpython-implementation-changes) * [PEP 445: Customization of CPython Memory Allocators](https://docs.python.org/3.9/whatsnew/3.4.html#pep-445-customization-of-cpython-memory-allocators) * [PEP 442: Safe Object Finalization](https://docs.python.org/3.9/whatsnew/3.4.html#pep-442-safe-object-finalization) * [PEP 456: Secure and Interchangeable Hash Algorithm](https://docs.python.org/3.9/whatsnew/3.4.html#pep-456-secure-and-interchangeable-hash-algorithm) * [PEP 436: Argument Clinic](https://docs.python.org/3.9/whatsnew/3.4.html#pep-436-argument-clinic) * [Other Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.4.html#other-build-and-c-api-changes) * [Other Improvements](https://docs.python.org/3.9/whatsnew/3.4.html#other-improvements) * [Significant Optimizations](https://docs.python.org/3.9/whatsnew/3.4.html#significant-optimizations) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.4.html#deprecated) * [Deprecations in the Python API](https://docs.python.org/3.9/whatsnew/3.4.html#deprecations-in-the-python-api) * [Deprecated Features](https://docs.python.org/3.9/whatsnew/3.4.html#deprecated-features) - [Removed](https://docs.python.org/3.9/whatsnew/3.4.html#removed) * [Operating Systems No Longer Supported](https://docs.python.org/3.9/whatsnew/3.4.html#operating-systems-no-longer-supported) * [API and Feature Removals](https://docs.python.org/3.9/whatsnew/3.4.html#api-and-feature-removals) * [Code Cleanups](https://docs.python.org/3.9/whatsnew/3.4.html#code-cleanups) - [Porting to Python 3.4](https://docs.python.org/3.9/whatsnew/3.4.html#porting-to-python-3-4) * [Changes in ‘python’ Command Behavior](https://docs.python.org/3.9/whatsnew/3.4.html#changes-in-python-command-behavior) * [Changes in the Python API](https://docs.python.org/3.9/whatsnew/3.4.html#changes-in-the-python-api) * [Changes in the C API](https://docs.python.org/3.9/whatsnew/3.4.html#changes-in-the-c-api) - [Changed in 3.4.3](https://docs.python.org/3.9/whatsnew/3.4.html#changed-in-3-4-3) * [PEP 476: Enabling certificate verification by default for stdlib http clients](https://docs.python.org/3.9/whatsnew/3.4.html#pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients) + [What’s New In Python 3.3](https://docs.python.org/3.9/whatsnew/3.3.html) - [Summary – Release highlights](https://docs.python.org/3.9/whatsnew/3.3.html#summary-release-highlights) - [PEP 405: Virtual Environments](https://docs.python.org/3.9/whatsnew/3.3.html#pep-405-virtual-environments) - [PEP 420: Implicit Namespace Packages](https://docs.python.org/3.9/whatsnew/3.3.html#pep-420-implicit-namespace-packages) - [PEP 3118: New memoryview implementation and buffer protocol documentation](https://docs.python.org/3.9/whatsnew/3.3.html#pep-3118-new-memoryview-implementation-and-buffer-protocol-documentation) * [Features](https://docs.python.org/3.9/whatsnew/3.3.html#features) * [API changes](https://docs.python.org/3.9/whatsnew/3.3.html#api-changes) - [PEP 393: Flexible String Representation](https://docs.python.org/3.9/whatsnew/3.3.html#pep-393-flexible-string-representation) * [Functionality](https://docs.python.org/3.9/whatsnew/3.3.html#functionality) * [Performance and resource usage](https://docs.python.org/3.9/whatsnew/3.3.html#performance-and-resource-usage) - [PEP 397: Python Launcher for Windows](https://docs.python.org/3.9/whatsnew/3.3.html#pep-397-python-launcher-for-windows) - [PEP 3151: Reworking the OS and IO exception hierarchy](https://docs.python.org/3.9/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy) - [PEP 380: Syntax for Delegating to a Subgenerator](https://docs.python.org/3.9/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator) - [PEP 409: Suppressing exception context](https://docs.python.org/3.9/whatsnew/3.3.html#pep-409-suppressing-exception-context) - [PEP 414: Explicit Unicode literals](https://docs.python.org/3.9/whatsnew/3.3.html#pep-414-explicit-unicode-literals) - [PEP 3155: Qualified name for classes and functions](https://docs.python.org/3.9/whatsnew/3.3.html#pep-3155-qualified-name-for-classes-and-functions) - [PEP 412: Key-Sharing Dictionary](https://docs.python.org/3.9/whatsnew/3.3.html#pep-412-key-sharing-dictionary) - [PEP 362: Function Signature Object](https://docs.python.org/3.9/whatsnew/3.3.html#pep-362-function-signature-object) - [PEP 421: Adding sys.implementation](https://docs.python.org/3.9/whatsnew/3.3.html#pep-421-adding-sys-implementation) * [SimpleNamespace](https://docs.python.org/3.9/whatsnew/3.3.html#simplenamespace) - [Using importlib as the Implementation of Import](https://docs.python.org/3.9/whatsnew/3.3.html#using-importlib-as-the-implementation-of-import) * [New APIs](https://docs.python.org/3.9/whatsnew/3.3.html#new-apis) * [Visible Changes](https://docs.python.org/3.9/whatsnew/3.3.html#visible-changes) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.3.html#other-language-changes) - [A Finer-Grained Import Lock](https://docs.python.org/3.9/whatsnew/3.3.html#a-finer-grained-import-lock) - [Builtin functions and types](https://docs.python.org/3.9/whatsnew/3.3.html#builtin-functions-and-types) - [New Modules](https://docs.python.org/3.9/whatsnew/3.3.html#new-modules) * [faulthandler](https://docs.python.org/3.9/whatsnew/3.3.html#faulthandler) * [ipaddress](https://docs.python.org/3.9/whatsnew/3.3.html#ipaddress) * [lzma](https://docs.python.org/3.9/whatsnew/3.3.html#lzma) - [Improved Modules](https://docs.python.org/3.9/whatsnew/3.3.html#improved-modules) * [abc](https://docs.python.org/3.9/whatsnew/3.3.html#abc) * [array](https://docs.python.org/3.9/whatsnew/3.3.html#array) * [base64](https://docs.python.org/3.9/whatsnew/3.3.html#base64) * [binascii](https://docs.python.org/3.9/whatsnew/3.3.html#binascii) * [bz2](https://docs.python.org/3.9/whatsnew/3.3.html#bz2) * [codecs](https://docs.python.org/3.9/whatsnew/3.3.html#codecs) * [collections](https://docs.python.org/3.9/whatsnew/3.3.html#collections) * [contextlib](https://docs.python.org/3.9/whatsnew/3.3.html#contextlib) * [crypt](https://docs.python.org/3.9/whatsnew/3.3.html#crypt) * [curses](https://docs.python.org/3.9/whatsnew/3.3.html#curses) * [datetime](https://docs.python.org/3.9/whatsnew/3.3.html#datetime) * [decimal](https://docs.python.org/3.9/whatsnew/3.3.html#decimal) + [Features](https://docs.python.org/3.9/whatsnew/3.3.html#id1) + [API changes](https://docs.python.org/3.9/whatsnew/3.3.html#id2) * [email](https://docs.python.org/3.9/whatsnew/3.3.html#email) + [Policy Framework](https://docs.python.org/3.9/whatsnew/3.3.html#policy-framework) + [Provisional Policy with New Header API](https://docs.python.org/3.9/whatsnew/3.3.html#provisional-policy-with-new-header-api) + [Other API Changes](https://docs.python.org/3.9/whatsnew/3.3.html#other-api-changes) * [ftplib](https://docs.python.org/3.9/whatsnew/3.3.html#ftplib) * [functools](https://docs.python.org/3.9/whatsnew/3.3.html#functools) * [gc](https://docs.python.org/3.9/whatsnew/3.3.html#gc) * [hmac](https://docs.python.org/3.9/whatsnew/3.3.html#hmac) * [http](https://docs.python.org/3.9/whatsnew/3.3.html#http) * [html](https://docs.python.org/3.9/whatsnew/3.3.html#html) * [imaplib](https://docs.python.org/3.9/whatsnew/3.3.html#imaplib) * [inspect](https://docs.python.org/3.9/whatsnew/3.3.html#inspect) * [io](https://docs.python.org/3.9/whatsnew/3.3.html#io) * [itertools](https://docs.python.org/3.9/whatsnew/3.3.html#itertools) * [logging](https://docs.python.org/3.9/whatsnew/3.3.html#logging) * [math](https://docs.python.org/3.9/whatsnew/3.3.html#math) * [mmap](https://docs.python.org/3.9/whatsnew/3.3.html#mmap) * [multiprocessing](https://docs.python.org/3.9/whatsnew/3.3.html#multiprocessing) * [nntplib](https://docs.python.org/3.9/whatsnew/3.3.html#nntplib) * [os](https://docs.python.org/3.9/whatsnew/3.3.html#os) * [pdb](https://docs.python.org/3.9/whatsnew/3.3.html#pdb) * [pickle](https://docs.python.org/3.9/whatsnew/3.3.html#pickle) * [pydoc](https://docs.python.org/3.9/whatsnew/3.3.html#pydoc) * [re](https://docs.python.org/3.9/whatsnew/3.3.html#re) * [sched](https://docs.python.org/3.9/whatsnew/3.3.html#sched) * [select](https://docs.python.org/3.9/whatsnew/3.3.html#select) * [shlex](https://docs.python.org/3.9/whatsnew/3.3.html#shlex) * [shutil](https://docs.python.org/3.9/whatsnew/3.3.html#shutil) * [signal](https://docs.python.org/3.9/whatsnew/3.3.html#signal) * [smtpd](https://docs.python.org/3.9/whatsnew/3.3.html#smtpd) * [smtplib](https://docs.python.org/3.9/whatsnew/3.3.html#smtplib) * [socket](https://docs.python.org/3.9/whatsnew/3.3.html#socket) * [socketserver](https://docs.python.org/3.9/whatsnew/3.3.html#socketserver) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.3.html#sqlite3) * [ssl](https://docs.python.org/3.9/whatsnew/3.3.html#ssl) * [stat](https://docs.python.org/3.9/whatsnew/3.3.html#stat) * [struct](https://docs.python.org/3.9/whatsnew/3.3.html#struct) * [subprocess](https://docs.python.org/3.9/whatsnew/3.3.html#subprocess) * [sys](https://docs.python.org/3.9/whatsnew/3.3.html#sys) * [tarfile](https://docs.python.org/3.9/whatsnew/3.3.html#tarfile) * [tempfile](https://docs.python.org/3.9/whatsnew/3.3.html#tempfile) * [textwrap](https://docs.python.org/3.9/whatsnew/3.3.html#textwrap) * [threading](https://docs.python.org/3.9/whatsnew/3.3.html#threading) * [time](https://docs.python.org/3.9/whatsnew/3.3.html#time) * [types](https://docs.python.org/3.9/whatsnew/3.3.html#types) * [unittest](https://docs.python.org/3.9/whatsnew/3.3.html#unittest) * [urllib](https://docs.python.org/3.9/whatsnew/3.3.html#urllib) * [webbrowser](https://docs.python.org/3.9/whatsnew/3.3.html#webbrowser) * [xml.etree.ElementTree](https://docs.python.org/3.9/whatsnew/3.3.html#xml-etree-elementtree) * [zlib](https://docs.python.org/3.9/whatsnew/3.3.html#zlib) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.3.html#optimizations) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.3.html#build-and-c-api-changes) - [Deprecated](https://docs.python.org/3.9/whatsnew/3.3.html#deprecated) * [Unsupported Operating Systems](https://docs.python.org/3.9/whatsnew/3.3.html#unsupported-operating-systems) * [Deprecated Python modules, functions and methods](https://docs.python.org/3.9/whatsnew/3.3.html#deprecated-python-modules-functions-and-methods) * [Deprecated functions and types of the C API](https://docs.python.org/3.9/whatsnew/3.3.html#deprecated-functions-and-types-of-the-c-api) * [Deprecated features](https://docs.python.org/3.9/whatsnew/3.3.html#deprecated-features) - [Porting to Python 3.3](https://docs.python.org/3.9/whatsnew/3.3.html#porting-to-python-3-3) * [Porting Python code](https://docs.python.org/3.9/whatsnew/3.3.html#porting-python-code) * [Porting C code](https://docs.python.org/3.9/whatsnew/3.3.html#porting-c-code) * [Building C extensions](https://docs.python.org/3.9/whatsnew/3.3.html#building-c-extensions) * [Command Line Switch Changes](https://docs.python.org/3.9/whatsnew/3.3.html#command-line-switch-changes) + [What’s New In Python 3.2](https://docs.python.org/3.9/whatsnew/3.2.html) - [PEP 384: Defining a Stable ABI](https://docs.python.org/3.9/whatsnew/3.2.html#pep-384-defining-a-stable-abi) - [PEP 389: Argparse Command Line Parsing Module](https://docs.python.org/3.9/whatsnew/3.2.html#pep-389-argparse-command-line-parsing-module) - [PEP 391: Dictionary Based Configuration for Logging](https://docs.python.org/3.9/whatsnew/3.2.html#pep-391-dictionary-based-configuration-for-logging) - [PEP 3148: The `concurrent.futures` module](https://docs.python.org/3.9/whatsnew/3.2.html#pep-3148-the-concurrent-futures-module) - [PEP 3147: PYC Repository Directories](https://docs.python.org/3.9/whatsnew/3.2.html#pep-3147-pyc-repository-directories) - [PEP 3149: ABI Version Tagged .so Files](https://docs.python.org/3.9/whatsnew/3.2.html#pep-3149-abi-version-tagged-so-files) - [PEP 3333: Python Web Server Gateway Interface v1.0.1](https://docs.python.org/3.9/whatsnew/3.2.html#pep-3333-python-web-server-gateway-interface-v1-0-1) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.2.html#other-language-changes) - [New, Improved, and Deprecated Modules](https://docs.python.org/3.9/whatsnew/3.2.html#new-improved-and-deprecated-modules) * [email](https://docs.python.org/3.9/whatsnew/3.2.html#email) * [elementtree](https://docs.python.org/3.9/whatsnew/3.2.html#elementtree) * [functools](https://docs.python.org/3.9/whatsnew/3.2.html#functools) * [itertools](https://docs.python.org/3.9/whatsnew/3.2.html#itertools) * [collections](https://docs.python.org/3.9/whatsnew/3.2.html#collections) * [threading](https://docs.python.org/3.9/whatsnew/3.2.html#threading) * [datetime and time](https://docs.python.org/3.9/whatsnew/3.2.html#datetime-and-time) * [math](https://docs.python.org/3.9/whatsnew/3.2.html#math) * [abc](https://docs.python.org/3.9/whatsnew/3.2.html#abc) * [io](https://docs.python.org/3.9/whatsnew/3.2.html#io) * [reprlib](https://docs.python.org/3.9/whatsnew/3.2.html#reprlib) * [logging](https://docs.python.org/3.9/whatsnew/3.2.html#logging) * [csv](https://docs.python.org/3.9/whatsnew/3.2.html#csv) * [contextlib](https://docs.python.org/3.9/whatsnew/3.2.html#contextlib) * [decimal and fractions](https://docs.python.org/3.9/whatsnew/3.2.html#decimal-and-fractions) * [ftp](https://docs.python.org/3.9/whatsnew/3.2.html#ftp) * [popen](https://docs.python.org/3.9/whatsnew/3.2.html#popen) * [select](https://docs.python.org/3.9/whatsnew/3.2.html#select) * [gzip and zipfile](https://docs.python.org/3.9/whatsnew/3.2.html#gzip-and-zipfile) * [tarfile](https://docs.python.org/3.9/whatsnew/3.2.html#tarfile) * [hashlib](https://docs.python.org/3.9/whatsnew/3.2.html#hashlib) * [ast](https://docs.python.org/3.9/whatsnew/3.2.html#ast) * [os](https://docs.python.org/3.9/whatsnew/3.2.html#os) * [shutil](https://docs.python.org/3.9/whatsnew/3.2.html#shutil) * [sqlite3](https://docs.python.org/3.9/whatsnew/3.2.html#sqlite3) * [html](https://docs.python.org/3.9/whatsnew/3.2.html#html) * [socket](https://docs.python.org/3.9/whatsnew/3.2.html#socket) * [ssl](https://docs.python.org/3.9/whatsnew/3.2.html#ssl) * [nntp](https://docs.python.org/3.9/whatsnew/3.2.html#nntp) * [certificates](https://docs.python.org/3.9/whatsnew/3.2.html#certificates) * [imaplib](https://docs.python.org/3.9/whatsnew/3.2.html#imaplib) * [http.client](https://docs.python.org/3.9/whatsnew/3.2.html#http-client) * [unittest](https://docs.python.org/3.9/whatsnew/3.2.html#unittest) * [random](https://docs.python.org/3.9/whatsnew/3.2.html#random) * [poplib](https://docs.python.org/3.9/whatsnew/3.2.html#poplib) * [asyncore](https://docs.python.org/3.9/whatsnew/3.2.html#asyncore) * [tempfile](https://docs.python.org/3.9/whatsnew/3.2.html#tempfile) * [inspect](https://docs.python.org/3.9/whatsnew/3.2.html#inspect) * [pydoc](https://docs.python.org/3.9/whatsnew/3.2.html#pydoc) * [dis](https://docs.python.org/3.9/whatsnew/3.2.html#dis) * [dbm](https://docs.python.org/3.9/whatsnew/3.2.html#dbm) * [ctypes](https://docs.python.org/3.9/whatsnew/3.2.html#ctypes) * [site](https://docs.python.org/3.9/whatsnew/3.2.html#site) * [sysconfig](https://docs.python.org/3.9/whatsnew/3.2.html#sysconfig) * [pdb](https://docs.python.org/3.9/whatsnew/3.2.html#pdb) * [configparser](https://docs.python.org/3.9/whatsnew/3.2.html#configparser) * [urllib.parse](https://docs.python.org/3.9/whatsnew/3.2.html#urllib-parse) * [mailbox](https://docs.python.org/3.9/whatsnew/3.2.html#mailbox) * [turtledemo](https://docs.python.org/3.9/whatsnew/3.2.html#turtledemo) - [Multi-threading](https://docs.python.org/3.9/whatsnew/3.2.html#multi-threading) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.2.html#optimizations) - [Unicode](https://docs.python.org/3.9/whatsnew/3.2.html#unicode) - [Codecs](https://docs.python.org/3.9/whatsnew/3.2.html#codecs) - [Documentation](https://docs.python.org/3.9/whatsnew/3.2.html#documentation) - [IDLE](https://docs.python.org/3.9/whatsnew/3.2.html#idle) - [Code Repository](https://docs.python.org/3.9/whatsnew/3.2.html#code-repository) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.2.html#build-and-c-api-changes) - [Porting to Python 3.2](https://docs.python.org/3.9/whatsnew/3.2.html#porting-to-python-3-2) + [What’s New In Python 3.1](https://docs.python.org/3.9/whatsnew/3.1.html) - [PEP 372: Ordered Dictionaries](https://docs.python.org/3.9/whatsnew/3.1.html#pep-372-ordered-dictionaries) - [PEP 378: Format Specifier for Thousands Separator](https://docs.python.org/3.9/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/3.1.html#other-language-changes) - [New, Improved, and Deprecated Modules](https://docs.python.org/3.9/whatsnew/3.1.html#new-improved-and-deprecated-modules) - [Optimizations](https://docs.python.org/3.9/whatsnew/3.1.html#optimizations) - [IDLE](https://docs.python.org/3.9/whatsnew/3.1.html#idle) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.1.html#build-and-c-api-changes) - [Porting to Python 3.1](https://docs.python.org/3.9/whatsnew/3.1.html#porting-to-python-3-1) + [What’s New In Python 3.0](https://docs.python.org/3.9/whatsnew/3.0.html) - [Common Stumbling Blocks](https://docs.python.org/3.9/whatsnew/3.0.html#common-stumbling-blocks) * [Print Is A Function](https://docs.python.org/3.9/whatsnew/3.0.html#print-is-a-function) * [Views And Iterators Instead Of Lists](https://docs.python.org/3.9/whatsnew/3.0.html#views-and-iterators-instead-of-lists) * [Ordering Comparisons](https://docs.python.org/3.9/whatsnew/3.0.html#ordering-comparisons) * [Integers](https://docs.python.org/3.9/whatsnew/3.0.html#integers) * [Text Vs. Data Instead Of Unicode Vs. 8-bit](https://docs.python.org/3.9/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) - [Overview Of Syntax Changes](https://docs.python.org/3.9/whatsnew/3.0.html#overview-of-syntax-changes) * [New Syntax](https://docs.python.org/3.9/whatsnew/3.0.html#new-syntax) * [Changed Syntax](https://docs.python.org/3.9/whatsnew/3.0.html#changed-syntax) * [Removed Syntax](https://docs.python.org/3.9/whatsnew/3.0.html#removed-syntax) - [Changes Already Present In Python 2.6](https://docs.python.org/3.9/whatsnew/3.0.html#changes-already-present-in-python-2-6) - [Library Changes](https://docs.python.org/3.9/whatsnew/3.0.html#library-changes) - [**PEP 3101**: A New Approach To String Formatting](https://docs.python.org/3.9/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting) - [Changes To Exceptions](https://docs.python.org/3.9/whatsnew/3.0.html#changes-to-exceptions) - [Miscellaneous Other Changes](https://docs.python.org/3.9/whatsnew/3.0.html#miscellaneous-other-changes) * [Operators And Special Methods](https://docs.python.org/3.9/whatsnew/3.0.html#operators-and-special-methods) * [Builtins](https://docs.python.org/3.9/whatsnew/3.0.html#builtins) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/3.0.html#build-and-c-api-changes) - [Performance](https://docs.python.org/3.9/whatsnew/3.0.html#performance) - [Porting To Python 3.0](https://docs.python.org/3.9/whatsnew/3.0.html#porting-to-python-3-0) + [What’s New in Python 2.7](https://docs.python.org/3.9/whatsnew/2.7.html) - [The Future for Python 2.x](https://docs.python.org/3.9/whatsnew/2.7.html#the-future-for-python-2-x) - [Changes to the Handling of Deprecation Warnings](https://docs.python.org/3.9/whatsnew/2.7.html#changes-to-the-handling-of-deprecation-warnings) - [Python 3.1 Features](https://docs.python.org/3.9/whatsnew/2.7.html#python-3-1-features) - [PEP 372: Adding an Ordered Dictionary to collections](https://docs.python.org/3.9/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections) - [PEP 378: Format Specifier for Thousands Separator](https://docs.python.org/3.9/whatsnew/2.7.html#pep-378-format-specifier-for-thousands-separator) - [PEP 389: The argparse Module for Parsing Command Lines](https://docs.python.org/3.9/whatsnew/2.7.html#pep-389-the-argparse-module-for-parsing-command-lines) - [PEP 391: Dictionary-Based Configuration For Logging](https://docs.python.org/3.9/whatsnew/2.7.html#pep-391-dictionary-based-configuration-for-logging) - [PEP 3106: Dictionary Views](https://docs.python.org/3.9/whatsnew/2.7.html#pep-3106-dictionary-views) - [PEP 3137: The memoryview Object](https://docs.python.org/3.9/whatsnew/2.7.html#pep-3137-the-memoryview-object) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/2.7.html#other-language-changes) * [Interpreter Changes](https://docs.python.org/3.9/whatsnew/2.7.html#interpreter-changes) * [Optimizations](https://docs.python.org/3.9/whatsnew/2.7.html#optimizations) - [New and Improved Modules](https://docs.python.org/3.9/whatsnew/2.7.html#new-and-improved-modules) * [New module: importlib](https://docs.python.org/3.9/whatsnew/2.7.html#new-module-importlib) * [New module: sysconfig](https://docs.python.org/3.9/whatsnew/2.7.html#new-module-sysconfig) * [ttk: Themed Widgets for Tk](https://docs.python.org/3.9/whatsnew/2.7.html#ttk-themed-widgets-for-tk) * [Updated module: unittest](https://docs.python.org/3.9/whatsnew/2.7.html#updated-module-unittest) * [Updated module: ElementTree 1.3](https://docs.python.org/3.9/whatsnew/2.7.html#updated-module-elementtree-1-3) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/2.7.html#build-and-c-api-changes) * [Capsules](https://docs.python.org/3.9/whatsnew/2.7.html#capsules) * [Port-Specific Changes: Windows](https://docs.python.org/3.9/whatsnew/2.7.html#port-specific-changes-windows) * [Port-Specific Changes: Mac OS X](https://docs.python.org/3.9/whatsnew/2.7.html#port-specific-changes-mac-os-x) * [Port-Specific Changes: FreeBSD](https://docs.python.org/3.9/whatsnew/2.7.html#port-specific-changes-freebsd) - [Other Changes and Fixes](https://docs.python.org/3.9/whatsnew/2.7.html#other-changes-and-fixes) - [Porting to Python 2.7](https://docs.python.org/3.9/whatsnew/2.7.html#porting-to-python-2-7) - [New Features Added to Python 2.7 Maintenance Releases](https://docs.python.org/3.9/whatsnew/2.7.html#new-features-added-to-python-2-7-maintenance-releases) * [Two new environment variables for debug mode](https://docs.python.org/3.9/whatsnew/2.7.html#two-new-environment-variables-for-debug-mode) * [PEP 434: IDLE Enhancement Exception for All Branches](https://docs.python.org/3.9/whatsnew/2.7.html#pep-434-idle-enhancement-exception-for-all-branches) * [PEP 466: Network Security Enhancements for Python 2.7](https://docs.python.org/3.9/whatsnew/2.7.html#pep-466-network-security-enhancements-for-python-2-7) * [PEP 477: Backport ensurepip (PEP 453) to Python 2.7](https://docs.python.org/3.9/whatsnew/2.7.html#pep-477-backport-ensurepip-pep-453-to-python-2-7) + [Bootstrapping pip By Default](https://docs.python.org/3.9/whatsnew/2.7.html#bootstrapping-pip-by-default) + [Documentation Changes](https://docs.python.org/3.9/whatsnew/2.7.html#documentation-changes) * [PEP 476: Enabling certificate verification by default for stdlib http clients](https://docs.python.org/3.9/whatsnew/2.7.html#pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients) * [PEP 493: HTTPS verification migration tools for Python 2.7](https://docs.python.org/3.9/whatsnew/2.7.html#pep-493-https-verification-migration-tools-for-python-2-7) * [New `make regen-all` build target](https://docs.python.org/3.9/whatsnew/2.7.html#new-make-regen-all-build-target) * [Removal of `make touch` build target](https://docs.python.org/3.9/whatsnew/2.7.html#removal-of-make-touch-build-target) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.7.html#acknowledgements) + [What’s New in Python 2.6](https://docs.python.org/3.9/whatsnew/2.6.html) - [Python 3.0](https://docs.python.org/3.9/whatsnew/2.6.html#python-3-0) - [Changes to the Development Process](https://docs.python.org/3.9/whatsnew/2.6.html#changes-to-the-development-process) * [New Issue Tracker: Roundup](https://docs.python.org/3.9/whatsnew/2.6.html#new-issue-tracker-roundup) * [New Documentation Format: reStructuredText Using Sphinx](https://docs.python.org/3.9/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx) - [PEP 343: The ‘with’ statement](https://docs.python.org/3.9/whatsnew/2.6.html#pep-343-the-with-statement) * [Writing Context Managers](https://docs.python.org/3.9/whatsnew/2.6.html#writing-context-managers) * [The contextlib module](https://docs.python.org/3.9/whatsnew/2.6.html#the-contextlib-module) - [PEP 366: Explicit Relative Imports From a Main Module](https://docs.python.org/3.9/whatsnew/2.6.html#pep-366-explicit-relative-imports-from-a-main-module) - [PEP 370: Per-user `site-packages` Directory](https://docs.python.org/3.9/whatsnew/2.6.html#pep-370-per-user-site-packages-directory) - [PEP 371: The `multiprocessing` Package](https://docs.python.org/3.9/whatsnew/2.6.html#pep-371-the-multiprocessing-package) - [PEP 3101: Advanced String Formatting](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3101-advanced-string-formatting) - [PEP 3105: `print` As a Function](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3105-print-as-a-function) - [PEP 3110: Exception-Handling Changes](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3110-exception-handling-changes) - [PEP 3112: Byte Literals](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3112-byte-literals) - [PEP 3116: New I/O Library](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3116-new-i-o-library) - [PEP 3118: Revised Buffer Protocol](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3118-revised-buffer-protocol) - [PEP 3119: Abstract Base Classes](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3119-abstract-base-classes) - [PEP 3127: Integer Literal Support and Syntax](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax) - [PEP 3129: Class Decorators](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3129-class-decorators) - [PEP 3141: A Type Hierarchy for Numbers](https://docs.python.org/3.9/whatsnew/2.6.html#pep-3141-a-type-hierarchy-for-numbers) * [The `fractions` Module](https://docs.python.org/3.9/whatsnew/2.6.html#the-fractions-module) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/2.6.html#other-language-changes) * [Optimizations](https://docs.python.org/3.9/whatsnew/2.6.html#optimizations) * [Interpreter Changes](https://docs.python.org/3.9/whatsnew/2.6.html#interpreter-changes) - [New and Improved Modules](https://docs.python.org/3.9/whatsnew/2.6.html#new-and-improved-modules) * [The `ast` module](https://docs.python.org/3.9/whatsnew/2.6.html#the-ast-module) * [The `future_builtins` module](https://docs.python.org/3.9/whatsnew/2.6.html#the-future-builtins-module) * [The `json` module: JavaScript Object Notation](https://docs.python.org/3.9/whatsnew/2.6.html#the-json-module-javascript-object-notation) * [The `plistlib` module: A Property-List Parser](https://docs.python.org/3.9/whatsnew/2.6.html#the-plistlib-module-a-property-list-parser) * [ctypes Enhancements](https://docs.python.org/3.9/whatsnew/2.6.html#ctypes-enhancements) * [Improved SSL Support](https://docs.python.org/3.9/whatsnew/2.6.html#improved-ssl-support) - [Deprecations and Removals](https://docs.python.org/3.9/whatsnew/2.6.html#deprecations-and-removals) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/2.6.html#build-and-c-api-changes) * [Port-Specific Changes: Windows](https://docs.python.org/3.9/whatsnew/2.6.html#port-specific-changes-windows) * [Port-Specific Changes: Mac OS X](https://docs.python.org/3.9/whatsnew/2.6.html#port-specific-changes-mac-os-x) * [Port-Specific Changes: IRIX](https://docs.python.org/3.9/whatsnew/2.6.html#port-specific-changes-irix) - [Porting to Python 2.6](https://docs.python.org/3.9/whatsnew/2.6.html#porting-to-python-2-6) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.6.html#acknowledgements) + [What’s New in Python 2.5](https://docs.python.org/3.9/whatsnew/2.5.html) - [PEP 308: Conditional Expressions](https://docs.python.org/3.9/whatsnew/2.5.html#pep-308-conditional-expressions) - [PEP 309: Partial Function Application](https://docs.python.org/3.9/whatsnew/2.5.html#pep-309-partial-function-application) - [PEP 314: Metadata for Python Software Packages v1.1](https://docs.python.org/3.9/whatsnew/2.5.html#pep-314-metadata-for-python-software-packages-v1-1) - [PEP 328: Absolute and Relative Imports](https://docs.python.org/3.9/whatsnew/2.5.html#pep-328-absolute-and-relative-imports) - [PEP 338: Executing Modules as Scripts](https://docs.python.org/3.9/whatsnew/2.5.html#pep-338-executing-modules-as-scripts) - [PEP 341: Unified try/except/finally](https://docs.python.org/3.9/whatsnew/2.5.html#pep-341-unified-try-except-finally) - [PEP 342: New Generator Features](https://docs.python.org/3.9/whatsnew/2.5.html#pep-342-new-generator-features) - [PEP 343: The ‘with’ statement](https://docs.python.org/3.9/whatsnew/2.5.html#pep-343-the-with-statement) * [Writing Context Managers](https://docs.python.org/3.9/whatsnew/2.5.html#writing-context-managers) * [The contextlib module](https://docs.python.org/3.9/whatsnew/2.5.html#the-contextlib-module) - [PEP 352: Exceptions as New-Style Classes](https://docs.python.org/3.9/whatsnew/2.5.html#pep-352-exceptions-as-new-style-classes) - [PEP 353: Using ssize\_t as the index type](https://docs.python.org/3.9/whatsnew/2.5.html#pep-353-using-ssize-t-as-the-index-type) - [PEP 357: The ‘\_\_index\_\_’ method](https://docs.python.org/3.9/whatsnew/2.5.html#pep-357-the-index-method) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/2.5.html#other-language-changes) * [Interactive Interpreter Changes](https://docs.python.org/3.9/whatsnew/2.5.html#interactive-interpreter-changes) * [Optimizations](https://docs.python.org/3.9/whatsnew/2.5.html#optimizations) - [New, Improved, and Removed Modules](https://docs.python.org/3.9/whatsnew/2.5.html#new-improved-and-removed-modules) * [The ctypes package](https://docs.python.org/3.9/whatsnew/2.5.html#the-ctypes-package) * [The ElementTree package](https://docs.python.org/3.9/whatsnew/2.5.html#the-elementtree-package) * [The hashlib package](https://docs.python.org/3.9/whatsnew/2.5.html#the-hashlib-package) * [The sqlite3 package](https://docs.python.org/3.9/whatsnew/2.5.html#the-sqlite3-package) * [The wsgiref package](https://docs.python.org/3.9/whatsnew/2.5.html#the-wsgiref-package) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/2.5.html#build-and-c-api-changes) * [Port-Specific Changes](https://docs.python.org/3.9/whatsnew/2.5.html#port-specific-changes) - [Porting to Python 2.5](https://docs.python.org/3.9/whatsnew/2.5.html#porting-to-python-2-5) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.5.html#acknowledgements) + [What’s New in Python 2.4](https://docs.python.org/3.9/whatsnew/2.4.html) - [PEP 218: Built-In Set Objects](https://docs.python.org/3.9/whatsnew/2.4.html#pep-218-built-in-set-objects) - [PEP 237: Unifying Long Integers and Integers](https://docs.python.org/3.9/whatsnew/2.4.html#pep-237-unifying-long-integers-and-integers) - [PEP 289: Generator Expressions](https://docs.python.org/3.9/whatsnew/2.4.html#pep-289-generator-expressions) - [PEP 292: Simpler String Substitutions](https://docs.python.org/3.9/whatsnew/2.4.html#pep-292-simpler-string-substitutions) - [PEP 318: Decorators for Functions and Methods](https://docs.python.org/3.9/whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods) - [PEP 322: Reverse Iteration](https://docs.python.org/3.9/whatsnew/2.4.html#pep-322-reverse-iteration) - [PEP 324: New subprocess Module](https://docs.python.org/3.9/whatsnew/2.4.html#pep-324-new-subprocess-module) - [PEP 327: Decimal Data Type](https://docs.python.org/3.9/whatsnew/2.4.html#pep-327-decimal-data-type) * [Why is Decimal needed?](https://docs.python.org/3.9/whatsnew/2.4.html#why-is-decimal-needed) * [The `Decimal` type](https://docs.python.org/3.9/whatsnew/2.4.html#the-decimal-type) * [The `Context` type](https://docs.python.org/3.9/whatsnew/2.4.html#the-context-type) - [PEP 328: Multi-line Imports](https://docs.python.org/3.9/whatsnew/2.4.html#pep-328-multi-line-imports) - [PEP 331: Locale-Independent Float/String Conversions](https://docs.python.org/3.9/whatsnew/2.4.html#pep-331-locale-independent-float-string-conversions) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/2.4.html#other-language-changes) * [Optimizations](https://docs.python.org/3.9/whatsnew/2.4.html#optimizations) - [New, Improved, and Deprecated Modules](https://docs.python.org/3.9/whatsnew/2.4.html#new-improved-and-deprecated-modules) * [cookielib](https://docs.python.org/3.9/whatsnew/2.4.html#cookielib) * [doctest](https://docs.python.org/3.9/whatsnew/2.4.html#doctest) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/2.4.html#build-and-c-api-changes) * [Port-Specific Changes](https://docs.python.org/3.9/whatsnew/2.4.html#port-specific-changes) - [Porting to Python 2.4](https://docs.python.org/3.9/whatsnew/2.4.html#porting-to-python-2-4) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.4.html#acknowledgements) + [What’s New in Python 2.3](https://docs.python.org/3.9/whatsnew/2.3.html) - [PEP 218: A Standard Set Datatype](https://docs.python.org/3.9/whatsnew/2.3.html#pep-218-a-standard-set-datatype) - [PEP 255: Simple Generators](https://docs.python.org/3.9/whatsnew/2.3.html#pep-255-simple-generators) - [PEP 263: Source Code Encodings](https://docs.python.org/3.9/whatsnew/2.3.html#pep-263-source-code-encodings) - [PEP 273: Importing Modules from ZIP Archives](https://docs.python.org/3.9/whatsnew/2.3.html#pep-273-importing-modules-from-zip-archives) - [PEP 277: Unicode file name support for Windows NT](https://docs.python.org/3.9/whatsnew/2.3.html#pep-277-unicode-file-name-support-for-windows-nt) - [PEP 278: Universal Newline Support](https://docs.python.org/3.9/whatsnew/2.3.html#pep-278-universal-newline-support) - [PEP 279: enumerate()](https://docs.python.org/3.9/whatsnew/2.3.html#pep-279-enumerate) - [PEP 282: The logging Package](https://docs.python.org/3.9/whatsnew/2.3.html#pep-282-the-logging-package) - [PEP 285: A Boolean Type](https://docs.python.org/3.9/whatsnew/2.3.html#pep-285-a-boolean-type) - [PEP 293: Codec Error Handling Callbacks](https://docs.python.org/3.9/whatsnew/2.3.html#pep-293-codec-error-handling-callbacks) - [PEP 301: Package Index and Metadata for Distutils](https://docs.python.org/3.9/whatsnew/2.3.html#pep-301-package-index-and-metadata-for-distutils) - [PEP 302: New Import Hooks](https://docs.python.org/3.9/whatsnew/2.3.html#pep-302-new-import-hooks) - [PEP 305: Comma-separated Files](https://docs.python.org/3.9/whatsnew/2.3.html#pep-305-comma-separated-files) - [PEP 307: Pickle Enhancements](https://docs.python.org/3.9/whatsnew/2.3.html#pep-307-pickle-enhancements) - [Extended Slices](https://docs.python.org/3.9/whatsnew/2.3.html#extended-slices) - [Other Language Changes](https://docs.python.org/3.9/whatsnew/2.3.html#other-language-changes) * [String Changes](https://docs.python.org/3.9/whatsnew/2.3.html#string-changes) * [Optimizations](https://docs.python.org/3.9/whatsnew/2.3.html#optimizations) - [New, Improved, and Deprecated Modules](https://docs.python.org/3.9/whatsnew/2.3.html#new-improved-and-deprecated-modules) * [Date/Time Type](https://docs.python.org/3.9/whatsnew/2.3.html#date-time-type) * [The optparse Module](https://docs.python.org/3.9/whatsnew/2.3.html#the-optparse-module) - [Pymalloc: A Specialized Object Allocator](https://docs.python.org/3.9/whatsnew/2.3.html#pymalloc-a-specialized-object-allocator) - [Build and C API Changes](https://docs.python.org/3.9/whatsnew/2.3.html#build-and-c-api-changes) * [Port-Specific Changes](https://docs.python.org/3.9/whatsnew/2.3.html#port-specific-changes) - [Other Changes and Fixes](https://docs.python.org/3.9/whatsnew/2.3.html#other-changes-and-fixes) - [Porting to Python 2.3](https://docs.python.org/3.9/whatsnew/2.3.html#porting-to-python-2-3) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.3.html#acknowledgements) + [What’s New in Python 2.2](https://docs.python.org/3.9/whatsnew/2.2.html) - [Introduction](https://docs.python.org/3.9/whatsnew/2.2.html#introduction) - [PEPs 252 and 253: Type and Class Changes](https://docs.python.org/3.9/whatsnew/2.2.html#peps-252-and-253-type-and-class-changes) * [Old and New Classes](https://docs.python.org/3.9/whatsnew/2.2.html#old-and-new-classes) * [Descriptors](https://docs.python.org/3.9/whatsnew/2.2.html#descriptors) * [Multiple Inheritance: The Diamond Rule](https://docs.python.org/3.9/whatsnew/2.2.html#multiple-inheritance-the-diamond-rule) * [Attribute Access](https://docs.python.org/3.9/whatsnew/2.2.html#attribute-access) * [Related Links](https://docs.python.org/3.9/whatsnew/2.2.html#related-links) - [PEP 234: Iterators](https://docs.python.org/3.9/whatsnew/2.2.html#pep-234-iterators) - [PEP 255: Simple Generators](https://docs.python.org/3.9/whatsnew/2.2.html#pep-255-simple-generators) - [PEP 237: Unifying Long Integers and Integers](https://docs.python.org/3.9/whatsnew/2.2.html#pep-237-unifying-long-integers-and-integers) - [PEP 238: Changing the Division Operator](https://docs.python.org/3.9/whatsnew/2.2.html#pep-238-changing-the-division-operator) - [Unicode Changes](https://docs.python.org/3.9/whatsnew/2.2.html#unicode-changes) - [PEP 227: Nested Scopes](https://docs.python.org/3.9/whatsnew/2.2.html#pep-227-nested-scopes) - [New and Improved Modules](https://docs.python.org/3.9/whatsnew/2.2.html#new-and-improved-modules) - [Interpreter Changes and Fixes](https://docs.python.org/3.9/whatsnew/2.2.html#interpreter-changes-and-fixes) - [Other Changes and Fixes](https://docs.python.org/3.9/whatsnew/2.2.html#other-changes-and-fixes) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.2.html#acknowledgements) + [What’s New in Python 2.1](https://docs.python.org/3.9/whatsnew/2.1.html) - [Introduction](https://docs.python.org/3.9/whatsnew/2.1.html#introduction) - [PEP 227: Nested Scopes](https://docs.python.org/3.9/whatsnew/2.1.html#pep-227-nested-scopes) - [PEP 236: \_\_future\_\_ Directives](https://docs.python.org/3.9/whatsnew/2.1.html#pep-236-future-directives) - [PEP 207: Rich Comparisons](https://docs.python.org/3.9/whatsnew/2.1.html#pep-207-rich-comparisons) - [PEP 230: Warning Framework](https://docs.python.org/3.9/whatsnew/2.1.html#pep-230-warning-framework) - [PEP 229: New Build System](https://docs.python.org/3.9/whatsnew/2.1.html#pep-229-new-build-system) - [PEP 205: Weak References](https://docs.python.org/3.9/whatsnew/2.1.html#pep-205-weak-references) - [PEP 232: Function Attributes](https://docs.python.org/3.9/whatsnew/2.1.html#pep-232-function-attributes) - [PEP 235: Importing Modules on Case-Insensitive Platforms](https://docs.python.org/3.9/whatsnew/2.1.html#pep-235-importing-modules-on-case-insensitive-platforms) - [PEP 217: Interactive Display Hook](https://docs.python.org/3.9/whatsnew/2.1.html#pep-217-interactive-display-hook) - [PEP 208: New Coercion Model](https://docs.python.org/3.9/whatsnew/2.1.html#pep-208-new-coercion-model) - [PEP 241: Metadata in Python Packages](https://docs.python.org/3.9/whatsnew/2.1.html#pep-241-metadata-in-python-packages) - [New and Improved Modules](https://docs.python.org/3.9/whatsnew/2.1.html#new-and-improved-modules) - [Other Changes and Fixes](https://docs.python.org/3.9/whatsnew/2.1.html#other-changes-and-fixes) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.1.html#acknowledgements) + [What’s New in Python 2.0](https://docs.python.org/3.9/whatsnew/2.0.html) - [Introduction](https://docs.python.org/3.9/whatsnew/2.0.html#introduction) - [What About Python 1.6?](https://docs.python.org/3.9/whatsnew/2.0.html#what-about-python-1-6) - [New Development Process](https://docs.python.org/3.9/whatsnew/2.0.html#new-development-process) - [Unicode](https://docs.python.org/3.9/whatsnew/2.0.html#unicode) - [List Comprehensions](https://docs.python.org/3.9/whatsnew/2.0.html#list-comprehensions) - [Augmented Assignment](https://docs.python.org/3.9/whatsnew/2.0.html#augmented-assignment) - [String Methods](https://docs.python.org/3.9/whatsnew/2.0.html#string-methods) - [Garbage Collection of Cycles](https://docs.python.org/3.9/whatsnew/2.0.html#garbage-collection-of-cycles) - [Other Core Changes](https://docs.python.org/3.9/whatsnew/2.0.html#other-core-changes) * [Minor Language Changes](https://docs.python.org/3.9/whatsnew/2.0.html#minor-language-changes) * [Changes to Built-in Functions](https://docs.python.org/3.9/whatsnew/2.0.html#changes-to-built-in-functions) - [Porting to 2.0](https://docs.python.org/3.9/whatsnew/2.0.html#porting-to-2-0) - [Extending/Embedding Changes](https://docs.python.org/3.9/whatsnew/2.0.html#extending-embedding-changes) - [Distutils: Making Modules Easy to Install](https://docs.python.org/3.9/whatsnew/2.0.html#distutils-making-modules-easy-to-install) - [XML Modules](https://docs.python.org/3.9/whatsnew/2.0.html#xml-modules) * [SAX2 Support](https://docs.python.org/3.9/whatsnew/2.0.html#sax2-support) * [DOM Support](https://docs.python.org/3.9/whatsnew/2.0.html#dom-support) * [Relationship to PyXML](https://docs.python.org/3.9/whatsnew/2.0.html#relationship-to-pyxml) - [Module changes](https://docs.python.org/3.9/whatsnew/2.0.html#module-changes) - [New modules](https://docs.python.org/3.9/whatsnew/2.0.html#new-modules) - [IDLE Improvements](https://docs.python.org/3.9/whatsnew/2.0.html#idle-improvements) - [Deleted and Deprecated Modules](https://docs.python.org/3.9/whatsnew/2.0.html#deleted-and-deprecated-modules) - [Acknowledgements](https://docs.python.org/3.9/whatsnew/2.0.html#acknowledgements) + [Changelog](https://docs.python.org/3.9/whatsnew/changelog.html) - [Python 3.9.14 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-14-final) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#security) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#core-and-builtins) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#library) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#tests) - [Python 3.9.13 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-13-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id2) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id3) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#documentation) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id4) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#build) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#windows) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#tools-demos) - [Python 3.9.12 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-12-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id5) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id6) - [Python 3.9.11 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-11-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id7) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id8) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id9) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id10) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id11) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id12) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#macos) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#idle) - [Python 3.9.10 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-10-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id13) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id14) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id15) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id16) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id17) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id18) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id19) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id20) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#c-api) - [Python 3.9.9 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-9-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id21) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id22) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id23) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id24) - [Python 3.9.8 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-8-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id25) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id26) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id27) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id28) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id29) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id30) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id31) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id32) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id33) - [Python 3.9.7 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-7-final) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id34) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id35) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id36) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id37) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id38) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id39) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id40) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id41) - [Python 3.9.6 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-6-final) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id42) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id43) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id44) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id45) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id46) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id47) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id48) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id49) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id50) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id51) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id52) - [Python 3.9.5 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-5-final) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id53) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id54) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id55) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id56) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id57) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id58) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id59) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id60) - [Python 3.9.4 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-4-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id61) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id62) - [Python 3.9.3 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-3-final) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id63) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id64) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id65) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id66) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id67) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id68) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id69) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id70) - [Python 3.9.2 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-2-final) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id71) - [Python 3.9.2 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-2-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id72) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id73) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id74) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id75) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id76) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id77) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id78) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id79) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id80) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id81) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id82) - [Python 3.9.1 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-1-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id83) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id84) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id85) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id86) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id87) - [Python 3.9.1 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-1-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id88) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id89) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id90) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id91) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id92) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id93) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id94) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id95) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id96) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id97) - [Python 3.9.0 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-final) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id98) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id99) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id100) - [Python 3.9.0 release candidate 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-release-candidate-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id101) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id102) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id103) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id104) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id105) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id106) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id107) - [Python 3.9.0 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id108) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id109) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id110) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id111) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id112) - [Python 3.9.0 beta 5](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-beta-5) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id113) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id114) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id115) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id116) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id117) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id118) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id119) - [Python 3.9.0 beta 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-beta-4) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id120) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id121) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id122) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id123) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id124) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id125) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id126) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id127) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id128) - [Python 3.9.0 beta 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-beta-3) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id129) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id130) - [Python 3.9.0 beta 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-beta-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id131) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id132) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id133) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id134) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id135) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id136) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id137) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id138) - [Python 3.9.0 beta 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-beta-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id139) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id140) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id141) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id142) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id143) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id144) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id145) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id146) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id147) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id148) - [Python 3.9.0 alpha 6](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-6) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id149) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id150) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id151) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id152) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id153) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id154) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id155) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id156) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id157) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id158) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id159) - [Python 3.9.0 alpha 5](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-5) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id160) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id161) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id162) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id163) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id164) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id165) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id166) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id167) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id168) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id169) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id170) - [Python 3.9.0 alpha 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-4) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id171) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id172) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id173) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id174) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id175) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id176) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id177) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id178) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id179) - [Python 3.9.0 alpha 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id180) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id181) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id182) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id183) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id184) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id185) - [Python 3.9.0 alpha 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-2) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id186) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id187) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id188) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id189) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id190) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id191) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id192) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id193) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id194) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id195) - [Python 3.9.0 alpha 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-9-0-alpha-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id196) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id197) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id198) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id199) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id200) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id201) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id202) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id203) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id204) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id205) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id206) - [Python 3.8.0 beta 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-8-0-beta-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id207) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id208) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id209) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id210) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id211) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id212) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id213) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id214) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id215) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id216) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id217) - [Python 3.8.0 alpha 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-8-0-alpha-4) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id218) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id219) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id220) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id221) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id222) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id223) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id224) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id225) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id226) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id227) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id228) - [Python 3.8.0 alpha 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-8-0-alpha-3) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id229) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id230) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id231) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id232) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id233) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id234) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id235) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id236) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id237) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id238) - [Python 3.8.0 alpha 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-8-0-alpha-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id239) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id240) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id241) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id242) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id243) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id244) - [Python 3.8.0 alpha 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-8-0-alpha-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id245) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id246) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id247) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id248) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id249) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id250) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id251) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id252) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id253) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id254) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id255) - [Python 3.7.0 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-final) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id256) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id257) - [Python 3.7.0 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id258) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id259) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id260) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id261) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id262) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id263) - [Python 3.7.0 beta 5](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-beta-5) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id264) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id265) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id266) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id267) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id268) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id269) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id270) - [Python 3.7.0 beta 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-beta-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id271) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id272) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id273) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id274) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id275) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id276) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id277) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id278) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id279) - [Python 3.7.0 beta 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-beta-3) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id280) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id281) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id282) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id283) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id284) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id285) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id286) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id287) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id288) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id289) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id290) - [Python 3.7.0 beta 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-beta-2) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id291) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id292) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id293) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id294) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id295) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id296) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id297) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id298) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id299) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id300) - [Python 3.7.0 beta 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-beta-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id301) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id302) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id303) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id304) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id305) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id306) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id307) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id308) - [Python 3.7.0 alpha 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-alpha-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id309) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id310) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id311) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id312) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id313) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id314) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id315) - [Python 3.7.0 alpha 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-alpha-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id316) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id317) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id318) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id319) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id320) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id321) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id322) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id323) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id324) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id325) - [Python 3.7.0 alpha 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-alpha-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id326) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id327) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id328) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id329) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id330) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id331) - [Python 3.7.0 alpha 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-7-0-alpha-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id332) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id333) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id334) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id335) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id336) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id337) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id338) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id339) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id340) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id341) - [Python 3.6.6 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-6-final) - [Python 3.6.6 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-6-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id342) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id343) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id344) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id345) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id346) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id347) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id348) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id349) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id350) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id351) - [Python 3.6.5 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-5-final) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id352) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id353) - [Python 3.6.5 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-5-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id354) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id355) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id356) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id357) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id358) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id359) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id360) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id361) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id362) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id363) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id364) - [Python 3.6.4 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-4-final) - [Python 3.6.4 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-4-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id365) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id366) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id367) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id368) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id369) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id370) * [macOS](https://docs.python.org/3.9/whatsnew/changelog.html#id371) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id372) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id373) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id374) - [Python 3.6.3 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-3-final) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id375) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id376) - [Python 3.6.3 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-3-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id377) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id378) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id379) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id380) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id381) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id382) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id383) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id384) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id385) - [Python 3.6.2 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-2-final) - [Python 3.6.2 release candidate 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-2-release-candidate-2) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id386) - [Python 3.6.2 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-2-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id387) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id388) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id389) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id390) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id391) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id392) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id393) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id394) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id395) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id396) - [Python 3.6.1 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-1-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id397) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id398) - [Python 3.6.1 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-1-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id399) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id400) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id401) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id402) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id403) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id404) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id405) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id406) - [Python 3.6.0 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-final) - [Python 3.6.0 release candidate 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-release-candidate-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id407) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id408) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id409) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id410) - [Python 3.6.0 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id411) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id412) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id413) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id414) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id415) - [Python 3.6.0 beta 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-beta-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id416) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id417) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id418) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id419) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id420) - [Python 3.6.0 beta 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-beta-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id421) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id422) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id423) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id424) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id425) - [Python 3.6.0 beta 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-beta-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id426) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id427) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id428) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id429) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id430) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id431) - [Python 3.6.0 beta 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-beta-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id432) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id433) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id434) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id435) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id436) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id437) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id438) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id439) - [Python 3.6.0 alpha 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-alpha-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id440) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id441) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id442) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id443) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id444) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id445) - [Python 3.6.0 alpha 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-alpha-3) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id446) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id447) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id448) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id449) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id450) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id451) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id452) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id453) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id454) - [Python 3.6.0 alpha 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-alpha-2) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id455) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id456) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id457) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id458) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id459) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id460) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id461) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id462) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id463) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id464) - [Python 3.6.0 alpha 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-6-0-alpha-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id465) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id466) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id467) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id468) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id469) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id470) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id471) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id472) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id473) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id474) - [Python 3.5.5 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-5-final) - [Python 3.5.5 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-5-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id475) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id476) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id477) - [Python 3.5.4 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-4-final) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id478) - [Python 3.5.4 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-4-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id479) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id480) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id481) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id482) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id483) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id484) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id485) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id486) - [Python 3.5.3 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-3-final) - [Python 3.5.3 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-3-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id487) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id488) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id489) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id490) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id491) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id492) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id493) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id494) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id495) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id496) - [Python 3.5.2 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-2-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id497) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id498) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id499) - [Python 3.5.2 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-2-release-candidate-1) * [Security](https://docs.python.org/3.9/whatsnew/changelog.html#id500) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id501) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id502) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id503) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id504) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id505) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id506) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id507) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id508) - [Python 3.5.1 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-1-final) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id509) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id510) - [Python 3.5.1 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-1-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id511) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id512) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id513) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id514) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id515) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id516) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id517) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id518) - [Python 3.5.0 final](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-final) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id519) - [Python 3.5.0 release candidate 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-release-candidate-4) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id520) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id521) - [Python 3.5.0 release candidate 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-release-candidate-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id522) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id523) - [Python 3.5.0 release candidate 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-release-candidate-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id524) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id525) - [Python 3.5.0 release candidate 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-release-candidate-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id526) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id527) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id528) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id529) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id530) - [Python 3.5.0 beta 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-beta-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id531) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id532) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id533) - [Python 3.5.0 beta 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-beta-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id534) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id535) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id536) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id537) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id538) - [Python 3.5.0 beta 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-beta-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id539) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id540) - [Python 3.5.0 beta 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-beta-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id541) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id542) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id543) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id544) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id545) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id546) - [Python 3.5.0 alpha 4](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-alpha-4) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id547) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id548) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id549) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id550) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id551) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id552) - [Python 3.5.0 alpha 3](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-alpha-3) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id553) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id554) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id555) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id556) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id557) - [Python 3.5.0 alpha 2](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-alpha-2) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id558) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id559) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id560) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id561) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id562) - [Python 3.5.0 alpha 1](https://docs.python.org/3.9/whatsnew/changelog.html#python-3-5-0-alpha-1) * [Core and Builtins](https://docs.python.org/3.9/whatsnew/changelog.html#id563) * [Library](https://docs.python.org/3.9/whatsnew/changelog.html#id564) * [IDLE](https://docs.python.org/3.9/whatsnew/changelog.html#id565) * [Build](https://docs.python.org/3.9/whatsnew/changelog.html#id566) * [C API](https://docs.python.org/3.9/whatsnew/changelog.html#id567) * [Documentation](https://docs.python.org/3.9/whatsnew/changelog.html#id568) * [Tests](https://docs.python.org/3.9/whatsnew/changelog.html#id569) * [Tools/Demos](https://docs.python.org/3.9/whatsnew/changelog.html#id570) * [Windows](https://docs.python.org/3.9/whatsnew/changelog.html#id571) * [The Python Tutorial](tutorial/index) + [1. Whetting Your Appetite](tutorial/appetite) + [2. Using the Python Interpreter](tutorial/interpreter) - [2.1. Invoking the Interpreter](tutorial/interpreter#invoking-the-interpreter) * [2.1.1. Argument Passing](tutorial/interpreter#argument-passing) * [2.1.2. Interactive Mode](tutorial/interpreter#interactive-mode) - [2.2. The Interpreter and Its Environment](tutorial/interpreter#the-interpreter-and-its-environment) * [2.2.1. Source Code Encoding](tutorial/interpreter#source-code-encoding) + [3. An Informal Introduction to Python](tutorial/introduction) - [3.1. Using Python as a Calculator](tutorial/introduction#using-python-as-a-calculator) * [3.1.1. Numbers](tutorial/introduction#numbers) * [3.1.2. Strings](tutorial/introduction#strings) * [3.1.3. Lists](tutorial/introduction#lists) - [3.2. First Steps Towards Programming](tutorial/introduction#first-steps-towards-programming) + [4. More Control Flow Tools](tutorial/controlflow) - [4.1. `if` Statements](tutorial/controlflow#if-statements) - [4.2. `for` Statements](tutorial/controlflow#for-statements) - [4.3. The `range()` Function](tutorial/controlflow#the-range-function) - [4.4. `break` and `continue` Statements, and `else` Clauses on Loops](tutorial/controlflow#break-and-continue-statements-and-else-clauses-on-loops) - [4.5. `pass` Statements](tutorial/controlflow#pass-statements) - [4.6. Defining Functions](tutorial/controlflow#defining-functions) - [4.7. More on Defining Functions](tutorial/controlflow#more-on-defining-functions) * [4.7.1. Default Argument Values](tutorial/controlflow#default-argument-values) * [4.7.2. Keyword Arguments](tutorial/controlflow#keyword-arguments) * [4.7.3. Special parameters](tutorial/controlflow#special-parameters) + [4.7.3.1. Positional-or-Keyword Arguments](tutorial/controlflow#positional-or-keyword-arguments) + [4.7.3.2. Positional-Only Parameters](tutorial/controlflow#positional-only-parameters) + [4.7.3.3. Keyword-Only Arguments](tutorial/controlflow#keyword-only-arguments) + [4.7.3.4. Function Examples](tutorial/controlflow#function-examples) + [4.7.3.5. Recap](tutorial/controlflow#recap) * [4.7.4. Arbitrary Argument Lists](tutorial/controlflow#arbitrary-argument-lists) * [4.7.5. Unpacking Argument Lists](tutorial/controlflow#unpacking-argument-lists) * [4.7.6. Lambda Expressions](tutorial/controlflow#lambda-expressions) * [4.7.7. Documentation Strings](tutorial/controlflow#documentation-strings) * [4.7.8. Function Annotations](tutorial/controlflow#function-annotations) - [4.8. Intermezzo: Coding Style](tutorial/controlflow#intermezzo-coding-style) + [5. Data Structures](tutorial/datastructures) - [5.1. More on Lists](tutorial/datastructures#more-on-lists) * [5.1.1. Using Lists as Stacks](tutorial/datastructures#using-lists-as-stacks) * [5.1.2. Using Lists as Queues](tutorial/datastructures#using-lists-as-queues) * [5.1.3. List Comprehensions](tutorial/datastructures#list-comprehensions) * [5.1.4. Nested List Comprehensions](tutorial/datastructures#nested-list-comprehensions) - [5.2. The `del` statement](tutorial/datastructures#the-del-statement) - [5.3. Tuples and Sequences](tutorial/datastructures#tuples-and-sequences) - [5.4. Sets](tutorial/datastructures#sets) - [5.5. Dictionaries](tutorial/datastructures#dictionaries) - [5.6. Looping Techniques](tutorial/datastructures#looping-techniques) - [5.7. More on Conditions](tutorial/datastructures#more-on-conditions) - [5.8. Comparing Sequences and Other Types](tutorial/datastructures#comparing-sequences-and-other-types) + [6. Modules](tutorial/modules) - [6.1. More on Modules](tutorial/modules#more-on-modules) * [6.1.1. Executing modules as scripts](tutorial/modules#executing-modules-as-scripts) * [6.1.2. The Module Search Path](tutorial/modules#the-module-search-path) * [6.1.3. “Compiled” Python files](tutorial/modules#compiled-python-files) - [6.2. Standard Modules](tutorial/modules#standard-modules) - [6.3. The `dir()` Function](tutorial/modules#the-dir-function) - [6.4. Packages](tutorial/modules#packages) * [6.4.1. Importing \* From a Package](tutorial/modules#importing-from-a-package) * [6.4.2. Intra-package References](tutorial/modules#intra-package-references) * [6.4.3. Packages in Multiple Directories](tutorial/modules#packages-in-multiple-directories) + [7. Input and Output](tutorial/inputoutput) - [7.1. Fancier Output Formatting](tutorial/inputoutput#fancier-output-formatting) * [7.1.1. Formatted String Literals](tutorial/inputoutput#formatted-string-literals) * [7.1.2. The String format() Method](tutorial/inputoutput#the-string-format-method) * [7.1.3. Manual String Formatting](tutorial/inputoutput#manual-string-formatting) * [7.1.4. Old string formatting](tutorial/inputoutput#old-string-formatting) - [7.2. Reading and Writing Files](tutorial/inputoutput#reading-and-writing-files) * [7.2.1. Methods of File Objects](tutorial/inputoutput#methods-of-file-objects) * [7.2.2. Saving structured data with `json`](tutorial/inputoutput#saving-structured-data-with-json) + [8. Errors and Exceptions](tutorial/errors) - [8.1. Syntax Errors](tutorial/errors#syntax-errors) - [8.2. Exceptions](tutorial/errors#exceptions) - [8.3. Handling Exceptions](tutorial/errors#handling-exceptions) - [8.4. Raising Exceptions](tutorial/errors#raising-exceptions) - [8.5. Exception Chaining](tutorial/errors#exception-chaining) - [8.6. User-defined Exceptions](tutorial/errors#user-defined-exceptions) - [8.7. Defining Clean-up Actions](tutorial/errors#defining-clean-up-actions) - [8.8. Predefined Clean-up Actions](tutorial/errors#predefined-clean-up-actions) + [9. Classes](tutorial/classes) - [9.1. A Word About Names and Objects](tutorial/classes#a-word-about-names-and-objects) - [9.2. Python Scopes and Namespaces](tutorial/classes#python-scopes-and-namespaces) * [9.2.1. Scopes and Namespaces Example](tutorial/classes#scopes-and-namespaces-example) - [9.3. A First Look at Classes](tutorial/classes#a-first-look-at-classes) * [9.3.1. Class Definition Syntax](tutorial/classes#class-definition-syntax) * [9.3.2. Class Objects](tutorial/classes#class-objects) * [9.3.3. Instance Objects](tutorial/classes#instance-objects) * [9.3.4. Method Objects](tutorial/classes#method-objects) * [9.3.5. Class and Instance Variables](tutorial/classes#class-and-instance-variables) - [9.4. Random Remarks](tutorial/classes#random-remarks) - [9.5. Inheritance](tutorial/classes#inheritance) * [9.5.1. Multiple Inheritance](tutorial/classes#multiple-inheritance) - [9.6. Private Variables](tutorial/classes#private-variables) - [9.7. Odds and Ends](tutorial/classes#odds-and-ends) - [9.8. Iterators](tutorial/classes#iterators) - [9.9. Generators](tutorial/classes#generators) - [9.10. Generator Expressions](tutorial/classes#generator-expressions) + [10. Brief Tour of the Standard Library](tutorial/stdlib) - [10.1. Operating System Interface](tutorial/stdlib#operating-system-interface) - [10.2. File Wildcards](tutorial/stdlib#file-wildcards) - [10.3. Command Line Arguments](tutorial/stdlib#command-line-arguments) - [10.4. Error Output Redirection and Program Termination](tutorial/stdlib#error-output-redirection-and-program-termination) - [10.5. String Pattern Matching](tutorial/stdlib#string-pattern-matching) - [10.6. Mathematics](tutorial/stdlib#mathematics) - [10.7. Internet Access](tutorial/stdlib#internet-access) - [10.8. Dates and Times](tutorial/stdlib#dates-and-times) - [10.9. Data Compression](tutorial/stdlib#data-compression) - [10.10. Performance Measurement](tutorial/stdlib#performance-measurement) - [10.11. Quality Control](tutorial/stdlib#quality-control) - [10.12. Batteries Included](tutorial/stdlib#batteries-included) + [11. Brief Tour of the Standard Library — Part II](tutorial/stdlib2) - [11.1. Output Formatting](tutorial/stdlib2#output-formatting) - [11.2. Templating](tutorial/stdlib2#templating) - [11.3. Working with Binary Data Record Layouts](tutorial/stdlib2#working-with-binary-data-record-layouts) - [11.4. Multi-threading](tutorial/stdlib2#multi-threading) - [11.5. Logging](tutorial/stdlib2#logging) - [11.6. Weak References](tutorial/stdlib2#weak-references) - [11.7. Tools for Working with Lists](tutorial/stdlib2#tools-for-working-with-lists) - [11.8. Decimal Floating Point Arithmetic](tutorial/stdlib2#decimal-floating-point-arithmetic) + [12. Virtual Environments and Packages](tutorial/venv) - [12.1. Introduction](tutorial/venv#introduction) - [12.2. Creating Virtual Environments](tutorial/venv#creating-virtual-environments) - [12.3. Managing Packages with pip](tutorial/venv#managing-packages-with-pip) + [13. What Now?](tutorial/whatnow) + [14. Interactive Input Editing and History Substitution](tutorial/interactive) - [14.1. Tab Completion and History Editing](tutorial/interactive#tab-completion-and-history-editing) - [14.2. Alternatives to the Interactive Interpreter](tutorial/interactive#alternatives-to-the-interactive-interpreter) + [15. Floating Point Arithmetic: Issues and Limitations](tutorial/floatingpoint) - [15.1. Representation Error](tutorial/floatingpoint#representation-error) + [16. Appendix](tutorial/appendix) - [16.1. Interactive Mode](tutorial/appendix#interactive-mode) * [16.1.1. Error Handling](tutorial/appendix#error-handling) * [16.1.2. Executable Python Scripts](tutorial/appendix#executable-python-scripts) * [16.1.3. The Interactive Startup File](tutorial/appendix#the-interactive-startup-file) * [16.1.4. The Customization Modules](tutorial/appendix#the-customization-modules) * [Python Setup and Usage](using/index) + [1. Command line and environment](using/cmdline) - [1.1. Command line](using/cmdline#command-line) * [1.1.1. Interface options](using/cmdline#interface-options) * [1.1.2. Generic options](using/cmdline#generic-options) * [1.1.3. Miscellaneous options](using/cmdline#miscellaneous-options) * [1.1.4. Options you shouldn’t use](using/cmdline#options-you-shouldn-t-use) - [1.2. Environment variables](using/cmdline#environment-variables) * [1.2.1. Debug-mode variables](using/cmdline#debug-mode-variables) + [2. Using Python on Unix platforms](using/unix) - [2.1. Getting and installing the latest version of Python](using/unix#getting-and-installing-the-latest-version-of-python) * [2.1.1. On Linux](using/unix#on-linux) * [2.1.2. On FreeBSD and OpenBSD](using/unix#on-freebsd-and-openbsd) * [2.1.3. On OpenSolaris](using/unix#on-opensolaris) - [2.2. Building Python](using/unix#building-python) - [2.3. Python-related paths and files](using/unix#python-related-paths-and-files) - [2.4. Miscellaneous](using/unix#miscellaneous) + [3. Using Python on Windows](using/windows) - [3.1. The full installer](using/windows#the-full-installer) * [3.1.1. Installation steps](using/windows#installation-steps) * [3.1.2. Removing the MAX\_PATH Limitation](using/windows#removing-the-max-path-limitation) * [3.1.3. Installing Without UI](using/windows#installing-without-ui) * [3.1.4. Installing Without Downloading](using/windows#installing-without-downloading) * [3.1.5. Modifying an install](using/windows#modifying-an-install) - [3.2. The Microsoft Store package](using/windows#the-microsoft-store-package) * [3.2.1. Known Issues](using/windows#known-issues) - [3.3. The nuget.org packages](using/windows#the-nuget-org-packages) - [3.4. The embeddable package](using/windows#the-embeddable-package) * [3.4.1. Python Application](using/windows#python-application) * [3.4.2. Embedding Python](using/windows#embedding-python) - [3.5. Alternative bundles](using/windows#alternative-bundles) - [3.6. Configuring Python](using/windows#configuring-python) * [3.6.1. Excursus: Setting environment variables](using/windows#excursus-setting-environment-variables) * [3.6.2. Finding the Python executable](using/windows#finding-the-python-executable) - [3.7. UTF-8 mode](using/windows#utf-8-mode) - [3.8. Python Launcher for Windows](using/windows#python-launcher-for-windows) * [3.8.1. Getting started](using/windows#getting-started) + [3.8.1.1. From the command-line](using/windows#from-the-command-line) + [3.8.1.2. Virtual environments](using/windows#virtual-environments) + [3.8.1.3. From a script](using/windows#from-a-script) + [3.8.1.4. From file associations](using/windows#from-file-associations) * [3.8.2. Shebang Lines](using/windows#shebang-lines) * [3.8.3. Arguments in shebang lines](using/windows#arguments-in-shebang-lines) * [3.8.4. Customization](using/windows#customization) + [3.8.4.1. Customization via INI files](using/windows#customization-via-ini-files) + [3.8.4.2. Customizing default Python versions](using/windows#customizing-default-python-versions) * [3.8.5. Diagnostics](using/windows#diagnostics) - [3.9. Finding modules](using/windows#finding-modules) - [3.10. Additional modules](using/windows#additional-modules) * [3.10.1. PyWin32](using/windows#pywin32) * [3.10.2. cx\_Freeze](using/windows#cx-freeze) - [3.11. Compiling Python on Windows](using/windows#compiling-python-on-windows) - [3.12. Other Platforms](using/windows#other-platforms) + [4. Using Python on a Mac](using/mac) - [4.1. Getting and Installing MacPython](using/mac#getting-and-installing-macpython) * [4.1.1. How to run a Python script](using/mac#how-to-run-a-python-script) * [4.1.2. Running scripts with a GUI](using/mac#running-scripts-with-a-gui) * [4.1.3. Configuration](using/mac#configuration) - [4.2. The IDE](using/mac#the-ide) - [4.3. Installing Additional Python Packages](using/mac#installing-additional-python-packages) - [4.4. GUI Programming on the Mac](using/mac#gui-programming-on-the-mac) - [4.5. Distributing Python Applications on the Mac](using/mac#distributing-python-applications-on-the-mac) - [4.6. Other Resources](using/mac#other-resources) + [5. Editors and IDEs](using/editors) * [The Python Language Reference](reference/index) + [1. Introduction](reference/introduction) - [1.1. Alternate Implementations](reference/introduction#alternate-implementations) - [1.2. Notation](reference/introduction#notation) + [2. Lexical analysis](reference/lexical_analysis) - [2.1. Line structure](reference/lexical_analysis#line-structure) * [2.1.1. Logical lines](reference/lexical_analysis#logical-lines) * [2.1.2. Physical lines](reference/lexical_analysis#physical-lines) * [2.1.3. Comments](reference/lexical_analysis#comments) * [2.1.4. Encoding declarations](reference/lexical_analysis#encoding-declarations) * [2.1.5. Explicit line joining](reference/lexical_analysis#explicit-line-joining) * [2.1.6. Implicit line joining](reference/lexical_analysis#implicit-line-joining) * [2.1.7. Blank lines](reference/lexical_analysis#blank-lines) * [2.1.8. Indentation](reference/lexical_analysis#indentation) * [2.1.9. Whitespace between tokens](reference/lexical_analysis#whitespace-between-tokens) - [2.2. Other tokens](reference/lexical_analysis#other-tokens) - [2.3. Identifiers and keywords](reference/lexical_analysis#identifiers) * [2.3.1. Keywords](reference/lexical_analysis#keywords) * [2.3.2. Reserved classes of identifiers](reference/lexical_analysis#reserved-classes-of-identifiers) - [2.4. Literals](reference/lexical_analysis#literals) * [2.4.1. String and Bytes literals](reference/lexical_analysis#string-and-bytes-literals) * [2.4.2. String literal concatenation](reference/lexical_analysis#string-literal-concatenation) * [2.4.3. Formatted string literals](reference/lexical_analysis#formatted-string-literals) * [2.4.4. Numeric literals](reference/lexical_analysis#numeric-literals) * [2.4.5. Integer literals](reference/lexical_analysis#integer-literals) * [2.4.6. Floating point literals](reference/lexical_analysis#floating-point-literals) * [2.4.7. Imaginary literals](reference/lexical_analysis#imaginary-literals) - [2.5. Operators](reference/lexical_analysis#operators) - [2.6. Delimiters](reference/lexical_analysis#delimiters) + [3. Data model](reference/datamodel) - [3.1. Objects, values and types](reference/datamodel#objects-values-and-types) - [3.2. The standard type hierarchy](reference/datamodel#the-standard-type-hierarchy) - [3.3. Special method names](reference/datamodel#special-method-names) * [3.3.1. Basic customization](reference/datamodel#basic-customization) * [3.3.2. Customizing attribute access](reference/datamodel#customizing-attribute-access) + [3.3.2.1. Customizing module attribute access](reference/datamodel#customizing-module-attribute-access) + [3.3.2.2. Implementing Descriptors](reference/datamodel#implementing-descriptors) + [3.3.2.3. Invoking Descriptors](reference/datamodel#invoking-descriptors) + [3.3.2.4. \_\_slots\_\_](reference/datamodel#slots) - [3.3.2.4.1. Notes on using \_\_slots\_\_](reference/datamodel#notes-on-using-slots) * [3.3.3. Customizing class creation](reference/datamodel#customizing-class-creation) + [3.3.3.1. Metaclasses](reference/datamodel#metaclasses) + [3.3.3.2. Resolving MRO entries](reference/datamodel#resolving-mro-entries) + [3.3.3.3. Determining the appropriate metaclass](reference/datamodel#determining-the-appropriate-metaclass) + [3.3.3.4. Preparing the class namespace](reference/datamodel#preparing-the-class-namespace) + [3.3.3.5. Executing the class body](reference/datamodel#executing-the-class-body) + [3.3.3.6. Creating the class object](reference/datamodel#creating-the-class-object) + [3.3.3.7. Uses for metaclasses](reference/datamodel#uses-for-metaclasses) * [3.3.4. Customizing instance and subclass checks](reference/datamodel#customizing-instance-and-subclass-checks) * [3.3.5. Emulating generic types](reference/datamodel#emulating-generic-types) + [3.3.5.1. The purpose of \_\_class\_getitem\_\_](reference/datamodel#the-purpose-of-class-getitem) + [3.3.5.2. \_\_class\_getitem\_\_ versus \_\_getitem\_\_](reference/datamodel#class-getitem-versus-getitem) * [3.3.6. Emulating callable objects](reference/datamodel#emulating-callable-objects) * [3.3.7. Emulating container types](reference/datamodel#emulating-container-types) * [3.3.8. Emulating numeric types](reference/datamodel#emulating-numeric-types) * [3.3.9. With Statement Context Managers](reference/datamodel#with-statement-context-managers) * [3.3.10. Special method lookup](reference/datamodel#special-method-lookup) - [3.4. Coroutines](reference/datamodel#coroutines) * [3.4.1. Awaitable Objects](reference/datamodel#awaitable-objects) * [3.4.2. Coroutine Objects](reference/datamodel#coroutine-objects) * [3.4.3. Asynchronous Iterators](reference/datamodel#asynchronous-iterators) * [3.4.4. Asynchronous Context Managers](reference/datamodel#asynchronous-context-managers) + [4. Execution model](reference/executionmodel) - [4.1. Structure of a program](reference/executionmodel#structure-of-a-program) - [4.2. Naming and binding](reference/executionmodel#naming-and-binding) * [4.2.1. Binding of names](reference/executionmodel#binding-of-names) * [4.2.2. Resolution of names](reference/executionmodel#resolution-of-names) * [4.2.3. Builtins and restricted execution](reference/executionmodel#builtins-and-restricted-execution) * [4.2.4. Interaction with dynamic features](reference/executionmodel#interaction-with-dynamic-features) - [4.3. Exceptions](reference/executionmodel#exceptions) + [5. The import system](reference/import) - [5.1. `importlib`](reference/import#importlib) - [5.2. Packages](reference/import#packages) * [5.2.1. Regular packages](reference/import#regular-packages) * [5.2.2. Namespace packages](reference/import#namespace-packages) - [5.3. Searching](reference/import#searching) * [5.3.1. The module cache](reference/import#the-module-cache) * [5.3.2. Finders and loaders](reference/import#finders-and-loaders) * [5.3.3. Import hooks](reference/import#import-hooks) * [5.3.4. The meta path](reference/import#the-meta-path) - [5.4. Loading](reference/import#loading) * [5.4.1. Loaders](reference/import#loaders) * [5.4.2. Submodules](reference/import#submodules) * [5.4.3. Module spec](reference/import#module-spec) * [5.4.4. Import-related module attributes](reference/import#import-related-module-attributes) * [5.4.5. module.\_\_path\_\_](reference/import#module-path) * [5.4.6. Module reprs](reference/import#module-reprs) * [5.4.7. Cached bytecode invalidation](reference/import#cached-bytecode-invalidation) - [5.5. The Path Based Finder](reference/import#the-path-based-finder) * [5.5.1. Path entry finders](reference/import#path-entry-finders) * [5.5.2. Path entry finder protocol](reference/import#path-entry-finder-protocol) - [5.6. Replacing the standard import system](reference/import#replacing-the-standard-import-system) - [5.7. Package Relative Imports](reference/import#package-relative-imports) - [5.8. Special considerations for \_\_main\_\_](reference/import#special-considerations-for-main) * [5.8.1. \_\_main\_\_.\_\_spec\_\_](reference/import#main-spec) - [5.9. Open issues](reference/import#open-issues) - [5.10. References](reference/import#references) + [6. Expressions](reference/expressions) - [6.1. Arithmetic conversions](reference/expressions#arithmetic-conversions) - [6.2. Atoms](reference/expressions#atoms) * [6.2.1. Identifiers (Names)](reference/expressions#atom-identifiers) * [6.2.2. Literals](reference/expressions#literals) * [6.2.3. Parenthesized forms](reference/expressions#parenthesized-forms) * [6.2.4. Displays for lists, sets and dictionaries](reference/expressions#displays-for-lists-sets-and-dictionaries) * [6.2.5. List displays](reference/expressions#list-displays) * [6.2.6. Set displays](reference/expressions#set-displays) * [6.2.7. Dictionary displays](reference/expressions#dictionary-displays) * [6.2.8. Generator expressions](reference/expressions#generator-expressions) * [6.2.9. Yield expressions](reference/expressions#yield-expressions) + [6.2.9.1. Generator-iterator methods](reference/expressions#generator-iterator-methods) + [6.2.9.2. Examples](reference/expressions#examples) + [6.2.9.3. Asynchronous generator functions](reference/expressions#asynchronous-generator-functions) + [6.2.9.4. Asynchronous generator-iterator methods](reference/expressions#asynchronous-generator-iterator-methods) - [6.3. Primaries](reference/expressions#primaries) * [6.3.1. Attribute references](reference/expressions#attribute-references) * [6.3.2. Subscriptions](reference/expressions#subscriptions) * [6.3.3. Slicings](reference/expressions#slicings) * [6.3.4. Calls](reference/expressions#calls) - [6.4. Await expression](reference/expressions#await-expression) - [6.5. The power operator](reference/expressions#the-power-operator) - [6.6. Unary arithmetic and bitwise operations](reference/expressions#unary-arithmetic-and-bitwise-operations) - [6.7. Binary arithmetic operations](reference/expressions#binary-arithmetic-operations) - [6.8. Shifting operations](reference/expressions#shifting-operations) - [6.9. Binary bitwise operations](reference/expressions#binary-bitwise-operations) - [6.10. Comparisons](reference/expressions#comparisons) * [6.10.1. Value comparisons](reference/expressions#value-comparisons) * [6.10.2. Membership test operations](reference/expressions#membership-test-operations) * [6.10.3. Identity comparisons](reference/expressions#is-not) - [6.11. Boolean operations](reference/expressions#boolean-operations) - [6.12. Assignment expressions](reference/expressions#assignment-expressions) - [6.13. Conditional expressions](reference/expressions#conditional-expressions) - [6.14. Lambdas](reference/expressions#lambda) - [6.15. Expression lists](reference/expressions#expression-lists) - [6.16. Evaluation order](reference/expressions#evaluation-order) - [6.17. Operator precedence](reference/expressions#operator-precedence) + [7. Simple statements](reference/simple_stmts) - [7.1. Expression statements](reference/simple_stmts#expression-statements) - [7.2. Assignment statements](reference/simple_stmts#assignment-statements) * [7.2.1. Augmented assignment statements](reference/simple_stmts#augmented-assignment-statements) * [7.2.2. Annotated assignment statements](reference/simple_stmts#annotated-assignment-statements) - [7.3. The `assert` statement](reference/simple_stmts#the-assert-statement) - [7.4. The `pass` statement](reference/simple_stmts#the-pass-statement) - [7.5. The `del` statement](reference/simple_stmts#the-del-statement) - [7.6. The `return` statement](reference/simple_stmts#the-return-statement) - [7.7. The `yield` statement](reference/simple_stmts#the-yield-statement) - [7.8. The `raise` statement](reference/simple_stmts#the-raise-statement) - [7.9. The `break` statement](reference/simple_stmts#the-break-statement) - [7.10. The `continue` statement](reference/simple_stmts#the-continue-statement) - [7.11. The `import` statement](reference/simple_stmts#the-import-statement) * [7.11.1. Future statements](reference/simple_stmts#future-statements) - [7.12. The `global` statement](reference/simple_stmts#the-global-statement) - [7.13. The `nonlocal` statement](reference/simple_stmts#the-nonlocal-statement) + [8. Compound statements](reference/compound_stmts) - [8.1. The `if` statement](reference/compound_stmts#the-if-statement) - [8.2. The `while` statement](reference/compound_stmts#the-while-statement) - [8.3. The `for` statement](reference/compound_stmts#the-for-statement) - [8.4. The `try` statement](reference/compound_stmts#the-try-statement) - [8.5. The `with` statement](reference/compound_stmts#the-with-statement) - [8.6. Function definitions](reference/compound_stmts#function-definitions) - [8.7. Class definitions](reference/compound_stmts#class-definitions) - [8.8. Coroutines](reference/compound_stmts#coroutines) * [8.8.1. Coroutine function definition](reference/compound_stmts#coroutine-function-definition) * [8.8.2. The `async for` statement](reference/compound_stmts#the-async-for-statement) * [8.8.3. The `async with` statement](reference/compound_stmts#the-async-with-statement) + [9. Top-level components](reference/toplevel_components) - [9.1. Complete Python programs](reference/toplevel_components#complete-python-programs) - [9.2. File input](reference/toplevel_components#file-input) - [9.3. Interactive input](reference/toplevel_components#interactive-input) - [9.4. Expression input](reference/toplevel_components#expression-input) + [10. Full Grammar specification](reference/grammar) * [The Python Standard Library](library/index) + [Introduction](https://docs.python.org/3.9/library/intro.html) - [Notes on availability](https://docs.python.org/3.9/library/intro.html#notes-on-availability) + [Built-in Functions](library/functions) + [Built-in Constants](library/constants) - [Constants added by the `site` module](library/constants#constants-added-by-the-site-module) + [Built-in Types](library/stdtypes) - [Truth Value Testing](library/stdtypes#truth-value-testing) - [Boolean Operations — `and`, `or`, `not`](library/stdtypes#boolean-operations-and-or-not) - [Comparisons](library/stdtypes#comparisons) - [Numeric Types — `int`, `float`, `complex`](library/stdtypes#numeric-types-int-float-complex) * [Bitwise Operations on Integer Types](library/stdtypes#bitwise-operations-on-integer-types) * [Additional Methods on Integer Types](library/stdtypes#additional-methods-on-integer-types) * [Additional Methods on Float](library/stdtypes#additional-methods-on-float) * [Hashing of numeric types](library/stdtypes#hashing-of-numeric-types) - [Iterator Types](library/stdtypes#iterator-types) * [Generator Types](library/stdtypes#generator-types) - [Sequence Types — `list`, `tuple`, `range`](library/stdtypes#sequence-types-list-tuple-range) * [Common Sequence Operations](library/stdtypes#common-sequence-operations) * [Immutable Sequence Types](library/stdtypes#immutable-sequence-types) * [Mutable Sequence Types](library/stdtypes#mutable-sequence-types) * [Lists](library/stdtypes#lists) * [Tuples](library/stdtypes#tuples) * [Ranges](library/stdtypes#ranges) - [Text Sequence Type — `str`](library/stdtypes#text-sequence-type-str) * [String Methods](library/stdtypes#string-methods) * [`printf`-style String Formatting](library/stdtypes#printf-style-string-formatting) - [Binary Sequence Types — `bytes`, `bytearray`, `memoryview`](library/stdtypes#binary-sequence-types-bytes-bytearray-memoryview) * [Bytes Objects](library/stdtypes#bytes-objects) * [Bytearray Objects](library/stdtypes#bytearray-objects) * [Bytes and Bytearray Operations](library/stdtypes#bytes-and-bytearray-operations) * [`printf`-style Bytes Formatting](library/stdtypes#printf-style-bytes-formatting) * [Memory Views](library/stdtypes#memory-views) - [Set Types — `set`, `frozenset`](library/stdtypes#set-types-set-frozenset) - [Mapping Types — `dict`](library/stdtypes#mapping-types-dict) * [Dictionary view objects](library/stdtypes#dictionary-view-objects) - [Context Manager Types](library/stdtypes#context-manager-types) - [Generic Alias Type](library/stdtypes#generic-alias-type) * [Standard Generic Classes](library/stdtypes#standard-generic-classes) * [Special Attributes of `GenericAlias` objects](library/stdtypes#special-attributes-of-genericalias-objects) - [Other Built-in Types](library/stdtypes#other-built-in-types) * [Modules](library/stdtypes#modules) * [Classes and Class Instances](library/stdtypes#classes-and-class-instances) * [Functions](library/stdtypes#functions) * [Methods](library/stdtypes#methods) * [Code Objects](library/stdtypes#code-objects) * [Type Objects](library/stdtypes#type-objects) * [The Null Object](library/stdtypes#the-null-object) * [The Ellipsis Object](library/stdtypes#the-ellipsis-object) * [The NotImplemented Object](library/stdtypes#the-notimplemented-object) * [Boolean Values](library/stdtypes#boolean-values) * [Internal Objects](library/stdtypes#internal-objects) - [Special Attributes](library/stdtypes#special-attributes) - [Integer string conversion length limitation](library/stdtypes#integer-string-conversion-length-limitation) * [Affected APIs](library/stdtypes#affected-apis) * [Configuring the limit](library/stdtypes#configuring-the-limit) * [Recommended configuration](library/stdtypes#recommended-configuration) + [Built-in Exceptions](library/exceptions) - [Exception context](library/exceptions#exception-context) - [Inheriting from built-in exceptions](library/exceptions#inheriting-from-built-in-exceptions) - [Base classes](library/exceptions#base-classes) - [Concrete exceptions](library/exceptions#concrete-exceptions) * [OS exceptions](library/exceptions#os-exceptions) - [Warnings](library/exceptions#warnings) - [Exception hierarchy](library/exceptions#exception-hierarchy) + [Text Processing Services](library/text) - [`string` — Common string operations](library/string) * [String constants](library/string#string-constants) * [Custom String Formatting](library/string#custom-string-formatting) * [Format String Syntax](library/string#format-string-syntax) + [Format Specification Mini-Language](library/string#format-specification-mini-language) + [Format examples](library/string#format-examples) * [Template strings](library/string#template-strings) * [Helper functions](library/string#helper-functions) - [`re` — Regular expression operations](library/re) * [Regular Expression Syntax](library/re#regular-expression-syntax) * [Module Contents](library/re#module-contents) * [Regular Expression Objects](library/re#regular-expression-objects) * [Match Objects](library/re#match-objects) * [Regular Expression Examples](library/re#regular-expression-examples) + [Checking for a Pair](library/re#checking-for-a-pair) + [Simulating scanf()](library/re#simulating-scanf) + [search() vs. match()](library/re#search-vs-match) + [Making a Phonebook](library/re#making-a-phonebook) + [Text Munging](library/re#text-munging) + [Finding all Adverbs](library/re#finding-all-adverbs) + [Finding all Adverbs and their Positions](library/re#finding-all-adverbs-and-their-positions) + [Raw String Notation](library/re#raw-string-notation) + [Writing a Tokenizer](library/re#writing-a-tokenizer) - [`difflib` — Helpers for computing deltas](library/difflib) * [SequenceMatcher Objects](library/difflib#sequencematcher-objects) * [SequenceMatcher Examples](library/difflib#sequencematcher-examples) * [Differ Objects](library/difflib#differ-objects) * [Differ Example](library/difflib#differ-example) * [A command-line interface to difflib](library/difflib#a-command-line-interface-to-difflib) - [`textwrap` — Text wrapping and filling](library/textwrap) - [`unicodedata` — Unicode Database](library/unicodedata) - [`stringprep` — Internet String Preparation](library/stringprep) - [`readline` — GNU readline interface](library/readline) * [Init file](library/readline#init-file) * [Line buffer](library/readline#line-buffer) * [History file](library/readline#history-file) * [History list](library/readline#history-list) * [Startup hooks](library/readline#startup-hooks) * [Completion](library/readline#completion) * [Example](library/readline#example) - [`rlcompleter` — Completion function for GNU readline](library/rlcompleter) * [Completer Objects](library/rlcompleter#completer-objects) + [Binary Data Services](library/binary) - [`struct` — Interpret bytes as packed binary data](library/struct) * [Functions and Exceptions](library/struct#functions-and-exceptions) * [Format Strings](library/struct#format-strings) + [Byte Order, Size, and Alignment](library/struct#byte-order-size-and-alignment) + [Format Characters](library/struct#format-characters) + [Examples](library/struct#examples) * [Classes](library/struct#classes) - [`codecs` — Codec registry and base classes](library/codecs) * [Codec Base Classes](library/codecs#codec-base-classes) + [Error Handlers](library/codecs#error-handlers) + [Stateless Encoding and Decoding](library/codecs#stateless-encoding-and-decoding) + [Incremental Encoding and Decoding](library/codecs#incremental-encoding-and-decoding) - [IncrementalEncoder Objects](library/codecs#incrementalencoder-objects) - [IncrementalDecoder Objects](library/codecs#incrementaldecoder-objects) + [Stream Encoding and Decoding](library/codecs#stream-encoding-and-decoding) - [StreamWriter Objects](library/codecs#streamwriter-objects) - [StreamReader Objects](library/codecs#streamreader-objects) - [StreamReaderWriter Objects](library/codecs#streamreaderwriter-objects) - [StreamRecoder Objects](library/codecs#streamrecoder-objects) * [Encodings and Unicode](library/codecs#encodings-and-unicode) * [Standard Encodings](library/codecs#standard-encodings) * [Python Specific Encodings](library/codecs#python-specific-encodings) + [Text Encodings](library/codecs#text-encodings) + [Binary Transforms](library/codecs#binary-transforms) + [Text Transforms](library/codecs#text-transforms) * [`encodings.idna` — Internationalized Domain Names in Applications](library/codecs#module-encodings.idna) * [`encodings.mbcs` — Windows ANSI codepage](library/codecs#module-encodings.mbcs) * [`encodings.utf_8_sig` — UTF-8 codec with BOM signature](library/codecs#module-encodings.utf_8_sig) + [Data Types](library/datatypes) - [`datetime` — Basic date and time types](library/datetime) * [Aware and Naive Objects](library/datetime#aware-and-naive-objects) * [Constants](library/datetime#constants) * [Available Types](library/datetime#available-types) + [Common Properties](library/datetime#common-properties) + [Determining if an Object is Aware or Naive](library/datetime#determining-if-an-object-is-aware-or-naive) * [`timedelta` Objects](library/datetime#timedelta-objects) + [Examples of usage: `timedelta`](library/datetime#examples-of-usage-timedelta) * [`date` Objects](library/datetime#date-objects) + [Examples of Usage: `date`](library/datetime#examples-of-usage-date) * [`datetime` Objects](library/datetime#datetime-objects) + [Examples of Usage: `datetime`](library/datetime#examples-of-usage-datetime) * [`time` Objects](library/datetime#time-objects) + [Examples of Usage: `time`](library/datetime#examples-of-usage-time) * [`tzinfo` Objects](library/datetime#tzinfo-objects) * [`timezone` Objects](library/datetime#timezone-objects) * [`strftime()` and `strptime()` Behavior](library/datetime#strftime-and-strptime-behavior) + [`strftime()` and `strptime()` Format Codes](library/datetime#strftime-and-strptime-format-codes) + [Technical Detail](library/datetime#technical-detail) - [`zoneinfo` — IANA time zone support](library/zoneinfo) * [Using `ZoneInfo`](library/zoneinfo#using-zoneinfo) * [Data sources](library/zoneinfo#data-sources) + [Configuring the data sources](library/zoneinfo#configuring-the-data-sources) - [Compile-time configuration](library/zoneinfo#compile-time-configuration) - [Environment configuration](library/zoneinfo#environment-configuration) - [Runtime configuration](library/zoneinfo#runtime-configuration) * [The `ZoneInfo` class](library/zoneinfo#the-zoneinfo-class) + [String representations](library/zoneinfo#string-representations) + [Pickle serialization](library/zoneinfo#pickle-serialization) * [Functions](library/zoneinfo#functions) * [Globals](library/zoneinfo#globals) * [Exceptions and warnings](library/zoneinfo#exceptions-and-warnings) - [`calendar` — General calendar-related functions](library/calendar) - [`collections` — Container datatypes](library/collections) * [`ChainMap` objects](library/collections#chainmap-objects) + [`ChainMap` Examples and Recipes](library/collections#chainmap-examples-and-recipes) * [`Counter` objects](library/collections#counter-objects) * [`deque` objects](library/collections#deque-objects) + [`deque` Recipes](library/collections#deque-recipes) * [`defaultdict` objects](library/collections#defaultdict-objects) + [`defaultdict` Examples](library/collections#defaultdict-examples) * [`namedtuple()` Factory Function for Tuples with Named Fields](library/collections#namedtuple-factory-function-for-tuples-with-named-fields) * [`OrderedDict` objects](library/collections#ordereddict-objects) + [`OrderedDict` Examples and Recipes](library/collections#ordereddict-examples-and-recipes) * [`UserDict` objects](library/collections#userdict-objects) * [`UserList` objects](library/collections#userlist-objects) * [`UserString` objects](library/collections#userstring-objects) - [`collections.abc` — Abstract Base Classes for Containers](library/collections.abc) * [Collections Abstract Base Classes](library/collections.abc#collections-abstract-base-classes) - [`heapq` — Heap queue algorithm](library/heapq) * [Basic Examples](library/heapq#basic-examples) * [Priority Queue Implementation Notes](library/heapq#priority-queue-implementation-notes) * [Theory](library/heapq#theory) - [`bisect` — Array bisection algorithm](library/bisect) * [Searching Sorted Lists](library/bisect#searching-sorted-lists) * [Other Examples](library/bisect#other-examples) - [`array` — Efficient arrays of numeric values](library/array) - [`weakref` — Weak references](library/weakref) * [Weak Reference Objects](library/weakref#weak-reference-objects) * [Example](library/weakref#example) * [Finalizer Objects](library/weakref#finalizer-objects) * [Comparing finalizers with `__del__()` methods](library/weakref#comparing-finalizers-with-del-methods) - [`types` — Dynamic type creation and names for built-in types](library/types) * [Dynamic Type Creation](library/types#dynamic-type-creation) * [Standard Interpreter Types](library/types#standard-interpreter-types) * [Additional Utility Classes and Functions](library/types#additional-utility-classes-and-functions) * [Coroutine Utility Functions](library/types#coroutine-utility-functions) - [`copy` — Shallow and deep copy operations](library/copy) - [`pprint` — Data pretty printer](library/pprint) * [PrettyPrinter Objects](library/pprint#prettyprinter-objects) * [Example](library/pprint#example) - [`reprlib` — Alternate `repr()` implementation](library/reprlib) * [Repr Objects](library/reprlib#repr-objects) * [Subclassing Repr Objects](library/reprlib#subclassing-repr-objects) - [`enum` — Support for enumerations](library/enum) * [Module Contents](library/enum#module-contents) * [Creating an Enum](library/enum#creating-an-enum) * [Programmatic access to enumeration members and their attributes](library/enum#programmatic-access-to-enumeration-members-and-their-attributes) * [Duplicating enum members and values](library/enum#duplicating-enum-members-and-values) * [Ensuring unique enumeration values](library/enum#ensuring-unique-enumeration-values) * [Using automatic values](library/enum#using-automatic-values) * [Iteration](library/enum#iteration) * [Comparisons](library/enum#comparisons) * [Allowed members and attributes of enumerations](library/enum#allowed-members-and-attributes-of-enumerations) * [Restricted Enum subclassing](library/enum#restricted-enum-subclassing) * [Pickling](library/enum#pickling) * [Functional API](library/enum#functional-api) * [Derived Enumerations](library/enum#derived-enumerations) + [IntEnum](library/enum#intenum) + [IntFlag](library/enum#intflag) + [Flag](library/enum#flag) + [Others](library/enum#others) * [When to use `__new__()` vs. `__init__()`](library/enum#when-to-use-new-vs-init) * [Interesting examples](library/enum#interesting-examples) + [Omitting values](library/enum#omitting-values) - [Using `auto`](library/enum#using-auto) - [Using `object`](library/enum#using-object) - [Using a descriptive string](library/enum#using-a-descriptive-string) - [Using a custom `__new__()`](library/enum#using-a-custom-new) + [OrderedEnum](library/enum#orderedenum) + [DuplicateFreeEnum](library/enum#duplicatefreeenum) + [Planet](library/enum#planet) + [TimePeriod](library/enum#timeperiod) * [How are Enums different?](library/enum#how-are-enums-different) + [Enum Classes](library/enum#enum-classes) + [Enum Members (aka instances)](library/enum#enum-members-aka-instances) + [Finer Points](library/enum#finer-points) - [Supported `__dunder__` names](library/enum#supported-dunder-names) - [Supported `_sunder_` names](library/enum#supported-sunder-names) - [\_Private\_\_names](library/enum#private-names) - [`Enum` member type](library/enum#enum-member-type) - [Boolean value of `Enum` classes and members](library/enum#boolean-value-of-enum-classes-and-members) - [`Enum` classes with methods](library/enum#enum-classes-with-methods) - [Combining members of `Flag`](library/enum#combining-members-of-flag) - [`graphlib` — Functionality to operate with graph-like structures](library/graphlib) * [Exceptions](library/graphlib#exceptions) + [Numeric and Mathematical Modules](library/numeric) - [`numbers` — Numeric abstract base classes](library/numbers) * [The numeric tower](library/numbers#the-numeric-tower) * [Notes for type implementors](library/numbers#notes-for-type-implementors) + [Adding More Numeric ABCs](library/numbers#adding-more-numeric-abcs) + [Implementing the arithmetic operations](library/numbers#implementing-the-arithmetic-operations) - [`math` — Mathematical functions](library/math) * [Number-theoretic and representation functions](library/math#number-theoretic-and-representation-functions) * [Power and logarithmic functions](library/math#power-and-logarithmic-functions) * [Trigonometric functions](library/math#trigonometric-functions) * [Angular conversion](library/math#angular-conversion) * [Hyperbolic functions](library/math#hyperbolic-functions) * [Special functions](library/math#special-functions) * [Constants](library/math#constants) - [`cmath` — Mathematical functions for complex numbers](library/cmath) * [Conversions to and from polar coordinates](library/cmath#conversions-to-and-from-polar-coordinates) * [Power and logarithmic functions](library/cmath#power-and-logarithmic-functions) * [Trigonometric functions](library/cmath#trigonometric-functions) * [Hyperbolic functions](library/cmath#hyperbolic-functions) * [Classification functions](library/cmath#classification-functions) * [Constants](library/cmath#constants) - [`decimal` — Decimal fixed point and floating point arithmetic](library/decimal) * [Quick-start Tutorial](library/decimal#quick-start-tutorial) * [Decimal objects](library/decimal#decimal-objects) + [Logical operands](library/decimal#logical-operands) * [Context objects](library/decimal#context-objects) * [Constants](library/decimal#constants) * [Rounding modes](library/decimal#rounding-modes) * [Signals](library/decimal#signals) * [Floating Point Notes](library/decimal#floating-point-notes) + [Mitigating round-off error with increased precision](library/decimal#mitigating-round-off-error-with-increased-precision) + [Special values](library/decimal#special-values) * [Working with threads](library/decimal#working-with-threads) * [Recipes](library/decimal#recipes) * [Decimal FAQ](library/decimal#decimal-faq) - [`fractions` — Rational numbers](library/fractions) - [`random` — Generate pseudo-random numbers](library/random) * [Bookkeeping functions](library/random#bookkeeping-functions) * [Functions for bytes](library/random#functions-for-bytes) * [Functions for integers](library/random#functions-for-integers) * [Functions for sequences](library/random#functions-for-sequences) * [Real-valued distributions](library/random#real-valued-distributions) * [Alternative Generator](library/random#alternative-generator) * [Notes on Reproducibility](library/random#notes-on-reproducibility) * [Examples](library/random#examples) * [Recipes](library/random#recipes) - [`statistics` — Mathematical statistics functions](library/statistics) * [Averages and measures of central location](library/statistics#averages-and-measures-of-central-location) * [Measures of spread](library/statistics#measures-of-spread) * [Function details](library/statistics#function-details) * [Exceptions](library/statistics#exceptions) * [`NormalDist` objects](library/statistics#normaldist-objects) + [`NormalDist` Examples and Recipes](library/statistics#normaldist-examples-and-recipes) + [Functional Programming Modules](library/functional) - [`itertools` — Functions creating iterators for efficient looping](library/itertools) * [Itertool functions](library/itertools#itertool-functions) * [Itertools Recipes](library/itertools#itertools-recipes) - [`functools` — Higher-order functions and operations on callable objects](library/functools) * [`partial` Objects](library/functools#partial-objects) - [`operator` — Standard operators as functions](library/operator) * [Mapping Operators to Functions](library/operator#mapping-operators-to-functions) * [In-place Operators](library/operator#in-place-operators) + [File and Directory Access](library/filesys) - [`pathlib` — Object-oriented filesystem paths](library/pathlib) * [Basic use](library/pathlib#basic-use) * [Pure paths](library/pathlib#pure-paths) + [General properties](library/pathlib#general-properties) + [Operators](library/pathlib#operators) + [Accessing individual parts](library/pathlib#accessing-individual-parts) + [Methods and properties](library/pathlib#methods-and-properties) * [Concrete paths](library/pathlib#concrete-paths) + [Methods](library/pathlib#methods) * [Correspondence to tools in the `os` module](library/pathlib#correspondence-to-tools-in-the-os-module) - [`os.path` — Common pathname manipulations](library/os.path) - [`fileinput` — Iterate over lines from multiple input streams](library/fileinput) - [`stat` — Interpreting `stat()` results](library/stat) - [`filecmp` — File and Directory Comparisons](library/filecmp) * [The `dircmp` class](library/filecmp#the-dircmp-class) - [`tempfile` — Generate temporary files and directories](library/tempfile) * [Examples](library/tempfile#examples) * [Deprecated functions and variables](library/tempfile#deprecated-functions-and-variables) - [`glob` — Unix style pathname pattern expansion](library/glob) - [`fnmatch` — Unix filename pattern matching](library/fnmatch) - [`linecache` — Random access to text lines](library/linecache) - [`shutil` — High-level file operations](library/shutil) * [Directory and files operations](library/shutil#directory-and-files-operations) + [Platform-dependent efficient copy operations](library/shutil#platform-dependent-efficient-copy-operations) + [copytree example](library/shutil#copytree-example) + [rmtree example](library/shutil#rmtree-example) * [Archiving operations](library/shutil#archiving-operations) + [Archiving example](library/shutil#archiving-example) + [Archiving example with base\_dir](library/shutil#archiving-example-with-base-dir) * [Querying the size of the output terminal](library/shutil#querying-the-size-of-the-output-terminal) + [Data Persistence](library/persistence) - [`pickle` — Python object serialization](library/pickle) * [Relationship to other Python modules](library/pickle#relationship-to-other-python-modules) + [Comparison with `marshal`](library/pickle#comparison-with-marshal) + [Comparison with `json`](library/pickle#comparison-with-json) * [Data stream format](library/pickle#data-stream-format) * [Module Interface](library/pickle#module-interface) * [What can be pickled and unpickled?](library/pickle#what-can-be-pickled-and-unpickled) * [Pickling Class Instances](library/pickle#pickling-class-instances) + [Persistence of External Objects](library/pickle#persistence-of-external-objects) + [Dispatch Tables](library/pickle#dispatch-tables) + [Handling Stateful Objects](library/pickle#handling-stateful-objects) * [Custom Reduction for Types, Functions, and Other Objects](library/pickle#custom-reduction-for-types-functions-and-other-objects) * [Out-of-band Buffers](library/pickle#out-of-band-buffers) + [Provider API](library/pickle#provider-api) + [Consumer API](library/pickle#consumer-api) + [Example](library/pickle#example) * [Restricting Globals](library/pickle#restricting-globals) * [Performance](library/pickle#performance) * [Examples](library/pickle#examples) - [`copyreg` — Register `pickle` support functions](library/copyreg) * [Example](library/copyreg#example) - [`shelve` — Python object persistence](library/shelve) * [Restrictions](library/shelve#restrictions) * [Example](library/shelve#example) - [`marshal` — Internal Python object serialization](library/marshal) - [`dbm` — Interfaces to Unix “databases”](library/dbm) * [`dbm.gnu` — GNU’s reinterpretation of dbm](library/dbm#module-dbm.gnu) * [`dbm.ndbm` — Interface based on ndbm](library/dbm#module-dbm.ndbm) * [`dbm.dumb` — Portable DBM implementation](library/dbm#module-dbm.dumb) - [`sqlite3` — DB-API 2.0 interface for SQLite databases](library/sqlite3) * [Module functions and constants](library/sqlite3#module-functions-and-constants) * [Connection Objects](library/sqlite3#connection-objects) * [Cursor Objects](library/sqlite3#cursor-objects) * [Row Objects](library/sqlite3#row-objects) * [Exceptions](library/sqlite3#exceptions) * [SQLite and Python types](library/sqlite3#sqlite-and-python-types) + [Introduction](library/sqlite3#introduction) + [Using adapters to store additional Python types in SQLite databases](library/sqlite3#using-adapters-to-store-additional-python-types-in-sqlite-databases) - [Letting your object adapt itself](library/sqlite3#letting-your-object-adapt-itself) - [Registering an adapter callable](library/sqlite3#registering-an-adapter-callable) + [Converting SQLite values to custom Python types](library/sqlite3#converting-sqlite-values-to-custom-python-types) + [Default adapters and converters](library/sqlite3#default-adapters-and-converters) * [Controlling Transactions](library/sqlite3#controlling-transactions) * [Using `sqlite3` efficiently](library/sqlite3#using-sqlite3-efficiently) + [Using shortcut methods](library/sqlite3#using-shortcut-methods) + [Accessing columns by name instead of by index](library/sqlite3#accessing-columns-by-name-instead-of-by-index) + [Using the connection as a context manager](library/sqlite3#using-the-connection-as-a-context-manager) + [Data Compression and Archiving](library/archiving) - [`zlib` — Compression compatible with **gzip**](library/zlib) - [`gzip` — Support for **gzip** files](library/gzip) * [Examples of usage](library/gzip#examples-of-usage) * [Command Line Interface](library/gzip#command-line-interface) + [Command line options](library/gzip#command-line-options) - [`bz2` — Support for **bzip2** compression](library/bz2) * [(De)compression of files](library/bz2#de-compression-of-files) * [Incremental (de)compression](library/bz2#incremental-de-compression) * [One-shot (de)compression](library/bz2#one-shot-de-compression) * [Examples of usage](library/bz2#examples-of-usage) - [`lzma` — Compression using the LZMA algorithm](library/lzma) * [Reading and writing compressed files](library/lzma#reading-and-writing-compressed-files) * [Compressing and decompressing data in memory](library/lzma#compressing-and-decompressing-data-in-memory) * [Miscellaneous](library/lzma#miscellaneous) * [Specifying custom filter chains](library/lzma#specifying-custom-filter-chains) * [Examples](library/lzma#examples) - [`zipfile` — Work with ZIP archives](library/zipfile) * [ZipFile Objects](library/zipfile#zipfile-objects) * [Path Objects](library/zipfile#path-objects) * [PyZipFile Objects](library/zipfile#pyzipfile-objects) * [ZipInfo Objects](library/zipfile#zipinfo-objects) * [Command-Line Interface](library/zipfile#command-line-interface) + [Command-line options](library/zipfile#command-line-options) * [Decompression pitfalls](library/zipfile#decompression-pitfalls) + [From file itself](library/zipfile#from-file-itself) + [File System limitations](library/zipfile#file-system-limitations) + [Resources limitations](library/zipfile#resources-limitations) + [Interruption](library/zipfile#interruption) + [Default behaviors of extraction](library/zipfile#default-behaviors-of-extraction) - [`tarfile` — Read and write tar archive files](library/tarfile) * [TarFile Objects](library/tarfile#tarfile-objects) * [TarInfo Objects](library/tarfile#tarinfo-objects) * [Command-Line Interface](library/tarfile#command-line-interface) + [Command-line options](library/tarfile#command-line-options) * [Examples](library/tarfile#examples) * [Supported tar formats](library/tarfile#supported-tar-formats) * [Unicode issues](library/tarfile#unicode-issues) + [File Formats](library/fileformats) - [`csv` — CSV File Reading and Writing](library/csv) * [Module Contents](library/csv#module-contents) * [Dialects and Formatting Parameters](library/csv#dialects-and-formatting-parameters) * [Reader Objects](library/csv#reader-objects) * [Writer Objects](library/csv#writer-objects) * [Examples](library/csv#examples) - [`configparser` — Configuration file parser](library/configparser) * [Quick Start](library/configparser#quick-start) * [Supported Datatypes](library/configparser#supported-datatypes) * [Fallback Values](library/configparser#fallback-values) * [Supported INI File Structure](library/configparser#supported-ini-file-structure) * [Interpolation of values](library/configparser#interpolation-of-values) * [Mapping Protocol Access](library/configparser#mapping-protocol-access) * [Customizing Parser Behaviour](library/configparser#customizing-parser-behaviour) * [Legacy API Examples](library/configparser#legacy-api-examples) * [ConfigParser Objects](library/configparser#configparser-objects) * [RawConfigParser Objects](library/configparser#rawconfigparser-objects) * [Exceptions](library/configparser#exceptions) - [`netrc` — netrc file processing](library/netrc) * [netrc Objects](library/netrc#netrc-objects) - [`plistlib` — Generate and parse Apple `.plist` files](library/plistlib) * [Examples](library/plistlib#examples) + [Cryptographic Services](library/crypto) - [`hashlib` — Secure hashes and message digests](library/hashlib) * [Hash algorithms](library/hashlib#hash-algorithms) * [SHAKE variable length digests](library/hashlib#shake-variable-length-digests) * [Key derivation](library/hashlib#key-derivation) * [BLAKE2](library/hashlib#blake2) + [Creating hash objects](library/hashlib#creating-hash-objects) + [Constants](library/hashlib#constants) + [Examples](library/hashlib#examples) - [Simple hashing](library/hashlib#simple-hashing) - [Using different digest sizes](library/hashlib#using-different-digest-sizes) - [Keyed hashing](library/hashlib#keyed-hashing) - [Randomized hashing](library/hashlib#randomized-hashing) - [Personalization](library/hashlib#personalization) - [Tree mode](library/hashlib#tree-mode) + [Credits](library/hashlib#credits) - [`hmac` — Keyed-Hashing for Message Authentication](library/hmac) - [`secrets` — Generate secure random numbers for managing secrets](library/secrets) * [Random numbers](library/secrets#random-numbers) * [Generating tokens](library/secrets#generating-tokens) + [How many bytes should tokens use?](library/secrets#how-many-bytes-should-tokens-use) * [Other functions](library/secrets#other-functions) * [Recipes and best practices](library/secrets#recipes-and-best-practices) + [Generic Operating System Services](library/allos) - [`os` — Miscellaneous operating system interfaces](library/os) * [File Names, Command Line Arguments, and Environment Variables](library/os#file-names-command-line-arguments-and-environment-variables) * [Process Parameters](library/os#process-parameters) * [File Object Creation](library/os#file-object-creation) * [File Descriptor Operations](library/os#file-descriptor-operations) + [Querying the size of a terminal](library/os#querying-the-size-of-a-terminal) + [Inheritance of File Descriptors](library/os#inheritance-of-file-descriptors) * [Files and Directories](library/os#files-and-directories) + [Linux extended attributes](library/os#linux-extended-attributes) * [Process Management](library/os#process-management) * [Interface to the scheduler](library/os#interface-to-the-scheduler) * [Miscellaneous System Information](library/os#miscellaneous-system-information) * [Random numbers](library/os#random-numbers) - [`io` — Core tools for working with streams](library/io) * [Overview](library/io#overview) + [Text I/O](library/io#text-i-o) + [Binary I/O](library/io#binary-i-o) + [Raw I/O](library/io#raw-i-o) * [High-level Module Interface](library/io#high-level-module-interface) * [Class hierarchy](library/io#class-hierarchy) + [I/O Base Classes](library/io#i-o-base-classes) + [Raw File I/O](library/io#raw-file-i-o) + [Buffered Streams](library/io#buffered-streams) + [Text I/O](library/io#id1) * [Performance](library/io#performance) + [Binary I/O](library/io#id2) + [Text I/O](library/io#id3) + [Multi-threading](library/io#multi-threading) + [Reentrancy](library/io#reentrancy) - [`time` — Time access and conversions](library/time) * [Functions](library/time#functions) * [Clock ID Constants](library/time#clock-id-constants) * [Timezone Constants](library/time#timezone-constants) - [`argparse` — Parser for command-line options, arguments and sub-commands](library/argparse) * [Example](library/argparse#example) + [Creating a parser](library/argparse#creating-a-parser) + [Adding arguments](library/argparse#adding-arguments) + [Parsing arguments](library/argparse#parsing-arguments) * [ArgumentParser objects](library/argparse#argumentparser-objects) + [prog](library/argparse#prog) + [usage](library/argparse#usage) + [description](library/argparse#description) + [epilog](library/argparse#epilog) + [parents](library/argparse#parents) + [formatter\_class](library/argparse#formatter-class) + [prefix\_chars](library/argparse#prefix-chars) + [fromfile\_prefix\_chars](library/argparse#fromfile-prefix-chars) + [argument\_default](library/argparse#argument-default) + [allow\_abbrev](library/argparse#allow-abbrev) + [conflict\_handler](library/argparse#conflict-handler) + [add\_help](library/argparse#add-help) + [exit\_on\_error](library/argparse#exit-on-error) * [The add\_argument() method](library/argparse#the-add-argument-method) + [name or flags](library/argparse#name-or-flags) + [action](library/argparse#action) + [nargs](library/argparse#nargs) + [const](library/argparse#const) + [default](library/argparse#default) + [type](library/argparse#type) + [choices](library/argparse#choices) + [required](library/argparse#required) + [help](library/argparse#help) + [metavar](library/argparse#metavar) + [dest](library/argparse#dest) + [Action classes](library/argparse#action-classes) * [The parse\_args() method](library/argparse#the-parse-args-method) + [Option value syntax](library/argparse#option-value-syntax) + [Invalid arguments](library/argparse#invalid-arguments) + [Arguments containing `-`](library/argparse#arguments-containing) + [Argument abbreviations (prefix matching)](library/argparse#argument-abbreviations-prefix-matching) + [Beyond `sys.argv`](library/argparse#beyond-sys-argv) + [The Namespace object](library/argparse#the-namespace-object) * [Other utilities](library/argparse#other-utilities) + [Sub-commands](library/argparse#sub-commands) + [FileType objects](library/argparse#filetype-objects) + [Argument groups](library/argparse#argument-groups) + [Mutual exclusion](library/argparse#mutual-exclusion) + [Parser defaults](library/argparse#parser-defaults) + [Printing help](library/argparse#printing-help) + [Partial parsing](library/argparse#partial-parsing) + [Customizing file parsing](library/argparse#customizing-file-parsing) + [Exiting methods](library/argparse#exiting-methods) + [Intermixed parsing](library/argparse#intermixed-parsing) * [Upgrading optparse code](library/argparse#upgrading-optparse-code) - [`getopt` — C-style parser for command line options](library/getopt) - [`logging` — Logging facility for Python](library/logging) * [Logger Objects](library/logging#logger-objects) * [Logging Levels](library/logging#logging-levels) * [Handler Objects](library/logging#handler-objects) * [Formatter Objects](library/logging#formatter-objects) * [Filter Objects](library/logging#filter-objects) * [LogRecord Objects](library/logging#logrecord-objects) * [LogRecord attributes](library/logging#logrecord-attributes) * [LoggerAdapter Objects](library/logging#loggeradapter-objects) * [Thread Safety](library/logging#thread-safety) * [Module-Level Functions](library/logging#module-level-functions) * [Module-Level Attributes](library/logging#module-level-attributes) * [Integration with the warnings module](library/logging#integration-with-the-warnings-module) - [`logging.config` — Logging configuration](library/logging.config) * [Configuration functions](library/logging.config#configuration-functions) * [Security considerations](library/logging.config#security-considerations) * [Configuration dictionary schema](library/logging.config#configuration-dictionary-schema) + [Dictionary Schema Details](library/logging.config#dictionary-schema-details) + [Incremental Configuration](library/logging.config#incremental-configuration) + [Object connections](library/logging.config#object-connections) + [User-defined objects](library/logging.config#user-defined-objects) + [Access to external objects](library/logging.config#access-to-external-objects) + [Access to internal objects](library/logging.config#access-to-internal-objects) + [Import resolution and custom importers](library/logging.config#import-resolution-and-custom-importers) * [Configuration file format](library/logging.config#configuration-file-format) - [`logging.handlers` — Logging handlers](library/logging.handlers) * [StreamHandler](library/logging.handlers#streamhandler) * [FileHandler](library/logging.handlers#filehandler) * [NullHandler](library/logging.handlers#nullhandler) * [WatchedFileHandler](library/logging.handlers#watchedfilehandler) * [BaseRotatingHandler](library/logging.handlers#baserotatinghandler) * [RotatingFileHandler](library/logging.handlers#rotatingfilehandler) * [TimedRotatingFileHandler](library/logging.handlers#timedrotatingfilehandler) * [SocketHandler](library/logging.handlers#sockethandler) * [DatagramHandler](library/logging.handlers#datagramhandler) * [SysLogHandler](library/logging.handlers#sysloghandler) * [NTEventLogHandler](library/logging.handlers#nteventloghandler) * [SMTPHandler](library/logging.handlers#smtphandler) * [MemoryHandler](library/logging.handlers#memoryhandler) * [HTTPHandler](library/logging.handlers#httphandler) * [QueueHandler](library/logging.handlers#queuehandler) * [QueueListener](library/logging.handlers#queuelistener) - [`getpass` — Portable password input](library/getpass) - [`curses` — Terminal handling for character-cell displays](library/curses) * [Functions](library/curses#functions) * [Window Objects](library/curses#window-objects) * [Constants](library/curses#constants) - [`curses.textpad` — Text input widget for curses programs](library/curses#module-curses.textpad) * [Textbox objects](library/curses#textbox-objects) - [`curses.ascii` — Utilities for ASCII characters](library/curses.ascii) - [`curses.panel` — A panel stack extension for curses](library/curses.panel) * [Functions](library/curses.panel#functions) * [Panel Objects](library/curses.panel#panel-objects) - [`platform` — Access to underlying platform’s identifying data](library/platform) * [Cross Platform](library/platform#cross-platform) * [Java Platform](library/platform#java-platform) * [Windows Platform](library/platform#windows-platform) * [macOS Platform](library/platform#macos-platform) * [Unix Platforms](library/platform#unix-platforms) - [`errno` — Standard errno system symbols](library/errno) - [`ctypes` — A foreign function library for Python](library/ctypes) * [ctypes tutorial](library/ctypes#ctypes-tutorial) + [Loading dynamic link libraries](library/ctypes#loading-dynamic-link-libraries) + [Accessing functions from loaded dlls](library/ctypes#accessing-functions-from-loaded-dlls) + [Calling functions](library/ctypes#calling-functions) + [Fundamental data types](library/ctypes#fundamental-data-types) + [Calling functions, continued](library/ctypes#calling-functions-continued) + [Calling functions with your own custom data types](library/ctypes#calling-functions-with-your-own-custom-data-types) + [Specifying the required argument types (function prototypes)](library/ctypes#specifying-the-required-argument-types-function-prototypes) + [Return types](library/ctypes#return-types) + [Passing pointers (or: passing parameters by reference)](library/ctypes#passing-pointers-or-passing-parameters-by-reference) + [Structures and unions](library/ctypes#structures-and-unions) + [Structure/union alignment and byte order](library/ctypes#structure-union-alignment-and-byte-order) + [Bit fields in structures and unions](library/ctypes#bit-fields-in-structures-and-unions) + [Arrays](library/ctypes#arrays) + [Pointers](library/ctypes#pointers) + [Type conversions](library/ctypes#type-conversions) + [Incomplete Types](library/ctypes#incomplete-types) + [Callback functions](library/ctypes#callback-functions) + [Accessing values exported from dlls](library/ctypes#accessing-values-exported-from-dlls) + [Surprises](library/ctypes#surprises) + [Variable-sized data types](library/ctypes#variable-sized-data-types) * [ctypes reference](library/ctypes#ctypes-reference) + [Finding shared libraries](library/ctypes#finding-shared-libraries) + [Loading shared libraries](library/ctypes#loading-shared-libraries) + [Foreign functions](library/ctypes#foreign-functions) + [Function prototypes](library/ctypes#function-prototypes) + [Utility functions](library/ctypes#utility-functions) + [Data types](library/ctypes#data-types) + [Fundamental data types](library/ctypes#ctypes-fundamental-data-types-2) + [Structured data types](library/ctypes#structured-data-types) + [Arrays and pointers](library/ctypes#arrays-and-pointers) + [Concurrent Execution](library/concurrency) - [`threading` — Thread-based parallelism](library/threading) * [Thread-Local Data](library/threading#thread-local-data) * [Thread Objects](library/threading#thread-objects) * [Lock Objects](library/threading#lock-objects) * [RLock Objects](library/threading#rlock-objects) * [Condition Objects](library/threading#condition-objects) * [Semaphore Objects](library/threading#semaphore-objects) + [`Semaphore` Example](library/threading#semaphore-example) * [Event Objects](library/threading#event-objects) * [Timer Objects](library/threading#timer-objects) * [Barrier Objects](library/threading#barrier-objects) * [Using locks, conditions, and semaphores in the `with` statement](library/threading#using-locks-conditions-and-semaphores-in-the-with-statement) - [`multiprocessing` — Process-based parallelism](library/multiprocessing) * [Introduction](library/multiprocessing#introduction) + [The `Process` class](library/multiprocessing#the-process-class) + [Contexts and start methods](library/multiprocessing#contexts-and-start-methods) + [Exchanging objects between processes](library/multiprocessing#exchanging-objects-between-processes) + [Synchronization between processes](library/multiprocessing#synchronization-between-processes) + [Sharing state between processes](library/multiprocessing#sharing-state-between-processes) + [Using a pool of workers](library/multiprocessing#using-a-pool-of-workers) * [Reference](library/multiprocessing#reference) + [`Process` and exceptions](library/multiprocessing#process-and-exceptions) + [Pipes and Queues](library/multiprocessing#pipes-and-queues) + [Miscellaneous](library/multiprocessing#miscellaneous) + [Connection Objects](library/multiprocessing#connection-objects) + [Synchronization primitives](library/multiprocessing#synchronization-primitives) + [Shared `ctypes` Objects](library/multiprocessing#shared-ctypes-objects) - [The `multiprocessing.sharedctypes` module](library/multiprocessing#module-multiprocessing.sharedctypes) + [Managers](library/multiprocessing#managers) - [Customized managers](library/multiprocessing#customized-managers) - [Using a remote manager](library/multiprocessing#using-a-remote-manager) + [Proxy Objects](library/multiprocessing#proxy-objects) - [Cleanup](library/multiprocessing#cleanup) + [Process Pools](library/multiprocessing#module-multiprocessing.pool) + [Listeners and Clients](library/multiprocessing#module-multiprocessing.connection) - [Address Formats](library/multiprocessing#address-formats) + [Authentication keys](library/multiprocessing#authentication-keys) + [Logging](library/multiprocessing#logging) + [The `multiprocessing.dummy` module](library/multiprocessing#module-multiprocessing.dummy) * [Programming guidelines](library/multiprocessing#programming-guidelines) + [All start methods](library/multiprocessing#all-start-methods) + [The spawn and forkserver start methods](library/multiprocessing#the-spawn-and-forkserver-start-methods) * [Examples](library/multiprocessing#examples) - [`multiprocessing.shared_memory` — Provides shared memory for direct access across processes](library/multiprocessing.shared_memory) - [The `concurrent` package](library/concurrent) - [`concurrent.futures` — Launching parallel tasks](library/concurrent.futures) * [Executor Objects](library/concurrent.futures#executor-objects) * [ThreadPoolExecutor](library/concurrent.futures#threadpoolexecutor) + [ThreadPoolExecutor Example](library/concurrent.futures#threadpoolexecutor-example) * [ProcessPoolExecutor](library/concurrent.futures#processpoolexecutor) + [ProcessPoolExecutor Example](library/concurrent.futures#processpoolexecutor-example) * [Future Objects](library/concurrent.futures#future-objects) * [Module Functions](library/concurrent.futures#module-functions) * [Exception classes](library/concurrent.futures#exception-classes) - [`subprocess` — Subprocess management](library/subprocess) * [Using the `subprocess` Module](library/subprocess#using-the-subprocess-module) + [Frequently Used Arguments](library/subprocess#frequently-used-arguments) + [Popen Constructor](library/subprocess#popen-constructor) + [Exceptions](library/subprocess#exceptions) * [Security Considerations](library/subprocess#security-considerations) * [Popen Objects](library/subprocess#popen-objects) * [Windows Popen Helpers](library/subprocess#windows-popen-helpers) + [Windows Constants](library/subprocess#windows-constants) * [Older high-level API](library/subprocess#older-high-level-api) * [Replacing Older Functions with the `subprocess` Module](library/subprocess#replacing-older-functions-with-the-subprocess-module) + [Replacing **/bin/sh** shell command substitution](library/subprocess#replacing-bin-sh-shell-command-substitution) + [Replacing shell pipeline](library/subprocess#replacing-shell-pipeline) + [Replacing `os.system()`](library/subprocess#replacing-os-system) + [Replacing the `os.spawn` family](library/subprocess#replacing-the-os-spawn-family) + [Replacing `os.popen()`, `os.popen2()`, `os.popen3()`](library/subprocess#replacing-os-popen-os-popen2-os-popen3) + [Replacing functions from the `popen2` module](library/subprocess#replacing-functions-from-the-popen2-module) * [Legacy Shell Invocation Functions](library/subprocess#legacy-shell-invocation-functions) * [Notes](library/subprocess#notes) + [Converting an argument sequence to a string on Windows](library/subprocess#converting-an-argument-sequence-to-a-string-on-windows) - [`sched` — Event scheduler](library/sched) * [Scheduler Objects](library/sched#scheduler-objects) - [`queue` — A synchronized queue class](library/queue) * [Queue Objects](library/queue#queue-objects) * [SimpleQueue Objects](library/queue#simplequeue-objects) - [`contextvars` — Context Variables](library/contextvars) * [Context Variables](library/contextvars#context-variables) * [Manual Context Management](library/contextvars#manual-context-management) * [asyncio support](library/contextvars#asyncio-support) - [`_thread` — Low-level threading API](library/_thread) + [Networking and Interprocess Communication](library/ipc) - [`asyncio` — Asynchronous I/O](library/asyncio) * [Coroutines and Tasks](library/asyncio-task) + [Coroutines](library/asyncio-task#coroutines) + [Awaitables](library/asyncio-task#awaitables) + [Running an asyncio Program](library/asyncio-task#running-an-asyncio-program) + [Creating Tasks](library/asyncio-task#creating-tasks) + [Sleeping](library/asyncio-task#sleeping) + [Running Tasks Concurrently](library/asyncio-task#running-tasks-concurrently) + [Shielding From Cancellation](library/asyncio-task#shielding-from-cancellation) + [Timeouts](library/asyncio-task#timeouts) + [Waiting Primitives](library/asyncio-task#waiting-primitives) + [Running in Threads](library/asyncio-task#running-in-threads) + [Scheduling From Other Threads](library/asyncio-task#scheduling-from-other-threads) + [Introspection](library/asyncio-task#introspection) + [Task Object](library/asyncio-task#task-object) + [Generator-based Coroutines](library/asyncio-task#generator-based-coroutines) * [Streams](library/asyncio-stream) + [StreamReader](library/asyncio-stream#streamreader) + [StreamWriter](library/asyncio-stream#streamwriter) + [Examples](library/asyncio-stream#examples) - [TCP echo client using streams](library/asyncio-stream#tcp-echo-client-using-streams) - [TCP echo server using streams](library/asyncio-stream#tcp-echo-server-using-streams) - [Get HTTP headers](library/asyncio-stream#get-http-headers) - [Register an open socket to wait for data using streams](library/asyncio-stream#register-an-open-socket-to-wait-for-data-using-streams) * [Synchronization Primitives](library/asyncio-sync) + [Lock](library/asyncio-sync#lock) + [Event](library/asyncio-sync#event) + [Condition](library/asyncio-sync#condition) + [Semaphore](library/asyncio-sync#semaphore) + [BoundedSemaphore](library/asyncio-sync#boundedsemaphore) * [Subprocesses](library/asyncio-subprocess) + [Creating Subprocesses](library/asyncio-subprocess#creating-subprocesses) + [Constants](library/asyncio-subprocess#constants) + [Interacting with Subprocesses](library/asyncio-subprocess#interacting-with-subprocesses) - [Subprocess and Threads](library/asyncio-subprocess#subprocess-and-threads) - [Examples](library/asyncio-subprocess#examples) * [Queues](library/asyncio-queue) + [Queue](library/asyncio-queue#queue) + [Priority Queue](library/asyncio-queue#priority-queue) + [LIFO Queue](library/asyncio-queue#lifo-queue) + [Exceptions](library/asyncio-queue#exceptions) + [Examples](library/asyncio-queue#examples) * [Exceptions](library/asyncio-exceptions) * [Event Loop](library/asyncio-eventloop) + [Event Loop Methods](library/asyncio-eventloop#event-loop-methods) - [Running and stopping the loop](library/asyncio-eventloop#running-and-stopping-the-loop) - [Scheduling callbacks](library/asyncio-eventloop#scheduling-callbacks) - [Scheduling delayed callbacks](library/asyncio-eventloop#scheduling-delayed-callbacks) - [Creating Futures and Tasks](library/asyncio-eventloop#creating-futures-and-tasks) - [Opening network connections](library/asyncio-eventloop#opening-network-connections) - [Creating network servers](library/asyncio-eventloop#creating-network-servers) - [Transferring files](library/asyncio-eventloop#transferring-files) - [TLS Upgrade](library/asyncio-eventloop#tls-upgrade) - [Watching file descriptors](library/asyncio-eventloop#watching-file-descriptors) - [Working with socket objects directly](library/asyncio-eventloop#working-with-socket-objects-directly) - [DNS](library/asyncio-eventloop#dns) - [Working with pipes](library/asyncio-eventloop#working-with-pipes) - [Unix signals](library/asyncio-eventloop#unix-signals) - [Executing code in thread or process pools](library/asyncio-eventloop#executing-code-in-thread-or-process-pools) - [Error Handling API](library/asyncio-eventloop#error-handling-api) - [Enabling debug mode](library/asyncio-eventloop#enabling-debug-mode) - [Running Subprocesses](library/asyncio-eventloop#running-subprocesses) + [Callback Handles](library/asyncio-eventloop#callback-handles) + [Server Objects](library/asyncio-eventloop#server-objects) + [Event Loop Implementations](library/asyncio-eventloop#event-loop-implementations) + [Examples](library/asyncio-eventloop#examples) - [Hello World with call\_soon()](library/asyncio-eventloop#hello-world-with-call-soon) - [Display the current date with call\_later()](library/asyncio-eventloop#display-the-current-date-with-call-later) - [Watch a file descriptor for read events](library/asyncio-eventloop#watch-a-file-descriptor-for-read-events) - [Set signal handlers for SIGINT and SIGTERM](library/asyncio-eventloop#set-signal-handlers-for-sigint-and-sigterm) * [Futures](library/asyncio-future) + [Future Functions](library/asyncio-future#future-functions) + [Future Object](library/asyncio-future#future-object) * [Transports and Protocols](library/asyncio-protocol) + [Transports](library/asyncio-protocol#transports) - [Transports Hierarchy](library/asyncio-protocol#transports-hierarchy) - [Base Transport](library/asyncio-protocol#base-transport) - [Read-only Transports](library/asyncio-protocol#read-only-transports) - [Write-only Transports](library/asyncio-protocol#write-only-transports) - [Datagram Transports](library/asyncio-protocol#datagram-transports) - [Subprocess Transports](library/asyncio-protocol#subprocess-transports) + [Protocols](library/asyncio-protocol#protocols) - [Base Protocols](library/asyncio-protocol#base-protocols) - [Base Protocol](library/asyncio-protocol#base-protocol) - [Streaming Protocols](library/asyncio-protocol#streaming-protocols) - [Buffered Streaming Protocols](library/asyncio-protocol#buffered-streaming-protocols) - [Datagram Protocols](library/asyncio-protocol#datagram-protocols) - [Subprocess Protocols](library/asyncio-protocol#subprocess-protocols) + [Examples](library/asyncio-protocol#examples) - [TCP Echo Server](library/asyncio-protocol#tcp-echo-server) - [TCP Echo Client](library/asyncio-protocol#tcp-echo-client) - [UDP Echo Server](library/asyncio-protocol#udp-echo-server) - [UDP Echo Client](library/asyncio-protocol#udp-echo-client) - [Connecting Existing Sockets](library/asyncio-protocol#connecting-existing-sockets) - [loop.subprocess\_exec() and SubprocessProtocol](library/asyncio-protocol#loop-subprocess-exec-and-subprocessprotocol) * [Policies](library/asyncio-policy) + [Getting and Setting the Policy](library/asyncio-policy#getting-and-setting-the-policy) + [Policy Objects](library/asyncio-policy#policy-objects) + [Process Watchers](library/asyncio-policy#process-watchers) + [Custom Policies](library/asyncio-policy#custom-policies) * [Platform Support](library/asyncio-platforms) + [All Platforms](library/asyncio-platforms#all-platforms) + [Windows](library/asyncio-platforms#windows) - [Subprocess Support on Windows](library/asyncio-platforms#subprocess-support-on-windows) + [macOS](library/asyncio-platforms#macos) * [High-level API Index](library/asyncio-api-index) + [Tasks](library/asyncio-api-index#tasks) + [Queues](library/asyncio-api-index#queues) + [Subprocesses](library/asyncio-api-index#subprocesses) + [Streams](library/asyncio-api-index#streams) + [Synchronization](library/asyncio-api-index#synchronization) + [Exceptions](library/asyncio-api-index#exceptions) * [Low-level API Index](library/asyncio-llapi-index) + [Obtaining the Event Loop](library/asyncio-llapi-index#obtaining-the-event-loop) + [Event Loop Methods](library/asyncio-llapi-index#event-loop-methods) + [Transports](library/asyncio-llapi-index#transports) + [Protocols](library/asyncio-llapi-index#protocols) + [Event Loop Policies](library/asyncio-llapi-index#event-loop-policies) * [Developing with asyncio](library/asyncio-dev) + [Debug Mode](library/asyncio-dev#debug-mode) + [Concurrency and Multithreading](library/asyncio-dev#concurrency-and-multithreading) + [Running Blocking Code](library/asyncio-dev#running-blocking-code) + [Logging](library/asyncio-dev#logging) + [Detect never-awaited coroutines](library/asyncio-dev#detect-never-awaited-coroutines) + [Detect never-retrieved exceptions](library/asyncio-dev#detect-never-retrieved-exceptions) - [`socket` — Low-level networking interface](library/socket) * [Socket families](library/socket#socket-families) * [Module contents](library/socket#module-contents) + [Exceptions](library/socket#exceptions) + [Constants](library/socket#constants) + [Functions](library/socket#functions) - [Creating sockets](library/socket#creating-sockets) - [Other functions](library/socket#other-functions) * [Socket Objects](library/socket#socket-objects) * [Notes on socket timeouts](library/socket#notes-on-socket-timeouts) + [Timeouts and the `connect` method](library/socket#timeouts-and-the-connect-method) + [Timeouts and the `accept` method](library/socket#timeouts-and-the-accept-method) * [Example](library/socket#example) - [`ssl` — TLS/SSL wrapper for socket objects](library/ssl) * [Functions, Constants, and Exceptions](library/ssl#functions-constants-and-exceptions) + [Socket creation](library/ssl#socket-creation) + [Context creation](library/ssl#context-creation) + [Exceptions](library/ssl#exceptions) + [Random generation](library/ssl#random-generation) + [Certificate handling](library/ssl#certificate-handling) + [Constants](library/ssl#constants) * [SSL Sockets](library/ssl#ssl-sockets) * [SSL Contexts](library/ssl#ssl-contexts) * [Certificates](library/ssl#certificates) + [Certificate chains](library/ssl#certificate-chains) + [CA certificates](library/ssl#ca-certificates) + [Combined key and certificate](library/ssl#combined-key-and-certificate) + [Self-signed certificates](library/ssl#self-signed-certificates) * [Examples](library/ssl#examples) + [Testing for SSL support](library/ssl#testing-for-ssl-support) + [Client-side operation](library/ssl#client-side-operation) + [Server-side operation](library/ssl#server-side-operation) * [Notes on non-blocking sockets](library/ssl#notes-on-non-blocking-sockets) * [Memory BIO Support](library/ssl#memory-bio-support) * [SSL session](library/ssl#ssl-session) * [Security considerations](library/ssl#security-considerations) + [Best defaults](library/ssl#best-defaults) + [Manual settings](library/ssl#manual-settings) - [Verifying certificates](library/ssl#verifying-certificates) - [Protocol versions](library/ssl#protocol-versions) - [Cipher selection](library/ssl#cipher-selection) + [Multi-processing](library/ssl#multi-processing) * [TLS 1.3](library/ssl#tls-1-3) * [LibreSSL support](library/ssl#libressl-support) - [`select` — Waiting for I/O completion](library/select) * [`/dev/poll` Polling Objects](library/select#dev-poll-polling-objects) * [Edge and Level Trigger Polling (epoll) Objects](library/select#edge-and-level-trigger-polling-epoll-objects) * [Polling Objects](library/select#polling-objects) * [Kqueue Objects](library/select#kqueue-objects) * [Kevent Objects](library/select#kevent-objects) - [`selectors` — High-level I/O multiplexing](library/selectors) * [Introduction](library/selectors#introduction) * [Classes](library/selectors#classes) * [Examples](library/selectors#examples) - [`signal` — Set handlers for asynchronous events](library/signal) * [General rules](library/signal#general-rules) + [Execution of Python signal handlers](library/signal#execution-of-python-signal-handlers) + [Signals and threads](library/signal#signals-and-threads) * [Module contents](library/signal#module-contents) * [Example](library/signal#example) * [Note on SIGPIPE](library/signal#note-on-sigpipe) * [Note on Signal Handlers and Exceptions](library/signal#note-on-signal-handlers-and-exceptions) - [`mmap` — Memory-mapped file support](library/mmap) * [MADV\_\* Constants](library/mmap#madv-constants) + [Internet Data Handling](library/netdata) - [`email` — An email and MIME handling package](library/email) * [`email.message`: Representing an email message](library/email.message) * [`email.parser`: Parsing email messages](library/email.parser) + [FeedParser API](library/email.parser#feedparser-api) + [Parser API](library/email.parser#parser-api) + [Additional notes](library/email.parser#additional-notes) * [`email.generator`: Generating MIME documents](library/email.generator) * [`email.policy`: Policy Objects](library/email.policy) * [`email.errors`: Exception and Defect classes](library/email.errors) * [`email.headerregistry`: Custom Header Objects](library/email.headerregistry) * [`email.contentmanager`: Managing MIME Content](library/email.contentmanager) + [Content Manager Instances](library/email.contentmanager#content-manager-instances) * [`email`: Examples](library/email.examples) * [`email.message.Message`: Representing an email message using the `compat32` API](library/email.compat32-message) * [`email.mime`: Creating email and MIME objects from scratch](library/email.mime) * [`email.header`: Internationalized headers](library/email.header) * [`email.charset`: Representing character sets](library/email.charset) * [`email.encoders`: Encoders](library/email.encoders) * [`email.utils`: Miscellaneous utilities](library/email.utils) * [`email.iterators`: Iterators](library/email.iterators) - [`json` — JSON encoder and decoder](library/json) * [Basic Usage](library/json#basic-usage) * [Encoders and Decoders](library/json#encoders-and-decoders) * [Exceptions](library/json#exceptions) * [Standard Compliance and Interoperability](library/json#standard-compliance-and-interoperability) + [Character Encodings](library/json#character-encodings) + [Infinite and NaN Number Values](library/json#infinite-and-nan-number-values) + [Repeated Names Within an Object](library/json#repeated-names-within-an-object) + [Top-level Non-Object, Non-Array Values](library/json#top-level-non-object-non-array-values) + [Implementation Limitations](library/json#implementation-limitations) * [Command Line Interface](library/json#module-json.tool) + [Command line options](library/json#command-line-options) - [`mailbox` — Manipulate mailboxes in various formats](library/mailbox) * [`Mailbox` objects](library/mailbox#mailbox-objects) + [`Maildir`](library/mailbox#maildir) + [`mbox`](library/mailbox#mbox) + [`MH`](library/mailbox#mh) + [`Babyl`](library/mailbox#babyl) + [`MMDF`](library/mailbox#mmdf) * [`Message` objects](library/mailbox#message-objects) + [`MaildirMessage`](library/mailbox#maildirmessage) + [`mboxMessage`](library/mailbox#mboxmessage) + [`MHMessage`](library/mailbox#mhmessage) + [`BabylMessage`](library/mailbox#babylmessage) + [`MMDFMessage`](library/mailbox#mmdfmessage) * [Exceptions](library/mailbox#exceptions) * [Examples](library/mailbox#examples) - [`mimetypes` — Map filenames to MIME types](library/mimetypes) * [MimeTypes Objects](library/mimetypes#mimetypes-objects) - [`base64` — Base16, Base32, Base64, Base85 Data Encodings](library/base64) - [`binhex` — Encode and decode binhex4 files](library/binhex) * [Notes](library/binhex#notes) - [`binascii` — Convert between binary and ASCII](library/binascii) - [`quopri` — Encode and decode MIME quoted-printable data](library/quopri) + [Structured Markup Processing Tools](library/markup) - [`html` — HyperText Markup Language support](library/html) - [`html.parser` — Simple HTML and XHTML parser](library/html.parser) * [Example HTML Parser Application](library/html.parser#example-html-parser-application) * [`HTMLParser` Methods](library/html.parser#htmlparser-methods) * [Examples](library/html.parser#examples) - [`html.entities` — Definitions of HTML general entities](library/html.entities) - [XML Processing Modules](library/xml) * [XML vulnerabilities](library/xml#xml-vulnerabilities) * [The `defusedxml` Package](library/xml#the-defusedxml-package) - [`xml.etree.ElementTree` — The ElementTree XML API](library/xml.etree.elementtree) * [Tutorial](library/xml.etree.elementtree#tutorial) + [XML tree and elements](library/xml.etree.elementtree#xml-tree-and-elements) + [Parsing XML](library/xml.etree.elementtree#parsing-xml) + [Pull API for non-blocking parsing](library/xml.etree.elementtree#pull-api-for-non-blocking-parsing) + [Finding interesting elements](library/xml.etree.elementtree#finding-interesting-elements) + [Modifying an XML File](library/xml.etree.elementtree#modifying-an-xml-file) + [Building XML documents](library/xml.etree.elementtree#building-xml-documents) + [Parsing XML with Namespaces](library/xml.etree.elementtree#parsing-xml-with-namespaces) * [XPath support](library/xml.etree.elementtree#xpath-support) + [Example](library/xml.etree.elementtree#example) + [Supported XPath syntax](library/xml.etree.elementtree#supported-xpath-syntax) * [Reference](library/xml.etree.elementtree#reference) + [Functions](library/xml.etree.elementtree#functions) * [XInclude support](library/xml.etree.elementtree#xinclude-support) + [Example](library/xml.etree.elementtree#id3) * [Reference](library/xml.etree.elementtree#id4) + [Functions](library/xml.etree.elementtree#elementinclude-functions) + [Element Objects](library/xml.etree.elementtree#element-objects) + [ElementTree Objects](library/xml.etree.elementtree#elementtree-objects) + [QName Objects](library/xml.etree.elementtree#qname-objects) + [TreeBuilder Objects](library/xml.etree.elementtree#treebuilder-objects) + [XMLParser Objects](library/xml.etree.elementtree#xmlparser-objects) + [XMLPullParser Objects](library/xml.etree.elementtree#xmlpullparser-objects) + [Exceptions](library/xml.etree.elementtree#exceptions) - [`xml.dom` — The Document Object Model API](library/xml.dom) * [Module Contents](library/xml.dom#module-contents) * [Objects in the DOM](library/xml.dom#objects-in-the-dom) + [DOMImplementation Objects](library/xml.dom#domimplementation-objects) + [Node Objects](library/xml.dom#node-objects) + [NodeList Objects](library/xml.dom#nodelist-objects) + [DocumentType Objects](library/xml.dom#documenttype-objects) + [Document Objects](library/xml.dom#document-objects) + [Element Objects](library/xml.dom#element-objects) + [Attr Objects](library/xml.dom#attr-objects) + [NamedNodeMap Objects](library/xml.dom#namednodemap-objects) + [Comment Objects](library/xml.dom#comment-objects) + [Text and CDATASection Objects](library/xml.dom#text-and-cdatasection-objects) + [ProcessingInstruction Objects](library/xml.dom#processinginstruction-objects) + [Exceptions](library/xml.dom#exceptions) * [Conformance](library/xml.dom#conformance) + [Type Mapping](library/xml.dom#type-mapping) + [Accessor Methods](library/xml.dom#accessor-methods) - [`xml.dom.minidom` — Minimal DOM implementation](library/xml.dom.minidom) * [DOM Objects](library/xml.dom.minidom#dom-objects) * [DOM Example](library/xml.dom.minidom#dom-example) * [minidom and the DOM standard](library/xml.dom.minidom#minidom-and-the-dom-standard) - [`xml.dom.pulldom` — Support for building partial DOM trees](library/xml.dom.pulldom) * [DOMEventStream Objects](library/xml.dom.pulldom#domeventstream-objects) - [`xml.sax` — Support for SAX2 parsers](library/xml.sax) * [SAXException Objects](library/xml.sax#saxexception-objects) - [`xml.sax.handler` — Base classes for SAX handlers](library/xml.sax.handler) * [ContentHandler Objects](library/xml.sax.handler#contenthandler-objects) * [DTDHandler Objects](library/xml.sax.handler#dtdhandler-objects) * [EntityResolver Objects](library/xml.sax.handler#entityresolver-objects) * [ErrorHandler Objects](library/xml.sax.handler#errorhandler-objects) - [`xml.sax.saxutils` — SAX Utilities](library/xml.sax.utils) - [`xml.sax.xmlreader` — Interface for XML parsers](library/xml.sax.reader) * [XMLReader Objects](library/xml.sax.reader#xmlreader-objects) * [IncrementalParser Objects](library/xml.sax.reader#incrementalparser-objects) * [Locator Objects](library/xml.sax.reader#locator-objects) * [InputSource Objects](library/xml.sax.reader#inputsource-objects) * [The `Attributes` Interface](library/xml.sax.reader#the-attributes-interface) * [The `AttributesNS` Interface](library/xml.sax.reader#the-attributesns-interface) - [`xml.parsers.expat` — Fast XML parsing using Expat](library/pyexpat) * [XMLParser Objects](library/pyexpat#xmlparser-objects) * [ExpatError Exceptions](library/pyexpat#expaterror-exceptions) * [Example](library/pyexpat#example) * [Content Model Descriptions](library/pyexpat#module-xml.parsers.expat.model) * [Expat error constants](library/pyexpat#module-xml.parsers.expat.errors) + [Internet Protocols and Support](library/internet) - [`webbrowser` — Convenient Web-browser controller](library/webbrowser) * [Browser Controller Objects](library/webbrowser#browser-controller-objects) - [`wsgiref` — WSGI Utilities and Reference Implementation](library/wsgiref) * [`wsgiref.util` – WSGI environment utilities](library/wsgiref#module-wsgiref.util) * [`wsgiref.headers` – WSGI response header tools](library/wsgiref#module-wsgiref.headers) * [`wsgiref.simple_server` – a simple WSGI HTTP server](library/wsgiref#module-wsgiref.simple_server) * [`wsgiref.validate` — WSGI conformance checker](library/wsgiref#module-wsgiref.validate) * [`wsgiref.handlers` – server/gateway base classes](library/wsgiref#module-wsgiref.handlers) * [Examples](library/wsgiref#examples) - [`urllib` — URL handling modules](library/urllib) - [`urllib.request` — Extensible library for opening URLs](library/urllib.request) * [Request Objects](library/urllib.request#request-objects) * [OpenerDirector Objects](library/urllib.request#openerdirector-objects) * [BaseHandler Objects](library/urllib.request#basehandler-objects) * [HTTPRedirectHandler Objects](library/urllib.request#httpredirecthandler-objects) * [HTTPCookieProcessor Objects](library/urllib.request#httpcookieprocessor-objects) * [ProxyHandler Objects](library/urllib.request#proxyhandler-objects) * [HTTPPasswordMgr Objects](library/urllib.request#httppasswordmgr-objects) * [HTTPPasswordMgrWithPriorAuth Objects](library/urllib.request#httppasswordmgrwithpriorauth-objects) * [AbstractBasicAuthHandler Objects](library/urllib.request#abstractbasicauthhandler-objects) * [HTTPBasicAuthHandler Objects](library/urllib.request#httpbasicauthhandler-objects) * [ProxyBasicAuthHandler Objects](library/urllib.request#proxybasicauthhandler-objects) * [AbstractDigestAuthHandler Objects](library/urllib.request#abstractdigestauthhandler-objects) * [HTTPDigestAuthHandler Objects](library/urllib.request#httpdigestauthhandler-objects) * [ProxyDigestAuthHandler Objects](library/urllib.request#proxydigestauthhandler-objects) * [HTTPHandler Objects](library/urllib.request#httphandler-objects) * [HTTPSHandler Objects](library/urllib.request#httpshandler-objects) * [FileHandler Objects](library/urllib.request#filehandler-objects) * [DataHandler Objects](library/urllib.request#datahandler-objects) * [FTPHandler Objects](library/urllib.request#ftphandler-objects) * [CacheFTPHandler Objects](library/urllib.request#cacheftphandler-objects) * [UnknownHandler Objects](library/urllib.request#unknownhandler-objects) * [HTTPErrorProcessor Objects](library/urllib.request#httperrorprocessor-objects) * [Examples](library/urllib.request#examples) * [Legacy interface](library/urllib.request#legacy-interface) * [`urllib.request` Restrictions](library/urllib.request#urllib-request-restrictions) - [`urllib.response` — Response classes used by urllib](library/urllib.request#module-urllib.response) - [`urllib.parse` — Parse URLs into components](library/urllib.parse) * [URL Parsing](library/urllib.parse#url-parsing) * [Parsing ASCII Encoded Bytes](library/urllib.parse#parsing-ascii-encoded-bytes) * [Structured Parse Results](library/urllib.parse#structured-parse-results) * [URL Quoting](library/urllib.parse#url-quoting) - [`urllib.error` — Exception classes raised by urllib.request](library/urllib.error) - [`urllib.robotparser` — Parser for robots.txt](library/urllib.robotparser) - [`http` — HTTP modules](library/http) * [HTTP status codes](library/http#http-status-codes) - [`http.client` — HTTP protocol client](library/http.client) * [HTTPConnection Objects](library/http.client#httpconnection-objects) * [HTTPResponse Objects](library/http.client#httpresponse-objects) * [Examples](library/http.client#examples) * [HTTPMessage Objects](library/http.client#httpmessage-objects) - [`ftplib` — FTP protocol client](library/ftplib) * [FTP Objects](library/ftplib#ftp-objects) * [FTP\_TLS Objects](library/ftplib#ftp-tls-objects) - [`poplib` — POP3 protocol client](library/poplib) * [POP3 Objects](library/poplib#pop3-objects) * [POP3 Example](library/poplib#pop3-example) - [`imaplib` — IMAP4 protocol client](library/imaplib) * [IMAP4 Objects](library/imaplib#imap4-objects) * [IMAP4 Example](library/imaplib#imap4-example) - [`smtplib` — SMTP protocol client](library/smtplib) * [SMTP Objects](library/smtplib#smtp-objects) * [SMTP Example](library/smtplib#smtp-example) - [`uuid` — UUID objects according to **RFC 4122**](library/uuid) * [Example](library/uuid#example) - [`socketserver` — A framework for network servers](library/socketserver) * [Server Creation Notes](library/socketserver#server-creation-notes) * [Server Objects](library/socketserver#server-objects) * [Request Handler Objects](library/socketserver#request-handler-objects) * [Examples](library/socketserver#examples) + [`socketserver.TCPServer` Example](library/socketserver#socketserver-tcpserver-example) + [`socketserver.UDPServer` Example](library/socketserver#socketserver-udpserver-example) + [Asynchronous Mixins](library/socketserver#asynchronous-mixins) - [`http.server` — HTTP servers](library/http.server) * [Security Considerations](library/http.server#security-considerations) - [`http.cookies` — HTTP state management](library/http.cookies) * [Cookie Objects](library/http.cookies#cookie-objects) * [Morsel Objects](library/http.cookies#morsel-objects) * [Example](library/http.cookies#example) - [`http.cookiejar` — Cookie handling for HTTP clients](library/http.cookiejar) * [CookieJar and FileCookieJar Objects](library/http.cookiejar#cookiejar-and-filecookiejar-objects) * [FileCookieJar subclasses and co-operation with web browsers](library/http.cookiejar#filecookiejar-subclasses-and-co-operation-with-web-browsers) * [CookiePolicy Objects](library/http.cookiejar#cookiepolicy-objects) * [DefaultCookiePolicy Objects](library/http.cookiejar#defaultcookiepolicy-objects) * [Cookie Objects](library/http.cookiejar#cookie-objects) * [Examples](library/http.cookiejar#examples) - [`xmlrpc` — XMLRPC server and client modules](library/xmlrpc) - [`xmlrpc.client` — XML-RPC client access](library/xmlrpc.client) * [ServerProxy Objects](library/xmlrpc.client#serverproxy-objects) * [DateTime Objects](library/xmlrpc.client#datetime-objects) * [Binary Objects](library/xmlrpc.client#binary-objects) * [Fault Objects](library/xmlrpc.client#fault-objects) * [ProtocolError Objects](library/xmlrpc.client#protocolerror-objects) * [MultiCall Objects](library/xmlrpc.client#multicall-objects) * [Convenience Functions](library/xmlrpc.client#convenience-functions) * [Example of Client Usage](library/xmlrpc.client#example-of-client-usage) * [Example of Client and Server Usage](library/xmlrpc.client#example-of-client-and-server-usage) - [`xmlrpc.server` — Basic XML-RPC servers](library/xmlrpc.server) * [SimpleXMLRPCServer Objects](library/xmlrpc.server#simplexmlrpcserver-objects) + [SimpleXMLRPCServer Example](library/xmlrpc.server#simplexmlrpcserver-example) * [CGIXMLRPCRequestHandler](library/xmlrpc.server#cgixmlrpcrequesthandler) * [Documenting XMLRPC server](library/xmlrpc.server#documenting-xmlrpc-server) * [DocXMLRPCServer Objects](library/xmlrpc.server#docxmlrpcserver-objects) * [DocCGIXMLRPCRequestHandler](library/xmlrpc.server#doccgixmlrpcrequesthandler) - [`ipaddress` — IPv4/IPv6 manipulation library](library/ipaddress) * [Convenience factory functions](library/ipaddress#convenience-factory-functions) * [IP Addresses](library/ipaddress#ip-addresses) + [Address objects](library/ipaddress#address-objects) + [Conversion to Strings and Integers](library/ipaddress#conversion-to-strings-and-integers) + [Operators](library/ipaddress#operators) - [Comparison operators](library/ipaddress#comparison-operators) - [Arithmetic operators](library/ipaddress#arithmetic-operators) * [IP Network definitions](library/ipaddress#ip-network-definitions) + [Prefix, net mask and host mask](library/ipaddress#prefix-net-mask-and-host-mask) + [Network objects](library/ipaddress#network-objects) + [Operators](library/ipaddress#id1) - [Logical operators](library/ipaddress#logical-operators) - [Iteration](library/ipaddress#iteration) - [Networks as containers of addresses](library/ipaddress#networks-as-containers-of-addresses) * [Interface objects](library/ipaddress#interface-objects) + [Operators](library/ipaddress#id2) - [Logical operators](library/ipaddress#id3) * [Other Module Level Functions](library/ipaddress#other-module-level-functions) * [Custom Exceptions](library/ipaddress#custom-exceptions) + [Multimedia Services](library/mm) - [`wave` — Read and write WAV files](library/wave) * [Wave\_read Objects](library/wave#wave-read-objects) * [Wave\_write Objects](library/wave#wave-write-objects) - [`colorsys` — Conversions between color systems](library/colorsys) + [Internationalization](library/i18n) - [`gettext` — Multilingual internationalization services](library/gettext) * [GNU **gettext** API](library/gettext#gnu-gettext-api) * [Class-based API](library/gettext#class-based-api) + [The `NullTranslations` class](library/gettext#the-nulltranslations-class) + [The `GNUTranslations` class](library/gettext#the-gnutranslations-class) + [Solaris message catalog support](library/gettext#solaris-message-catalog-support) + [The Catalog constructor](library/gettext#the-catalog-constructor) * [Internationalizing your programs and modules](library/gettext#internationalizing-your-programs-and-modules) + [Localizing your module](library/gettext#localizing-your-module) + [Localizing your application](library/gettext#localizing-your-application) + [Changing languages on the fly](library/gettext#changing-languages-on-the-fly) + [Deferred translations](library/gettext#deferred-translations) * [Acknowledgements](library/gettext#acknowledgements) - [`locale` — Internationalization services](library/locale) * [Background, details, hints, tips and caveats](library/locale#background-details-hints-tips-and-caveats) * [For extension writers and programs that embed Python](library/locale#for-extension-writers-and-programs-that-embed-python) * [Access to message catalogs](library/locale#access-to-message-catalogs) + [Program Frameworks](library/frameworks) - [`turtle` — Turtle graphics](library/turtle) * [Introduction](library/turtle#introduction) * [Overview of available Turtle and Screen methods](library/turtle#overview-of-available-turtle-and-screen-methods) + [Turtle methods](library/turtle#turtle-methods) + [Methods of TurtleScreen/Screen](library/turtle#methods-of-turtlescreen-screen) * [Methods of RawTurtle/Turtle and corresponding functions](library/turtle#methods-of-rawturtle-turtle-and-corresponding-functions) + [Turtle motion](library/turtle#turtle-motion) + [Tell Turtle’s state](library/turtle#tell-turtle-s-state) + [Settings for measurement](library/turtle#settings-for-measurement) + [Pen control](library/turtle#pen-control) - [Drawing state](library/turtle#drawing-state) - [Color control](library/turtle#color-control) - [Filling](library/turtle#filling) - [More drawing control](library/turtle#more-drawing-control) + [Turtle state](library/turtle#turtle-state) - [Visibility](library/turtle#visibility) - [Appearance](library/turtle#appearance) + [Using events](library/turtle#using-events) + [Special Turtle methods](library/turtle#special-turtle-methods) + [Compound shapes](library/turtle#compound-shapes) * [Methods of TurtleScreen/Screen and corresponding functions](library/turtle#methods-of-turtlescreen-screen-and-corresponding-functions) + [Window control](library/turtle#window-control) + [Animation control](library/turtle#animation-control) + [Using screen events](library/turtle#using-screen-events) + [Input methods](library/turtle#input-methods) + [Settings and special methods](library/turtle#settings-and-special-methods) + [Methods specific to Screen, not inherited from TurtleScreen](library/turtle#methods-specific-to-screen-not-inherited-from-turtlescreen) * [Public classes](library/turtle#public-classes) * [Help and configuration](library/turtle#help-and-configuration) + [How to use help](library/turtle#how-to-use-help) + [Translation of docstrings into different languages](library/turtle#translation-of-docstrings-into-different-languages) + [How to configure Screen and Turtles](library/turtle#how-to-configure-screen-and-turtles) * [`turtledemo` — Demo scripts](library/turtle#module-turtledemo) * [Changes since Python 2.6](library/turtle#changes-since-python-2-6) * [Changes since Python 3.0](library/turtle#changes-since-python-3-0) - [`cmd` — Support for line-oriented command interpreters](library/cmd) * [Cmd Objects](library/cmd#cmd-objects) * [Cmd Example](library/cmd#cmd-example) - [`shlex` — Simple lexical analysis](library/shlex) * [shlex Objects](library/shlex#shlex-objects) * [Parsing Rules](library/shlex#parsing-rules) * [Improved Compatibility with Shells](library/shlex#improved-compatibility-with-shells) + [Graphical User Interfaces with Tk](library/tk) - [`tkinter` — Python interface to Tcl/Tk](library/tkinter) * [Tkinter Modules](library/tkinter#tkinter-modules) * [Tkinter Life Preserver](library/tkinter#tkinter-life-preserver) + [How To Use This Section](library/tkinter#how-to-use-this-section) + [A Simple Hello World Program](library/tkinter#a-simple-hello-world-program) * [A (Very) Quick Look at Tcl/Tk](library/tkinter#a-very-quick-look-at-tcl-tk) * [Mapping Basic Tk into Tkinter](library/tkinter#mapping-basic-tk-into-tkinter) * [How Tk and Tkinter are Related](library/tkinter#how-tk-and-tkinter-are-related) * [Handy Reference](library/tkinter#handy-reference) + [Setting Options](library/tkinter#setting-options) + [The Packer](library/tkinter#the-packer) + [Packer Options](library/tkinter#packer-options) + [Coupling Widget Variables](library/tkinter#coupling-widget-variables) + [The Window Manager](library/tkinter#the-window-manager) + [Tk Option Data Types](library/tkinter#tk-option-data-types) + [Bindings and Events](library/tkinter#bindings-and-events) + [The index Parameter](library/tkinter#the-index-parameter) + [Images](library/tkinter#images) * [File Handlers](library/tkinter#file-handlers) - [`tkinter.colorchooser` — Color choosing dialog](library/tkinter.colorchooser) - [`tkinter.font` — Tkinter font wrapper](library/tkinter.font) - [Tkinter Dialogs](library/dialog) * [`tkinter.simpledialog` — Standard Tkinter input dialogs](library/dialog#module-tkinter.simpledialog) * [`tkinter.filedialog` — File selection dialogs](library/dialog#module-tkinter.filedialog) + [Native Load/Save Dialogs](library/dialog#native-load-save-dialogs) * [`tkinter.commondialog` — Dialog window templates](library/dialog#module-tkinter.commondialog) - [`tkinter.messagebox` — Tkinter message prompts](library/tkinter.messagebox) - [`tkinter.scrolledtext` — Scrolled Text Widget](library/tkinter.scrolledtext) - [`tkinter.dnd` — Drag and drop support](library/tkinter.dnd) - [`tkinter.ttk` — Tk themed widgets](library/tkinter.ttk) * [Using Ttk](library/tkinter.ttk#using-ttk) * [Ttk Widgets](library/tkinter.ttk#ttk-widgets) * [Widget](library/tkinter.ttk#widget) + [Standard Options](library/tkinter.ttk#standard-options) + [Scrollable Widget Options](library/tkinter.ttk#scrollable-widget-options) + [Label Options](library/tkinter.ttk#label-options) + [Compatibility Options](library/tkinter.ttk#compatibility-options) + [Widget States](library/tkinter.ttk#widget-states) + [ttk.Widget](library/tkinter.ttk#ttk-widget) * [Combobox](library/tkinter.ttk#combobox) + [Options](library/tkinter.ttk#options) + [Virtual events](library/tkinter.ttk#virtual-events) + [ttk.Combobox](library/tkinter.ttk#ttk-combobox) * [Spinbox](library/tkinter.ttk#spinbox) + [Options](library/tkinter.ttk#id1) + [Virtual events](library/tkinter.ttk#id2) + [ttk.Spinbox](library/tkinter.ttk#ttk-spinbox) * [Notebook](library/tkinter.ttk#notebook) + [Options](library/tkinter.ttk#id3) + [Tab Options](library/tkinter.ttk#tab-options) + [Tab Identifiers](library/tkinter.ttk#tab-identifiers) + [Virtual Events](library/tkinter.ttk#id4) + [ttk.Notebook](library/tkinter.ttk#ttk-notebook) * [Progressbar](library/tkinter.ttk#progressbar) + [Options](library/tkinter.ttk#id5) + [ttk.Progressbar](library/tkinter.ttk#ttk-progressbar) * [Separator](library/tkinter.ttk#separator) + [Options](library/tkinter.ttk#id6) * [Sizegrip](library/tkinter.ttk#sizegrip) + [Platform-specific notes](library/tkinter.ttk#platform-specific-notes) + [Bugs](library/tkinter.ttk#bugs) * [Treeview](library/tkinter.ttk#treeview) + [Options](library/tkinter.ttk#id7) + [Item Options](library/tkinter.ttk#item-options) + [Tag Options](library/tkinter.ttk#tag-options) + [Column Identifiers](library/tkinter.ttk#column-identifiers) + [Virtual Events](library/tkinter.ttk#id8) + [ttk.Treeview](library/tkinter.ttk#ttk-treeview) * [Ttk Styling](library/tkinter.ttk#ttk-styling) + [Layouts](library/tkinter.ttk#layouts) - [`tkinter.tix` — Extension widgets for Tk](library/tkinter.tix) * [Using Tix](library/tkinter.tix#using-tix) * [Tix Widgets](library/tkinter.tix#tix-widgets) + [Basic Widgets](library/tkinter.tix#basic-widgets) + [File Selectors](library/tkinter.tix#file-selectors) + [Hierarchical ListBox](library/tkinter.tix#hierarchical-listbox) + [Tabular ListBox](library/tkinter.tix#tabular-listbox) + [Manager Widgets](library/tkinter.tix#manager-widgets) + [Image Types](library/tkinter.tix#image-types) + [Miscellaneous Widgets](library/tkinter.tix#miscellaneous-widgets) + [Form Geometry Manager](library/tkinter.tix#form-geometry-manager) * [Tix Commands](library/tkinter.tix#tix-commands) - [IDLE](library/idle) * [Menus](library/idle#menus) + [File menu (Shell and Editor)](library/idle#file-menu-shell-and-editor) + [Edit menu (Shell and Editor)](library/idle#edit-menu-shell-and-editor) + [Format menu (Editor window only)](library/idle#format-menu-editor-window-only) + [Run menu (Editor window only)](library/idle#run-menu-editor-window-only) + [Shell menu (Shell window only)](library/idle#shell-menu-shell-window-only) + [Debug menu (Shell window only)](library/idle#debug-menu-shell-window-only) + [Options menu (Shell and Editor)](library/idle#options-menu-shell-and-editor) + [Window menu (Shell and Editor)](library/idle#window-menu-shell-and-editor) + [Help menu (Shell and Editor)](library/idle#help-menu-shell-and-editor) + [Context Menus](library/idle#context-menus) * [Editing and navigation](library/idle#editing-and-navigation) + [Editor windows](library/idle#editor-windows) + [Key bindings](library/idle#key-bindings) + [Automatic indentation](library/idle#automatic-indentation) + [Completions](library/idle#completions) + [Calltips](library/idle#calltips) + [Code Context](library/idle#code-context) + [Python Shell window](library/idle#python-shell-window) + [Text colors](library/idle#text-colors) * [Startup and code execution](library/idle#startup-and-code-execution) + [Command line usage](library/idle#command-line-usage) + [Startup failure](library/idle#startup-failure) + [Running user code](library/idle#running-user-code) + [User output in Shell](library/idle#user-output-in-shell) + [Developing tkinter applications](library/idle#developing-tkinter-applications) + [Running without a subprocess](library/idle#running-without-a-subprocess) * [Help and preferences](library/idle#help-and-preferences) + [Help sources](library/idle#help-sources) + [Setting preferences](library/idle#setting-preferences) + [IDLE on macOS](library/idle#idle-on-macos) + [Extensions](library/idle#extensions) + [Development Tools](library/development) - [`typing` — Support for type hints](library/typing) * [Relevant PEPs](library/typing#relevant-peps) * [Type aliases](library/typing#type-aliases) * [NewType](library/typing#newtype) * [Callable](library/typing#callable) * [Generics](library/typing#generics) * [User-defined generic types](library/typing#user-defined-generic-types) * [The `Any` type](library/typing#the-any-type) * [Nominal vs structural subtyping](library/typing#nominal-vs-structural-subtyping) * [Module contents](library/typing#module-contents) + [Special typing primitives](library/typing#special-typing-primitives) - [Special types](library/typing#special-types) - [Special forms](library/typing#special-forms) - [Building generic types](library/typing#building-generic-types) - [Other special directives](library/typing#other-special-directives) + [Generic concrete collections](library/typing#generic-concrete-collections) - [Corresponding to built-in types](library/typing#corresponding-to-built-in-types) - [Corresponding to types in `collections`](library/typing#corresponding-to-types-in-collections) - [Other concrete types](library/typing#other-concrete-types) + [Abstract Base Classes](library/typing#abstract-base-classes) - [Corresponding to collections in `collections.abc`](library/typing#corresponding-to-collections-in-collections-abc) - [Corresponding to other types in `collections.abc`](library/typing#corresponding-to-other-types-in-collections-abc) - [Asynchronous programming](library/typing#asynchronous-programming) - [Context manager types](library/typing#context-manager-types) + [Protocols](library/typing#protocols) + [Functions and decorators](library/typing#functions-and-decorators) + [Introspection helpers](library/typing#introspection-helpers) + [Constant](library/typing#constant) - [`pydoc` — Documentation generator and online help system](library/pydoc) - [Python Development Mode](library/devmode) - [Effects of the Python Development Mode](library/devmode#effects-of-the-python-development-mode) - [ResourceWarning Example](library/devmode#resourcewarning-example) - [Bad file descriptor error example](library/devmode#bad-file-descriptor-error-example) - [`doctest` — Test interactive Python examples](library/doctest) * [Simple Usage: Checking Examples in Docstrings](library/doctest#simple-usage-checking-examples-in-docstrings) * [Simple Usage: Checking Examples in a Text File](library/doctest#simple-usage-checking-examples-in-a-text-file) * [How It Works](library/doctest#how-it-works) + [Which Docstrings Are Examined?](library/doctest#which-docstrings-are-examined) + [How are Docstring Examples Recognized?](library/doctest#how-are-docstring-examples-recognized) + [What’s the Execution Context?](library/doctest#what-s-the-execution-context) + [What About Exceptions?](library/doctest#what-about-exceptions) + [Option Flags](library/doctest#option-flags) + [Directives](library/doctest#directives) + [Warnings](library/doctest#warnings) * [Basic API](library/doctest#basic-api) * [Unittest API](library/doctest#unittest-api) * [Advanced API](library/doctest#advanced-api) + [DocTest Objects](library/doctest#doctest-objects) + [Example Objects](library/doctest#example-objects) + [DocTestFinder objects](library/doctest#doctestfinder-objects) + [DocTestParser objects](library/doctest#doctestparser-objects) + [DocTestRunner objects](library/doctest#doctestrunner-objects) + [OutputChecker objects](library/doctest#outputchecker-objects) * [Debugging](library/doctest#debugging) * [Soapbox](library/doctest#soapbox) - [`unittest` — Unit testing framework](library/unittest) * [Basic example](library/unittest#basic-example) * [Command-Line Interface](library/unittest#command-line-interface) + [Command-line options](library/unittest#command-line-options) * [Test Discovery](library/unittest#test-discovery) * [Organizing test code](library/unittest#organizing-test-code) * [Re-using old test code](library/unittest#re-using-old-test-code) * [Skipping tests and expected failures](library/unittest#skipping-tests-and-expected-failures) * [Distinguishing test iterations using subtests](library/unittest#distinguishing-test-iterations-using-subtests) * [Classes and functions](library/unittest#classes-and-functions) + [Test cases](library/unittest#test-cases) - [Deprecated aliases](library/unittest#deprecated-aliases) + [Grouping tests](library/unittest#grouping-tests) + [Loading and running tests](library/unittest#loading-and-running-tests) - [load\_tests Protocol](library/unittest#load-tests-protocol) * [Class and Module Fixtures](library/unittest#class-and-module-fixtures) + [setUpClass and tearDownClass](library/unittest#setupclass-and-teardownclass) + [setUpModule and tearDownModule](library/unittest#setupmodule-and-teardownmodule) * [Signal Handling](library/unittest#signal-handling) - [`unittest.mock` — mock object library](library/unittest.mock) * [Quick Guide](library/unittest.mock#quick-guide) * [The Mock Class](library/unittest.mock#the-mock-class) + [Calling](library/unittest.mock#calling) + [Deleting Attributes](library/unittest.mock#deleting-attributes) + [Mock names and the name attribute](library/unittest.mock#mock-names-and-the-name-attribute) + [Attaching Mocks as Attributes](library/unittest.mock#attaching-mocks-as-attributes) * [The patchers](library/unittest.mock#the-patchers) + [patch](library/unittest.mock#patch) + [patch.object](library/unittest.mock#patch-object) + [patch.dict](library/unittest.mock#patch-dict) + [patch.multiple](library/unittest.mock#patch-multiple) + [patch methods: start and stop](library/unittest.mock#patch-methods-start-and-stop) + [patch builtins](library/unittest.mock#patch-builtins) + [TEST\_PREFIX](library/unittest.mock#test-prefix) + [Nesting Patch Decorators](library/unittest.mock#nesting-patch-decorators) + [Where to patch](library/unittest.mock#where-to-patch) + [Patching Descriptors and Proxy Objects](library/unittest.mock#patching-descriptors-and-proxy-objects) * [MagicMock and magic method support](library/unittest.mock#magicmock-and-magic-method-support) + [Mocking Magic Methods](library/unittest.mock#mocking-magic-methods) + [Magic Mock](library/unittest.mock#magic-mock) * [Helpers](library/unittest.mock#helpers) + [sentinel](library/unittest.mock#sentinel) + [DEFAULT](library/unittest.mock#default) + [call](library/unittest.mock#call) + [create\_autospec](library/unittest.mock#create-autospec) + [ANY](library/unittest.mock#any) + [FILTER\_DIR](library/unittest.mock#filter-dir) + [mock\_open](library/unittest.mock#mock-open) + [Autospeccing](library/unittest.mock#autospeccing) + [Sealing mocks](library/unittest.mock#sealing-mocks) - [`unittest.mock` — getting started](https://docs.python.org/3.9/library/unittest.mock-examples.html) * [Using Mock](https://docs.python.org/3.9/library/unittest.mock-examples.html#using-mock) + [Mock Patching Methods](https://docs.python.org/3.9/library/unittest.mock-examples.html#mock-patching-methods) + [Mock for Method Calls on an Object](https://docs.python.org/3.9/library/unittest.mock-examples.html#mock-for-method-calls-on-an-object) + [Mocking Classes](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-classes) + [Naming your mocks](https://docs.python.org/3.9/library/unittest.mock-examples.html#naming-your-mocks) + [Tracking all Calls](https://docs.python.org/3.9/library/unittest.mock-examples.html#tracking-all-calls) + [Setting Return Values and Attributes](https://docs.python.org/3.9/library/unittest.mock-examples.html#setting-return-values-and-attributes) + [Raising exceptions with mocks](https://docs.python.org/3.9/library/unittest.mock-examples.html#raising-exceptions-with-mocks) + [Side effect functions and iterables](https://docs.python.org/3.9/library/unittest.mock-examples.html#side-effect-functions-and-iterables) + [Mocking asynchronous iterators](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-asynchronous-iterators) + [Mocking asynchronous context manager](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-asynchronous-context-manager) + [Creating a Mock from an Existing Object](https://docs.python.org/3.9/library/unittest.mock-examples.html#creating-a-mock-from-an-existing-object) * [Patch Decorators](https://docs.python.org/3.9/library/unittest.mock-examples.html#patch-decorators) * [Further Examples](https://docs.python.org/3.9/library/unittest.mock-examples.html#further-examples) + [Mocking chained calls](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-chained-calls) + [Partial mocking](https://docs.python.org/3.9/library/unittest.mock-examples.html#partial-mocking) + [Mocking a Generator Method](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-a-generator-method) + [Applying the same patch to every test method](https://docs.python.org/3.9/library/unittest.mock-examples.html#applying-the-same-patch-to-every-test-method) + [Mocking Unbound Methods](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-unbound-methods) + [Checking multiple calls with mock](https://docs.python.org/3.9/library/unittest.mock-examples.html#checking-multiple-calls-with-mock) + [Coping with mutable arguments](https://docs.python.org/3.9/library/unittest.mock-examples.html#coping-with-mutable-arguments) + [Nesting Patches](https://docs.python.org/3.9/library/unittest.mock-examples.html#nesting-patches) + [Mocking a dictionary with MagicMock](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-a-dictionary-with-magicmock) + [Mock subclasses and their attributes](https://docs.python.org/3.9/library/unittest.mock-examples.html#mock-subclasses-and-their-attributes) + [Mocking imports with patch.dict](https://docs.python.org/3.9/library/unittest.mock-examples.html#mocking-imports-with-patch-dict) + [Tracking order of calls and less verbose call assertions](https://docs.python.org/3.9/library/unittest.mock-examples.html#tracking-order-of-calls-and-less-verbose-call-assertions) + [More complex argument matching](https://docs.python.org/3.9/library/unittest.mock-examples.html#more-complex-argument-matching) - [2to3 - Automated Python 2 to 3 code translation](https://docs.python.org/3.9/library/2to3.html) * [Using 2to3](https://docs.python.org/3.9/library/2to3.html#using-2to3) * [Fixers](https://docs.python.org/3.9/library/2to3.html#fixers) * [`lib2to3` - 2to3’s library](https://docs.python.org/3.9/library/2to3.html#module-lib2to3) - [`test` — Regression tests package for Python](library/test) * [Writing Unit Tests for the `test` package](library/test#writing-unit-tests-for-the-test-package) * [Running tests using the command-line interface](library/test#running-tests-using-the-command-line-interface) - [`test.support` — Utilities for the Python test suite](library/test#module-test.support) - [`test.support.socket_helper` — Utilities for socket tests](library/test#module-test.support.socket_helper) - [`test.support.script_helper` — Utilities for the Python execution tests](library/test#module-test.support.script_helper) - [`test.support.bytecode_helper` — Support tools for testing correct bytecode generation](library/test#module-test.support.bytecode_helper) + [Debugging and Profiling](library/debug) - [Audit events table](library/audit_events) - [`bdb` — Debugger framework](library/bdb) - [`faulthandler` — Dump the Python traceback](library/faulthandler) * [Dumping the traceback](library/faulthandler#dumping-the-traceback) * [Fault handler state](library/faulthandler#fault-handler-state) * [Dumping the tracebacks after a timeout](library/faulthandler#dumping-the-tracebacks-after-a-timeout) * [Dumping the traceback on a user signal](library/faulthandler#dumping-the-traceback-on-a-user-signal) * [Issue with file descriptors](library/faulthandler#issue-with-file-descriptors) * [Example](library/faulthandler#example) - [`pdb` — The Python Debugger](library/pdb) * [Debugger Commands](library/pdb#debugger-commands) - [The Python Profilers](library/profile) * [Introduction to the profilers](library/profile#introduction-to-the-profilers) * [Instant User’s Manual](library/profile#instant-user-s-manual) * [`profile` and `cProfile` Module Reference](library/profile#module-cProfile) * [The `Stats` Class](library/profile#the-stats-class) * [What Is Deterministic Profiling?](library/profile#what-is-deterministic-profiling) * [Limitations](library/profile#limitations) * [Calibration](library/profile#calibration) * [Using a custom timer](library/profile#using-a-custom-timer) - [`timeit` — Measure execution time of small code snippets](library/timeit) * [Basic Examples](library/timeit#basic-examples) * [Python Interface](library/timeit#python-interface) * [Command-Line Interface](library/timeit#command-line-interface) * [Examples](library/timeit#examples) - [`trace` — Trace or track Python statement execution](library/trace) * [Command-Line Usage](library/trace#command-line-usage) + [Main options](library/trace#main-options) + [Modifiers](library/trace#modifiers) + [Filters](library/trace#filters) * [Programmatic Interface](library/trace#programmatic-interface) - [`tracemalloc` — Trace memory allocations](library/tracemalloc) * [Examples](library/tracemalloc#examples) + [Display the top 10](library/tracemalloc#display-the-top-10) + [Compute differences](library/tracemalloc#compute-differences) + [Get the traceback of a memory block](library/tracemalloc#get-the-traceback-of-a-memory-block) + [Pretty top](library/tracemalloc#pretty-top) - [Record the current and peak size of all traced memory blocks](library/tracemalloc#record-the-current-and-peak-size-of-all-traced-memory-blocks) * [API](library/tracemalloc#api) + [Functions](library/tracemalloc#functions) + [DomainFilter](library/tracemalloc#domainfilter) + [Filter](library/tracemalloc#filter) + [Frame](library/tracemalloc#frame) + [Snapshot](library/tracemalloc#snapshot) + [Statistic](library/tracemalloc#statistic) + [StatisticDiff](library/tracemalloc#statisticdiff) + [Trace](library/tracemalloc#trace) + [Traceback](library/tracemalloc#traceback) + [Software Packaging and Distribution](library/distribution) - [`distutils` — Building and installing Python modules](library/distutils) - [`ensurepip` — Bootstrapping the `pip` installer](library/ensurepip) * [Command line interface](library/ensurepip#command-line-interface) * [Module API](library/ensurepip#module-api) - [`venv` — Creation of virtual environments](library/venv) * [Creating virtual environments](library/venv#creating-virtual-environments) * [API](library/venv#api) * [An example of extending `EnvBuilder`](library/venv#an-example-of-extending-envbuilder) - [`zipapp` — Manage executable Python zip archives](library/zipapp) * [Basic Example](library/zipapp#basic-example) * [Command-Line Interface](library/zipapp#command-line-interface) * [Python API](library/zipapp#python-api) * [Examples](library/zipapp#examples) * [Specifying the Interpreter](library/zipapp#specifying-the-interpreter) * [Creating Standalone Applications with zipapp](library/zipapp#creating-standalone-applications-with-zipapp) + [Making a Windows executable](library/zipapp#making-a-windows-executable) + [Caveats](library/zipapp#caveats) * [The Python Zip Application Archive Format](library/zipapp#the-python-zip-application-archive-format) + [Python Runtime Services](library/python) - [`sys` — System-specific parameters and functions](library/sys) - [`sysconfig` — Provide access to Python’s configuration information](library/sysconfig) * [Configuration variables](library/sysconfig#configuration-variables) * [Installation paths](library/sysconfig#installation-paths) * [Other functions](library/sysconfig#other-functions) * [Using `sysconfig` as a script](library/sysconfig#using-sysconfig-as-a-script) - [`builtins` — Built-in objects](library/builtins) - [`__main__` — Top-level script environment](library/__main__) - [`warnings` — Warning control](library/warnings) * [Warning Categories](library/warnings#warning-categories) * [The Warnings Filter](library/warnings#the-warnings-filter) + [Describing Warning Filters](library/warnings#describing-warning-filters) + [Default Warning Filter](library/warnings#default-warning-filter) + [Overriding the default filter](library/warnings#overriding-the-default-filter) * [Temporarily Suppressing Warnings](library/warnings#temporarily-suppressing-warnings) * [Testing Warnings](library/warnings#testing-warnings) * [Updating Code For New Versions of Dependencies](library/warnings#updating-code-for-new-versions-of-dependencies) * [Available Functions](library/warnings#available-functions) * [Available Context Managers](library/warnings#available-context-managers) - [`dataclasses` — Data Classes](library/dataclasses) * [Module-level decorators, classes, and functions](library/dataclasses#module-level-decorators-classes-and-functions) * [Post-init processing](library/dataclasses#post-init-processing) * [Class variables](library/dataclasses#class-variables) * [Init-only variables](library/dataclasses#init-only-variables) * [Frozen instances](library/dataclasses#frozen-instances) * [Inheritance](library/dataclasses#inheritance) * [Default factory functions](library/dataclasses#default-factory-functions) * [Mutable default values](library/dataclasses#mutable-default-values) * [Exceptions](library/dataclasses#exceptions) - [`contextlib` — Utilities for `with`-statement contexts](library/contextlib) * [Utilities](library/contextlib#utilities) * [Examples and Recipes](library/contextlib#examples-and-recipes) + [Supporting a variable number of context managers](library/contextlib#supporting-a-variable-number-of-context-managers) + [Catching exceptions from `__enter__` methods](library/contextlib#catching-exceptions-from-enter-methods) + [Cleaning up in an `__enter__` implementation](library/contextlib#cleaning-up-in-an-enter-implementation) + [Replacing any use of `try-finally` and flag variables](library/contextlib#replacing-any-use-of-try-finally-and-flag-variables) + [Using a context manager as a function decorator](library/contextlib#using-a-context-manager-as-a-function-decorator) * [Single use, reusable and reentrant context managers](library/contextlib#single-use-reusable-and-reentrant-context-managers) + [Reentrant context managers](library/contextlib#reentrant-context-managers) + [Reusable context managers](library/contextlib#reusable-context-managers) - [`abc` — Abstract Base Classes](library/abc) - [`atexit` — Exit handlers](library/atexit) * [`atexit` Example](library/atexit#atexit-example) - [`traceback` — Print or retrieve a stack traceback](library/traceback) * [`TracebackException` Objects](library/traceback#tracebackexception-objects) * [`StackSummary` Objects](library/traceback#stacksummary-objects) * [`FrameSummary` Objects](library/traceback#framesummary-objects) * [Traceback Examples](library/traceback#traceback-examples) - [`__future__` — Future statement definitions](library/__future__) - [`gc` — Garbage Collector interface](library/gc) - [`inspect` — Inspect live objects](library/inspect) * [Types and members](library/inspect#types-and-members) * [Retrieving source code](library/inspect#retrieving-source-code) * [Introspecting callables with the Signature object](library/inspect#introspecting-callables-with-the-signature-object) * [Classes and functions](library/inspect#classes-and-functions) * [The interpreter stack](library/inspect#the-interpreter-stack) * [Fetching attributes statically](library/inspect#fetching-attributes-statically) * [Current State of Generators and Coroutines](library/inspect#current-state-of-generators-and-coroutines) * [Code Objects Bit Flags](library/inspect#code-objects-bit-flags) * [Command Line Interface](library/inspect#command-line-interface) - [`site` — Site-specific configuration hook](library/site) * [Readline configuration](library/site#readline-configuration) * [Module contents](library/site#module-contents) * [Command Line Interface](library/site#command-line-interface) + [Custom Python Interpreters](library/custominterp) - [`code` — Interpreter base classes](library/code) * [Interactive Interpreter Objects](library/code#interactive-interpreter-objects) * [Interactive Console Objects](library/code#interactive-console-objects) - [`codeop` — Compile Python code](library/codeop) + [Importing Modules](library/modules) - [`zipimport` — Import modules from Zip archives](library/zipimport) * [zipimporter Objects](library/zipimport#zipimporter-objects) * [Examples](library/zipimport#examples) - [`pkgutil` — Package extension utility](library/pkgutil) - [`modulefinder` — Find modules used by a script](library/modulefinder) * [Example usage of `ModuleFinder`](library/modulefinder#example-usage-of-modulefinder) - [`runpy` — Locating and executing Python modules](library/runpy) - [`importlib` — The implementation of `import`](library/importlib) * [Introduction](library/importlib#introduction) * [Functions](library/importlib#functions) * [`importlib.abc` – Abstract base classes related to import](library/importlib#module-importlib.abc) * [`importlib.resources` – Resources](library/importlib#module-importlib.resources) * [`importlib.machinery` – Importers and path hooks](library/importlib#module-importlib.machinery) * [`importlib.util` – Utility code for importers](library/importlib#module-importlib.util) * [Examples](library/importlib#examples) + [Importing programmatically](library/importlib#importing-programmatically) + [Checking if a module can be imported](library/importlib#checking-if-a-module-can-be-imported) + [Importing a source file directly](library/importlib#importing-a-source-file-directly) + [Setting up an importer](library/importlib#setting-up-an-importer) + [Approximating `importlib.import_module()`](library/importlib#approximating-importlib-import-module) - [Using `importlib.metadata`](library/importlib.metadata) * [Overview](library/importlib.metadata#overview) * [Functional API](library/importlib.metadata#functional-api) + [Entry points](library/importlib.metadata#entry-points) + [Distribution metadata](library/importlib.metadata#distribution-metadata) + [Distribution versions](library/importlib.metadata#distribution-versions) + [Distribution files](library/importlib.metadata#distribution-files) + [Distribution requirements](library/importlib.metadata#distribution-requirements) * [Distributions](library/importlib.metadata#distributions) * [Extending the search algorithm](library/importlib.metadata#extending-the-search-algorithm) + [Python Language Services](library/language) - [`parser` — Access Python parse trees](library/parser) * [Creating ST Objects](library/parser#creating-st-objects) * [Converting ST Objects](library/parser#converting-st-objects) * [Queries on ST Objects](library/parser#queries-on-st-objects) * [Exceptions and Error Handling](library/parser#exceptions-and-error-handling) * [ST Objects](library/parser#st-objects) * [Example: Emulation of `compile()`](library/parser#example-emulation-of-compile) - [`ast` — Abstract Syntax Trees](library/ast) * [Abstract Grammar](library/ast#abstract-grammar) * [Node classes](library/ast#node-classes) + [Literals](library/ast#literals) + [Variables](library/ast#variables) + [Expressions](library/ast#expressions) - [Subscripting](library/ast#subscripting) - [Comprehensions](library/ast#comprehensions) + [Statements](library/ast#statements) - [Imports](library/ast#imports) + [Control flow](library/ast#control-flow) + [Function and class definitions](library/ast#function-and-class-definitions) + [Async and await](library/ast#async-and-await) * [`ast` Helpers](library/ast#ast-helpers) * [Compiler Flags](library/ast#compiler-flags) * [Command-Line Usage](library/ast#command-line-usage) - [`symtable` — Access to the compiler’s symbol tables](library/symtable) * [Generating Symbol Tables](library/symtable#generating-symbol-tables) * [Examining Symbol Tables](library/symtable#examining-symbol-tables) - [`symbol` — Constants used with Python parse trees](library/symbol) - [`token` — Constants used with Python parse trees](library/token) - [`keyword` — Testing for Python keywords](library/keyword) - [`tokenize` — Tokenizer for Python source](library/tokenize) * [Tokenizing Input](library/tokenize#tokenizing-input) * [Command-Line Usage](library/tokenize#command-line-usage) * [Examples](library/tokenize#examples) - [`tabnanny` — Detection of ambiguous indentation](library/tabnanny) - [`pyclbr` — Python module browser support](library/pyclbr) * [Function Objects](library/pyclbr#function-objects) * [Class Objects](library/pyclbr#class-objects) - [`py_compile` — Compile Python source files](library/py_compile) - [`compileall` — Byte-compile Python libraries](library/compileall) * [Command-line use](library/compileall#command-line-use) * [Public functions](library/compileall#public-functions) - [`dis` — Disassembler for Python bytecode](library/dis) * [Bytecode analysis](library/dis#bytecode-analysis) * [Analysis functions](library/dis#analysis-functions) * [Python Bytecode Instructions](library/dis#python-bytecode-instructions) * [Opcode collections](library/dis#opcode-collections) - [`pickletools` — Tools for pickle developers](library/pickletools) * [Command line usage](library/pickletools#command-line-usage) + [Command line options](library/pickletools#command-line-options) * [Programmatic Interface](library/pickletools#programmatic-interface) + [Miscellaneous Services](library/misc) - [`formatter` — Generic output formatting](https://docs.python.org/3.9/library/formatter.html) * [The Formatter Interface](https://docs.python.org/3.9/library/formatter.html#the-formatter-interface) * [Formatter Implementations](https://docs.python.org/3.9/library/formatter.html#formatter-implementations) * [The Writer Interface](https://docs.python.org/3.9/library/formatter.html#the-writer-interface) * [Writer Implementations](https://docs.python.org/3.9/library/formatter.html#writer-implementations) + [MS Windows Specific Services](library/windows) - [`msvcrt` — Useful routines from the MS VC++ runtime](library/msvcrt) * [File Operations](library/msvcrt#file-operations) * [Console I/O](library/msvcrt#console-i-o) * [Other Functions](library/msvcrt#other-functions) - [`winreg` — Windows registry access](library/winreg) * [Functions](library/winreg#functions) * [Constants](library/winreg#constants) + [HKEY\_\* Constants](library/winreg#hkey-constants) + [Access Rights](library/winreg#access-rights) - [64-bit Specific](library/winreg#bit-specific) + [Value Types](library/winreg#value-types) * [Registry Handle Objects](library/winreg#registry-handle-objects) - [`winsound` — Sound-playing interface for Windows](library/winsound) + [Unix Specific Services](library/unix) - [`posix` — The most common POSIX system calls](library/posix) * [Large File Support](library/posix#large-file-support) * [Notable Module Contents](library/posix#notable-module-contents) - [`pwd` — The password database](library/pwd) - [`grp` — The group database](library/grp) - [`termios` — POSIX style tty control](library/termios) * [Example](library/termios#example) - [`tty` — Terminal control functions](library/tty) - [`pty` — Pseudo-terminal utilities](library/pty) * [Example](library/pty#example) - [`fcntl` — The `fcntl` and `ioctl` system calls](library/fcntl) - [`resource` — Resource usage information](library/resource) * [Resource Limits](library/resource#resource-limits) * [Resource Usage](library/resource#resource-usage) - [`syslog` — Unix syslog library routines](library/syslog) * [Examples](library/syslog#examples) + [Simple example](library/syslog#simple-example) + [Superseded Modules](library/superseded) - [`aifc` — Read and write AIFF and AIFC files](library/aifc) - [`asynchat` — Asynchronous socket command/response handler](library/asynchat) * [asynchat Example](library/asynchat#asynchat-example) - [`asyncore` — Asynchronous socket handler](library/asyncore) * [asyncore Example basic HTTP client](library/asyncore#asyncore-example-basic-http-client) * [asyncore Example basic echo server](library/asyncore#asyncore-example-basic-echo-server) - [`audioop` — Manipulate raw audio data](library/audioop) - [`cgi` — Common Gateway Interface support](library/cgi) * [Introduction](library/cgi#introduction) * [Using the cgi module](library/cgi#using-the-cgi-module) * [Higher Level Interface](library/cgi#higher-level-interface) * [Functions](library/cgi#functions) * [Caring about security](library/cgi#caring-about-security) * [Installing your CGI script on a Unix system](library/cgi#installing-your-cgi-script-on-a-unix-system) * [Testing your CGI script](library/cgi#testing-your-cgi-script) * [Debugging CGI scripts](library/cgi#debugging-cgi-scripts) * [Common problems and solutions](library/cgi#common-problems-and-solutions) - [`cgitb` — Traceback manager for CGI scripts](library/cgitb) - [`chunk` — Read IFF chunked data](library/chunk) - [`crypt` — Function to check Unix passwords](library/crypt) * [Hashing Methods](library/crypt#hashing-methods) * [Module Attributes](library/crypt#module-attributes) * [Module Functions](library/crypt#module-functions) * [Examples](library/crypt#examples) - [`imghdr` — Determine the type of an image](library/imghdr) - [`imp` — Access the import internals](library/imp) * [Examples](library/imp#examples) - [`mailcap` — Mailcap file handling](library/mailcap) - [`msilib` — Read and write Microsoft Installer files](library/msilib) * [Database Objects](library/msilib#database-objects) * [View Objects](library/msilib#view-objects) * [Summary Information Objects](library/msilib#summary-information-objects) * [Record Objects](library/msilib#record-objects) * [Errors](library/msilib#errors) * [CAB Objects](library/msilib#cab-objects) * [Directory Objects](library/msilib#directory-objects) * [Features](library/msilib#features) * [GUI classes](library/msilib#gui-classes) * [Precomputed tables](library/msilib#precomputed-tables) - [`nis` — Interface to Sun’s NIS (Yellow Pages)](library/nis) - [`nntplib` — NNTP protocol client](library/nntplib) * [NNTP Objects](library/nntplib#nntp-objects) + [Attributes](library/nntplib#attributes) + [Methods](library/nntplib#methods) * [Utility functions](library/nntplib#utility-functions) - [`optparse` — Parser for command line options](library/optparse) * [Background](library/optparse#background) + [Terminology](library/optparse#terminology) + [What are options for?](library/optparse#what-are-options-for) + [What are positional arguments for?](library/optparse#what-are-positional-arguments-for) * [Tutorial](library/optparse#tutorial) + [Understanding option actions](library/optparse#understanding-option-actions) + [The store action](library/optparse#the-store-action) + [Handling boolean (flag) options](library/optparse#handling-boolean-flag-options) + [Other actions](library/optparse#other-actions) + [Default values](library/optparse#default-values) + [Generating help](library/optparse#generating-help) - [Grouping Options](library/optparse#grouping-options) + [Printing a version string](library/optparse#printing-a-version-string) + [How `optparse` handles errors](library/optparse#how-optparse-handles-errors) + [Putting it all together](library/optparse#putting-it-all-together) * [Reference Guide](library/optparse#reference-guide) + [Creating the parser](library/optparse#creating-the-parser) + [Populating the parser](library/optparse#populating-the-parser) + [Defining options](library/optparse#defining-options) + [Option attributes](library/optparse#option-attributes) + [Standard option actions](library/optparse#standard-option-actions) + [Standard option types](library/optparse#standard-option-types) + [Parsing arguments](library/optparse#parsing-arguments) + [Querying and manipulating your option parser](library/optparse#querying-and-manipulating-your-option-parser) + [Conflicts between options](library/optparse#conflicts-between-options) + [Cleanup](library/optparse#cleanup) + [Other methods](library/optparse#other-methods) * [Option Callbacks](library/optparse#option-callbacks) + [Defining a callback option](library/optparse#defining-a-callback-option) + [How callbacks are called](library/optparse#how-callbacks-are-called) + [Raising errors in a callback](library/optparse#raising-errors-in-a-callback) + [Callback example 1: trivial callback](library/optparse#callback-example-1-trivial-callback) + [Callback example 2: check option order](library/optparse#callback-example-2-check-option-order) + [Callback example 3: check option order (generalized)](library/optparse#callback-example-3-check-option-order-generalized) + [Callback example 4: check arbitrary condition](library/optparse#callback-example-4-check-arbitrary-condition) + [Callback example 5: fixed arguments](library/optparse#callback-example-5-fixed-arguments) + [Callback example 6: variable arguments](library/optparse#callback-example-6-variable-arguments) * [Extending `optparse`](library/optparse#extending-optparse) + [Adding new types](library/optparse#adding-new-types) + [Adding new actions](library/optparse#adding-new-actions) - [`ossaudiodev` — Access to OSS-compatible audio devices](library/ossaudiodev) * [Audio Device Objects](library/ossaudiodev#audio-device-objects) * [Mixer Device Objects](library/ossaudiodev#mixer-device-objects) - [`pipes` — Interface to shell pipelines](library/pipes) * [Template Objects](library/pipes#template-objects) - [`smtpd` — SMTP Server](library/smtpd) * [SMTPServer Objects](library/smtpd#smtpserver-objects) * [DebuggingServer Objects](library/smtpd#debuggingserver-objects) * [PureProxy Objects](library/smtpd#pureproxy-objects) * [MailmanProxy Objects](library/smtpd#mailmanproxy-objects) * [SMTPChannel Objects](library/smtpd#smtpchannel-objects) - [`sndhdr` — Determine type of sound file](library/sndhdr) - [`spwd` — The shadow password database](library/spwd) - [`sunau` — Read and write Sun AU files](https://docs.python.org/3.9/library/sunau.html) * [AU\_read Objects](https://docs.python.org/3.9/library/sunau.html#au-read-objects) * [AU\_write Objects](https://docs.python.org/3.9/library/sunau.html#au-write-objects) - [`telnetlib` — Telnet client](library/telnetlib) * [Telnet Objects](library/telnetlib#telnet-objects) * [Telnet Example](library/telnetlib#telnet-example) - [`uu` — Encode and decode uuencode files](library/uu) - [`xdrlib` — Encode and decode XDR data](library/xdrlib) * [Packer Objects](library/xdrlib#packer-objects) * [Unpacker Objects](library/xdrlib#unpacker-objects) * [Exceptions](library/xdrlib#exceptions) + [Security Considerations](library/security_warnings) * [Extending and Embedding the Python Interpreter](extending/index) + [Recommended third party tools](extending/index#recommended-third-party-tools) + [Creating extensions without third party tools](extending/index#creating-extensions-without-third-party-tools) - [1. Extending Python with C or C++](extending/extending) * [1.1. A Simple Example](extending/extending#a-simple-example) * [1.2. Intermezzo: Errors and Exceptions](extending/extending#intermezzo-errors-and-exceptions) * [1.3. Back to the Example](extending/extending#back-to-the-example) * [1.4. The Module’s Method Table and Initialization Function](extending/extending#the-module-s-method-table-and-initialization-function) * [1.5. Compilation and Linkage](extending/extending#compilation-and-linkage) * [1.6. Calling Python Functions from C](extending/extending#calling-python-functions-from-c) * [1.7. Extracting Parameters in Extension Functions](extending/extending#extracting-parameters-in-extension-functions) * [1.8. Keyword Parameters for Extension Functions](extending/extending#keyword-parameters-for-extension-functions) * [1.9. Building Arbitrary Values](extending/extending#building-arbitrary-values) * [1.10. Reference Counts](extending/extending#reference-counts) + [1.10.1. Reference Counting in Python](extending/extending#reference-counting-in-python) + [1.10.2. Ownership Rules](extending/extending#ownership-rules) + [1.10.3. Thin Ice](extending/extending#thin-ice) + [1.10.4. NULL Pointers](extending/extending#null-pointers) * [1.11. Writing Extensions in C++](extending/extending#writing-extensions-in-c) * [1.12. Providing a C API for an Extension Module](extending/extending#providing-a-c-api-for-an-extension-module) - [2. Defining Extension Types: Tutorial](extending/newtypes_tutorial) * [2.1. The Basics](extending/newtypes_tutorial#the-basics) * [2.2. Adding data and methods to the Basic example](extending/newtypes_tutorial#adding-data-and-methods-to-the-basic-example) * [2.3. Providing finer control over data attributes](extending/newtypes_tutorial#providing-finer-control-over-data-attributes) * [2.4. Supporting cyclic garbage collection](extending/newtypes_tutorial#supporting-cyclic-garbage-collection) * [2.5. Subclassing other types](extending/newtypes_tutorial#subclassing-other-types) - [3. Defining Extension Types: Assorted Topics](extending/newtypes) * [3.1. Finalization and De-allocation](extending/newtypes#finalization-and-de-allocation) * [3.2. Object Presentation](extending/newtypes#object-presentation) * [3.3. Attribute Management](extending/newtypes#attribute-management) + [3.3.1. Generic Attribute Management](extending/newtypes#generic-attribute-management) + [3.3.2. Type-specific Attribute Management](extending/newtypes#type-specific-attribute-management) * [3.4. Object Comparison](extending/newtypes#object-comparison) * [3.5. Abstract Protocol Support](extending/newtypes#abstract-protocol-support) * [3.6. Weak Reference Support](extending/newtypes#weak-reference-support) * [3.7. More Suggestions](extending/newtypes#more-suggestions) - [4. Building C and C++ Extensions](extending/building) * [4.1. Building C and C++ Extensions with distutils](extending/building#building-c-and-c-extensions-with-distutils) * [4.2. Distributing your extension modules](extending/building#distributing-your-extension-modules) - [5. Building C and C++ Extensions on Windows](extending/windows) * [5.1. A Cookbook Approach](extending/windows#a-cookbook-approach) * [5.2. Differences Between Unix and Windows](extending/windows#differences-between-unix-and-windows) * [5.3. Using DLLs in Practice](extending/windows#using-dlls-in-practice) + [Embedding the CPython runtime in a larger application](extending/index#embedding-the-cpython-runtime-in-a-larger-application) - [1. Embedding Python in Another Application](extending/embedding) * [1.1. Very High Level Embedding](extending/embedding#very-high-level-embedding) * [1.2. Beyond Very High Level Embedding: An overview](extending/embedding#beyond-very-high-level-embedding-an-overview) * [1.3. Pure Embedding](extending/embedding#pure-embedding) * [1.4. Extending Embedded Python](extending/embedding#extending-embedded-python) * [1.5. Embedding Python in C++](extending/embedding#embedding-python-in-c) * [1.6. Compiling and Linking under Unix-like systems](extending/embedding#compiling-and-linking-under-unix-like-systems) * [Python/C API Reference Manual](c-api/index) + [Introduction](c-api/intro) - [Coding standards](c-api/intro#coding-standards) - [Include Files](c-api/intro#include-files) - [Useful macros](c-api/intro#useful-macros) - [Objects, Types and Reference Counts](c-api/intro#objects-types-and-reference-counts) * [Reference Counts](c-api/intro#reference-counts) + [Reference Count Details](c-api/intro#reference-count-details) * [Types](c-api/intro#types) - [Exceptions](c-api/intro#exceptions) - [Embedding Python](c-api/intro#embedding-python) - [Debugging Builds](c-api/intro#debugging-builds) + [Stable Application Binary Interface](c-api/stable) + [The Very High Level Layer](c-api/veryhigh) + [Reference Counting](c-api/refcounting) + [Exception Handling](c-api/exceptions) - [Printing and clearing](c-api/exceptions#printing-and-clearing) - [Raising exceptions](c-api/exceptions#raising-exceptions) - [Issuing warnings](c-api/exceptions#issuing-warnings) - [Querying the error indicator](c-api/exceptions#querying-the-error-indicator) - [Signal Handling](c-api/exceptions#signal-handling) - [Exception Classes](c-api/exceptions#exception-classes) - [Exception Objects](c-api/exceptions#exception-objects) - [Unicode Exception Objects](c-api/exceptions#unicode-exception-objects) - [Recursion Control](c-api/exceptions#recursion-control) - [Standard Exceptions](c-api/exceptions#standard-exceptions) - [Standard Warning Categories](c-api/exceptions#standard-warning-categories) + [Utilities](c-api/utilities) - [Operating System Utilities](c-api/sys) - [System Functions](c-api/sys#system-functions) - [Process Control](c-api/sys#process-control) - [Importing Modules](c-api/import) - [Data marshalling support](c-api/marshal) - [Parsing arguments and building values](c-api/arg) * [Parsing arguments](c-api/arg#parsing-arguments) + [Strings and buffers](c-api/arg#strings-and-buffers) + [Numbers](c-api/arg#numbers) + [Other objects](c-api/arg#other-objects) + [API Functions](c-api/arg#api-functions) * [Building values](c-api/arg#building-values) - [String conversion and formatting](c-api/conversion) - [Reflection](c-api/reflection) - [Codec registry and support functions](c-api/codec) * [Codec lookup API](c-api/codec#codec-lookup-api) * [Registry API for Unicode encoding error handlers](c-api/codec#registry-api-for-unicode-encoding-error-handlers) + [Abstract Objects Layer](c-api/abstract) - [Object Protocol](c-api/object) - [Call Protocol](c-api/call) * [The tp\_call Protocol](c-api/call#the-tp-call-protocol) * [The Vectorcall Protocol](c-api/call#the-vectorcall-protocol) + [Recursion Control](c-api/call#recursion-control) + [Vectorcall Support API](c-api/call#vectorcall-support-api) * [Object Calling API](c-api/call#object-calling-api) * [Call Support API](c-api/call#call-support-api) - [Number Protocol](c-api/number) - [Sequence Protocol](c-api/sequence) - [Mapping Protocol](c-api/mapping) - [Iterator Protocol](c-api/iter) - [Buffer Protocol](c-api/buffer) * [Buffer structure](c-api/buffer#buffer-structure) * [Buffer request types](c-api/buffer#buffer-request-types) + [request-independent fields](c-api/buffer#request-independent-fields) + [readonly, format](c-api/buffer#readonly-format) + [shape, strides, suboffsets](c-api/buffer#shape-strides-suboffsets) + [contiguity requests](c-api/buffer#contiguity-requests) + [compound requests](c-api/buffer#compound-requests) * [Complex arrays](c-api/buffer#complex-arrays) + [NumPy-style: shape and strides](c-api/buffer#numpy-style-shape-and-strides) + [PIL-style: shape, strides and suboffsets](c-api/buffer#pil-style-shape-strides-and-suboffsets) * [Buffer-related functions](c-api/buffer#buffer-related-functions) - [Old Buffer Protocol](c-api/objbuffer) + [Concrete Objects Layer](c-api/concrete) - [Fundamental Objects](c-api/concrete#fundamental-objects) * [Type Objects](c-api/type) + [Creating Heap-Allocated Types](c-api/type#creating-heap-allocated-types) * [The `None` Object](c-api/none) - [Numeric Objects](c-api/concrete#numeric-objects) * [Integer Objects](c-api/long) * [Boolean Objects](c-api/bool) * [Floating Point Objects](c-api/float) * [Complex Number Objects](c-api/complex) + [Complex Numbers as C Structures](c-api/complex#complex-numbers-as-c-structures) + [Complex Numbers as Python Objects](c-api/complex#complex-numbers-as-python-objects) - [Sequence Objects](c-api/concrete#sequence-objects) * [Bytes Objects](c-api/bytes) * [Byte Array Objects](c-api/bytearray) + [Type check macros](c-api/bytearray#type-check-macros) + [Direct API functions](c-api/bytearray#direct-api-functions) + [Macros](c-api/bytearray#macros) * [Unicode Objects and Codecs](c-api/unicode) + [Unicode Objects](c-api/unicode#unicode-objects) - [Unicode Type](c-api/unicode#unicode-type) - [Unicode Character Properties](c-api/unicode#unicode-character-properties) - [Creating and accessing Unicode strings](c-api/unicode#creating-and-accessing-unicode-strings) - [Deprecated Py\_UNICODE APIs](c-api/unicode#deprecated-py-unicode-apis) - [Locale Encoding](c-api/unicode#locale-encoding) - [File System Encoding](c-api/unicode#file-system-encoding) - [wchar\_t Support](c-api/unicode#wchar-t-support) + [Built-in Codecs](c-api/unicode#built-in-codecs) - [Generic Codecs](c-api/unicode#generic-codecs) - [UTF-8 Codecs](c-api/unicode#utf-8-codecs) - [UTF-32 Codecs](c-api/unicode#utf-32-codecs) - [UTF-16 Codecs](c-api/unicode#utf-16-codecs) - [UTF-7 Codecs](c-api/unicode#utf-7-codecs) - [Unicode-Escape Codecs](c-api/unicode#unicode-escape-codecs) - [Raw-Unicode-Escape Codecs](c-api/unicode#raw-unicode-escape-codecs) - [Latin-1 Codecs](c-api/unicode#latin-1-codecs) - [ASCII Codecs](c-api/unicode#ascii-codecs) - [Character Map Codecs](c-api/unicode#character-map-codecs) - [MBCS codecs for Windows](c-api/unicode#mbcs-codecs-for-windows) - [Methods & Slots](c-api/unicode#methods-slots) + [Methods and Slot Functions](c-api/unicode#methods-and-slot-functions) * [Tuple Objects](c-api/tuple) * [Struct Sequence Objects](c-api/tuple#struct-sequence-objects) * [List Objects](c-api/list) - [Container Objects](c-api/concrete#container-objects) * [Dictionary Objects](c-api/dict) * [Set Objects](c-api/set) - [Function Objects](c-api/concrete#function-objects) * [Function Objects](c-api/function) * [Instance Method Objects](c-api/method) * [Method Objects](c-api/method#method-objects) * [Cell Objects](c-api/cell) * [Code Objects](c-api/code) - [Other Objects](c-api/concrete#other-objects) * [File Objects](c-api/file) * [Module Objects](c-api/module) + [Initializing C modules](c-api/module#initializing-c-modules) - [Single-phase initialization](c-api/module#single-phase-initialization) - [Multi-phase initialization](c-api/module#multi-phase-initialization) - [Low-level module creation functions](c-api/module#low-level-module-creation-functions) - [Support functions](c-api/module#support-functions) + [Module lookup](c-api/module#module-lookup) * [Iterator Objects](c-api/iterator) * [Descriptor Objects](c-api/descriptor) * [Slice Objects](c-api/slice) * [Ellipsis Object](c-api/slice#ellipsis-object) * [MemoryView objects](c-api/memoryview) * [Weak Reference Objects](c-api/weakref) * [Capsules](c-api/capsule) * [Generator Objects](c-api/gen) * [Coroutine Objects](c-api/coro) * [Context Variables Objects](c-api/contextvars) * [DateTime Objects](c-api/datetime) * [Objects for Type Hinting](c-api/typehints) + [Initialization, Finalization, and Threads](c-api/init) - [Before Python Initialization](c-api/init#before-python-initialization) - [Global configuration variables](c-api/init#global-configuration-variables) - [Initializing and finalizing the interpreter](c-api/init#initializing-and-finalizing-the-interpreter) - [Process-wide parameters](c-api/init#process-wide-parameters) - [Thread State and the Global Interpreter Lock](c-api/init#thread-state-and-the-global-interpreter-lock) * [Releasing the GIL from extension code](c-api/init#releasing-the-gil-from-extension-code) * [Non-Python created threads](c-api/init#non-python-created-threads) * [Cautions about fork()](c-api/init#cautions-about-fork) * [High-level API](c-api/init#high-level-api) * [Low-level API](c-api/init#low-level-api) - [Sub-interpreter support](c-api/init#sub-interpreter-support) * [Bugs and caveats](c-api/init#bugs-and-caveats) - [Asynchronous Notifications](c-api/init#asynchronous-notifications) - [Profiling and Tracing](c-api/init#profiling-and-tracing) - [Advanced Debugger Support](c-api/init#advanced-debugger-support) - [Thread Local Storage Support](c-api/init#thread-local-storage-support) * [Thread Specific Storage (TSS) API](c-api/init#thread-specific-storage-tss-api) + [Dynamic Allocation](c-api/init#dynamic-allocation) + [Methods](c-api/init#methods) * [Thread Local Storage (TLS) API](c-api/init#thread-local-storage-tls-api) + [Python Initialization Configuration](c-api/init_config) - [PyWideStringList](c-api/init_config#pywidestringlist) - [PyStatus](c-api/init_config#pystatus) - [PyPreConfig](c-api/init_config#pypreconfig) - [Preinitialization with PyPreConfig](c-api/init_config#preinitialization-with-pypreconfig) - [PyConfig](c-api/init_config#pyconfig) - [Initialization with PyConfig](c-api/init_config#initialization-with-pyconfig) - [Isolated Configuration](c-api/init_config#isolated-configuration) - [Python Configuration](c-api/init_config#python-configuration) - [Path Configuration](c-api/init_config#path-configuration) - [Py\_RunMain()](c-api/init_config#py-runmain) - [Py\_GetArgcArgv()](c-api/init_config#py-getargcargv) - [Multi-Phase Initialization Private Provisional API](c-api/init_config#multi-phase-initialization-private-provisional-api) + [Memory Management](c-api/memory) - [Overview](c-api/memory#overview) - [Raw Memory Interface](c-api/memory#raw-memory-interface) - [Memory Interface](c-api/memory#memory-interface) - [Object allocators](c-api/memory#object-allocators) - [Default Memory Allocators](c-api/memory#default-memory-allocators) - [Customize Memory Allocators](c-api/memory#customize-memory-allocators) - [The pymalloc allocator](c-api/memory#the-pymalloc-allocator) * [Customize pymalloc Arena Allocator](c-api/memory#customize-pymalloc-arena-allocator) - [tracemalloc C API](c-api/memory#tracemalloc-c-api) - [Examples](c-api/memory#examples) + [Object Implementation Support](c-api/objimpl) - [Allocating Objects on the Heap](c-api/allocation) - [Common Object Structures](c-api/structures) * [Base object types and macros](c-api/structures#base-object-types-and-macros) * [Implementing functions and methods](c-api/structures#implementing-functions-and-methods) * [Accessing attributes of extension types](c-api/structures#accessing-attributes-of-extension-types) - [Type Objects](c-api/typeobj) * [Quick Reference](c-api/typeobj#quick-reference) + [“tp slots”](c-api/typeobj#tp-slots) + [sub-slots](c-api/typeobj#sub-slots) + [slot typedefs](c-api/typeobj#slot-typedefs) * [PyTypeObject Definition](c-api/typeobj#pytypeobject-definition) * [PyObject Slots](c-api/typeobj#pyobject-slots) * [PyVarObject Slots](c-api/typeobj#pyvarobject-slots) * [PyTypeObject Slots](c-api/typeobj#pytypeobject-slots) * [Heap Types](c-api/typeobj#heap-types) - [Number Object Structures](c-api/typeobj#number-object-structures) - [Mapping Object Structures](c-api/typeobj#mapping-object-structures) - [Sequence Object Structures](c-api/typeobj#sequence-object-structures) - [Buffer Object Structures](c-api/typeobj#buffer-object-structures) - [Async Object Structures](c-api/typeobj#async-object-structures) - [Slot Type typedefs](c-api/typeobj#slot-type-typedefs) - [Examples](c-api/typeobj#examples) - [Supporting Cyclic Garbage Collection](c-api/gcsupport) + [API and ABI Versioning](c-api/apiabiversion) * [Distributing Python Modules](distributing/index) + [Key terms](distributing/index#key-terms) + [Open source licensing and collaboration](distributing/index#open-source-licensing-and-collaboration) + [Installing the tools](distributing/index#installing-the-tools) + [Reading the Python Packaging User Guide](distributing/index#reading-the-python-packaging-user-guide) + [How do I…?](distributing/index#how-do-i) - [… choose a name for my project?](distributing/index#choose-a-name-for-my-project) - [… create and distribute binary extensions?](distributing/index#create-and-distribute-binary-extensions) * [Installing Python Modules](installing/index) + [Key terms](installing/index#key-terms) + [Basic usage](installing/index#basic-usage) + [How do I …?](installing/index#how-do-i) - [… install `pip` in versions of Python prior to Python 3.4?](installing/index#install-pip-in-versions-of-python-prior-to-python-3-4) - [… install packages just for the current user?](installing/index#install-packages-just-for-the-current-user) - [… install scientific Python packages?](installing/index#install-scientific-python-packages) - [… work with multiple versions of Python installed in parallel?](installing/index#work-with-multiple-versions-of-python-installed-in-parallel) + [Common installation issues](installing/index#common-installation-issues) - [Installing into the system Python on Linux](installing/index#installing-into-the-system-python-on-linux) - [Pip not installed](installing/index#pip-not-installed) - [Installing binary extensions](installing/index#installing-binary-extensions) * [Python HOWTOs](howto/index) + [Porting Python 2 Code to Python 3](howto/pyporting) - [The Short Explanation](howto/pyporting#the-short-explanation) - [Details](howto/pyporting#details) * [Drop support for Python 2.6 and older](howto/pyporting#drop-support-for-python-2-6-and-older) * [Make sure you specify the proper version support in your `setup.py` file](howto/pyporting#make-sure-you-specify-the-proper-version-support-in-your-setup-py-file) * [Have good test coverage](howto/pyporting#have-good-test-coverage) * [Learn the differences between Python 2 & 3](howto/pyporting#learn-the-differences-between-python-2-3) * [Update your code](howto/pyporting#update-your-code) + [Division](howto/pyporting#division) + [Text versus binary data](howto/pyporting#text-versus-binary-data) + [Use feature detection instead of version detection](howto/pyporting#use-feature-detection-instead-of-version-detection) * [Prevent compatibility regressions](howto/pyporting#prevent-compatibility-regressions) * [Check which dependencies block your transition](howto/pyporting#check-which-dependencies-block-your-transition) * [Update your `setup.py` file to denote Python 3 compatibility](howto/pyporting#update-your-setup-py-file-to-denote-python-3-compatibility) * [Use continuous integration to stay compatible](howto/pyporting#use-continuous-integration-to-stay-compatible) * [Consider using optional static type checking](howto/pyporting#consider-using-optional-static-type-checking) + [Porting Extension Modules to Python 3](howto/cporting) + [Curses Programming with Python](howto/curses) - [What is curses?](howto/curses#what-is-curses) * [The Python curses module](howto/curses#the-python-curses-module) - [Starting and ending a curses application](howto/curses#starting-and-ending-a-curses-application) - [Windows and Pads](howto/curses#windows-and-pads) - [Displaying Text](howto/curses#displaying-text) * [Attributes and Color](howto/curses#attributes-and-color) - [User Input](howto/curses#user-input) - [For More Information](howto/curses#for-more-information) + [Descriptor HowTo Guide](howto/descriptor) - [Primer](howto/descriptor#primer) * [Simple example: A descriptor that returns a constant](howto/descriptor#simple-example-a-descriptor-that-returns-a-constant) * [Dynamic lookups](howto/descriptor#dynamic-lookups) * [Managed attributes](howto/descriptor#managed-attributes) * [Customized names](howto/descriptor#customized-names) * [Closing thoughts](howto/descriptor#closing-thoughts) - [Complete Practical Example](howto/descriptor#complete-practical-example) * [Validator class](howto/descriptor#validator-class) * [Custom validators](howto/descriptor#custom-validators) * [Practical application](howto/descriptor#practical-application) - [Technical Tutorial](howto/descriptor#technical-tutorial) * [Abstract](howto/descriptor#abstract) * [Definition and introduction](howto/descriptor#definition-and-introduction) * [Descriptor protocol](howto/descriptor#descriptor-protocol) * [Overview of descriptor invocation](howto/descriptor#overview-of-descriptor-invocation) * [Invocation from an instance](howto/descriptor#invocation-from-an-instance) * [Invocation from a class](howto/descriptor#invocation-from-a-class) * [Invocation from super](howto/descriptor#invocation-from-super) * [Summary of invocation logic](howto/descriptor#summary-of-invocation-logic) * [Automatic name notification](howto/descriptor#automatic-name-notification) * [ORM example](howto/descriptor#orm-example) - [Pure Python Equivalents](howto/descriptor#pure-python-equivalents) * [Properties](howto/descriptor#properties) * [Functions and methods](howto/descriptor#functions-and-methods) * [Kinds of methods](howto/descriptor#kinds-of-methods) * [Static methods](howto/descriptor#static-methods) * [Class methods](howto/descriptor#class-methods) * [Member objects and \_\_slots\_\_](howto/descriptor#member-objects-and-slots) + [Functional Programming HOWTO](howto/functional) - [Introduction](howto/functional#introduction) * [Formal provability](howto/functional#formal-provability) * [Modularity](howto/functional#modularity) * [Ease of debugging and testing](howto/functional#ease-of-debugging-and-testing) * [Composability](howto/functional#composability) - [Iterators](howto/functional#iterators) * [Data Types That Support Iterators](howto/functional#data-types-that-support-iterators) - [Generator expressions and list comprehensions](howto/functional#generator-expressions-and-list-comprehensions) - [Generators](howto/functional#generators) * [Passing values into a generator](howto/functional#passing-values-into-a-generator) - [Built-in functions](howto/functional#built-in-functions) - [The itertools module](howto/functional#the-itertools-module) * [Creating new iterators](howto/functional#creating-new-iterators) * [Calling functions on elements](howto/functional#calling-functions-on-elements) * [Selecting elements](howto/functional#selecting-elements) * [Combinatoric functions](howto/functional#combinatoric-functions) * [Grouping elements](howto/functional#grouping-elements) - [The functools module](howto/functional#the-functools-module) * [The operator module](howto/functional#the-operator-module) - [Small functions and the lambda expression](howto/functional#small-functions-and-the-lambda-expression) - [Revision History and Acknowledgements](howto/functional#revision-history-and-acknowledgements) - [References](howto/functional#references) * [General](howto/functional#general) * [Python-specific](howto/functional#python-specific) * [Python documentation](howto/functional#python-documentation) + [Logging HOWTO](howto/logging) - [Basic Logging Tutorial](howto/logging#basic-logging-tutorial) * [When to use logging](howto/logging#when-to-use-logging) * [A simple example](howto/logging#a-simple-example) * [Logging to a file](howto/logging#logging-to-a-file) * [Logging from multiple modules](howto/logging#logging-from-multiple-modules) * [Logging variable data](howto/logging#logging-variable-data) * [Changing the format of displayed messages](howto/logging#changing-the-format-of-displayed-messages) * [Displaying the date/time in messages](howto/logging#displaying-the-date-time-in-messages) * [Next Steps](howto/logging#next-steps) - [Advanced Logging Tutorial](howto/logging#advanced-logging-tutorial) * [Logging Flow](howto/logging#logging-flow) * [Loggers](howto/logging#loggers) * [Handlers](howto/logging#handlers) * [Formatters](howto/logging#formatters) * [Configuring Logging](howto/logging#configuring-logging) * [What happens if no configuration is provided](howto/logging#what-happens-if-no-configuration-is-provided) * [Configuring Logging for a Library](howto/logging#configuring-logging-for-a-library) - [Logging Levels](howto/logging#logging-levels) * [Custom Levels](howto/logging#custom-levels) - [Useful Handlers](howto/logging#useful-handlers) - [Exceptions raised during logging](howto/logging#exceptions-raised-during-logging) - [Using arbitrary objects as messages](howto/logging#using-arbitrary-objects-as-messages) - [Optimization](howto/logging#optimization) + [Logging Cookbook](howto/logging-cookbook) - [Using logging in multiple modules](howto/logging-cookbook#using-logging-in-multiple-modules) - [Logging from multiple threads](howto/logging-cookbook#logging-from-multiple-threads) - [Multiple handlers and formatters](howto/logging-cookbook#multiple-handlers-and-formatters) - [Logging to multiple destinations](howto/logging-cookbook#logging-to-multiple-destinations) - [Configuration server example](howto/logging-cookbook#configuration-server-example) - [Dealing with handlers that block](howto/logging-cookbook#dealing-with-handlers-that-block) - [Sending and receiving logging events across a network](howto/logging-cookbook#sending-and-receiving-logging-events-across-a-network) * [Running a logging socket listener in production](howto/logging-cookbook#running-a-logging-socket-listener-in-production) - [Adding contextual information to your logging output](howto/logging-cookbook#adding-contextual-information-to-your-logging-output) * [Using LoggerAdapters to impart contextual information](howto/logging-cookbook#using-loggeradapters-to-impart-contextual-information) + [Using objects other than dicts to pass contextual information](howto/logging-cookbook#using-objects-other-than-dicts-to-pass-contextual-information) * [Using Filters to impart contextual information](howto/logging-cookbook#using-filters-to-impart-contextual-information) - [Logging to a single file from multiple processes](howto/logging-cookbook#logging-to-a-single-file-from-multiple-processes) * [Using concurrent.futures.ProcessPoolExecutor](howto/logging-cookbook#using-concurrent-futures-processpoolexecutor) * [Deploying Web applications using Gunicorn and uWSGI](howto/logging-cookbook#deploying-web-applications-using-gunicorn-and-uwsgi) - [Using file rotation](howto/logging-cookbook#using-file-rotation) - [Use of alternative formatting styles](howto/logging-cookbook#use-of-alternative-formatting-styles) - [Customizing `LogRecord`](howto/logging-cookbook#customizing-logrecord) - [Subclassing QueueHandler - a ZeroMQ example](howto/logging-cookbook#subclassing-queuehandler-a-zeromq-example) - [Subclassing QueueListener - a ZeroMQ example](howto/logging-cookbook#subclassing-queuelistener-a-zeromq-example) - [An example dictionary-based configuration](howto/logging-cookbook#an-example-dictionary-based-configuration) - [Using a rotator and namer to customize log rotation processing](howto/logging-cookbook#using-a-rotator-and-namer-to-customize-log-rotation-processing) - [A more elaborate multiprocessing example](howto/logging-cookbook#a-more-elaborate-multiprocessing-example) - [Inserting a BOM into messages sent to a SysLogHandler](howto/logging-cookbook#inserting-a-bom-into-messages-sent-to-a-sysloghandler) - [Implementing structured logging](howto/logging-cookbook#implementing-structured-logging) - [Customizing handlers with `dictConfig()`](howto/logging-cookbook#customizing-handlers-with-dictconfig) - [Using particular formatting styles throughout your application](howto/logging-cookbook#using-particular-formatting-styles-throughout-your-application) * [Using LogRecord factories](howto/logging-cookbook#using-logrecord-factories) * [Using custom message objects](howto/logging-cookbook#using-custom-message-objects) - [Configuring filters with `dictConfig()`](howto/logging-cookbook#configuring-filters-with-dictconfig) - [Customized exception formatting](howto/logging-cookbook#customized-exception-formatting) - [Speaking logging messages](howto/logging-cookbook#speaking-logging-messages) - [Buffering logging messages and outputting them conditionally](howto/logging-cookbook#buffering-logging-messages-and-outputting-them-conditionally) - [Formatting times using UTC (GMT) via configuration](howto/logging-cookbook#formatting-times-using-utc-gmt-via-configuration) - [Using a context manager for selective logging](howto/logging-cookbook#using-a-context-manager-for-selective-logging) - [A CLI application starter template](howto/logging-cookbook#a-cli-application-starter-template) - [A Qt GUI for logging](howto/logging-cookbook#a-qt-gui-for-logging) - [Patterns to avoid](howto/logging-cookbook#patterns-to-avoid) * [Opening the same log file multiple times](howto/logging-cookbook#opening-the-same-log-file-multiple-times) * [Using loggers as attributes in a class or passing them as parameters](howto/logging-cookbook#using-loggers-as-attributes-in-a-class-or-passing-them-as-parameters) * [Adding handlers other than `NullHandler` to a logger in a library](howto/logging-cookbook#adding-handlers-other-than-nullhandler-to-a-logger-in-a-library) * [Creating a lot of loggers](howto/logging-cookbook#creating-a-lot-of-loggers) + [Regular Expression HOWTO](howto/regex) - [Introduction](howto/regex#introduction) - [Simple Patterns](howto/regex#simple-patterns) * [Matching Characters](howto/regex#matching-characters) * [Repeating Things](howto/regex#repeating-things) - [Using Regular Expressions](howto/regex#using-regular-expressions) * [Compiling Regular Expressions](howto/regex#compiling-regular-expressions) * [The Backslash Plague](howto/regex#the-backslash-plague) * [Performing Matches](howto/regex#performing-matches) * [Module-Level Functions](howto/regex#module-level-functions) * [Compilation Flags](howto/regex#compilation-flags) - [More Pattern Power](howto/regex#more-pattern-power) * [More Metacharacters](howto/regex#more-metacharacters) * [Grouping](howto/regex#grouping) * [Non-capturing and Named Groups](howto/regex#non-capturing-and-named-groups) * [Lookahead Assertions](howto/regex#lookahead-assertions) - [Modifying Strings](howto/regex#modifying-strings) * [Splitting Strings](howto/regex#splitting-strings) * [Search and Replace](howto/regex#search-and-replace) - [Common Problems](howto/regex#common-problems) * [Use String Methods](howto/regex#use-string-methods) * [match() versus search()](howto/regex#match-versus-search) * [Greedy versus Non-Greedy](howto/regex#greedy-versus-non-greedy) * [Using re.VERBOSE](howto/regex#using-re-verbose) - [Feedback](howto/regex#feedback) + [Socket Programming HOWTO](howto/sockets) - [Sockets](howto/sockets#sockets) * [History](howto/sockets#history) - [Creating a Socket](howto/sockets#creating-a-socket) * [IPC](howto/sockets#ipc) - [Using a Socket](howto/sockets#using-a-socket) * [Binary Data](howto/sockets#binary-data) - [Disconnecting](howto/sockets#disconnecting) * [When Sockets Die](howto/sockets#when-sockets-die) - [Non-blocking Sockets](howto/sockets#non-blocking-sockets) + [Sorting HOW TO](howto/sorting) - [Sorting Basics](howto/sorting#sorting-basics) - [Key Functions](howto/sorting#key-functions) - [Operator Module Functions](howto/sorting#operator-module-functions) - [Ascending and Descending](howto/sorting#ascending-and-descending) - [Sort Stability and Complex Sorts](howto/sorting#sort-stability-and-complex-sorts) - [The Old Way Using Decorate-Sort-Undecorate](howto/sorting#the-old-way-using-decorate-sort-undecorate) - [The Old Way Using the cmp Parameter](howto/sorting#the-old-way-using-the-cmp-parameter) - [Odd and Ends](howto/sorting#odd-and-ends) + [Unicode HOWTO](howto/unicode) - [Introduction to Unicode](howto/unicode#introduction-to-unicode) * [Definitions](howto/unicode#definitions) * [Encodings](howto/unicode#encodings) * [References](howto/unicode#references) - [Python’s Unicode Support](howto/unicode#python-s-unicode-support) * [The String Type](howto/unicode#the-string-type) * [Converting to Bytes](howto/unicode#converting-to-bytes) * [Unicode Literals in Python Source Code](howto/unicode#unicode-literals-in-python-source-code) * [Unicode Properties](howto/unicode#unicode-properties) * [Comparing Strings](howto/unicode#comparing-strings) * [Unicode Regular Expressions](howto/unicode#unicode-regular-expressions) * [References](howto/unicode#id2) - [Reading and Writing Unicode Data](howto/unicode#reading-and-writing-unicode-data) * [Unicode filenames](howto/unicode#unicode-filenames) * [Tips for Writing Unicode-aware Programs](howto/unicode#tips-for-writing-unicode-aware-programs) + [Converting Between File Encodings](howto/unicode#converting-between-file-encodings) + [Files in an Unknown Encoding](howto/unicode#files-in-an-unknown-encoding) * [References](howto/unicode#id3) - [Acknowledgements](howto/unicode#acknowledgements) + [HOWTO Fetch Internet Resources Using The urllib Package](howto/urllib2) - [Introduction](howto/urllib2#introduction) - [Fetching URLs](howto/urllib2#fetching-urls) * [Data](howto/urllib2#data) * [Headers](howto/urllib2#headers) - [Handling Exceptions](howto/urllib2#handling-exceptions) * [URLError](howto/urllib2#urlerror) * [HTTPError](howto/urllib2#httperror) + [Error Codes](howto/urllib2#error-codes) * [Wrapping it Up](howto/urllib2#wrapping-it-up) + [Number 1](howto/urllib2#number-1) + [Number 2](howto/urllib2#number-2) - [info and geturl](howto/urllib2#info-and-geturl) - [Openers and Handlers](howto/urllib2#openers-and-handlers) - [Basic Authentication](howto/urllib2#id5) - [Proxies](howto/urllib2#proxies) - [Sockets and Layers](howto/urllib2#sockets-and-layers) - [Footnotes](howto/urllib2#footnotes) + [Argparse Tutorial](howto/argparse) - [Concepts](howto/argparse#concepts) - [The basics](howto/argparse#the-basics) - [Introducing Positional arguments](howto/argparse#introducing-positional-arguments) - [Introducing Optional arguments](howto/argparse#introducing-optional-arguments) * [Short options](howto/argparse#short-options) - [Combining Positional and Optional arguments](howto/argparse#combining-positional-and-optional-arguments) - [Getting a little more advanced](howto/argparse#getting-a-little-more-advanced) * [Conflicting options](howto/argparse#conflicting-options) - [Conclusion](howto/argparse#conclusion) + [An introduction to the ipaddress module](howto/ipaddress) - [Creating Address/Network/Interface objects](howto/ipaddress#creating-address-network-interface-objects) * [A Note on IP Versions](howto/ipaddress#a-note-on-ip-versions) * [IP Host Addresses](howto/ipaddress#ip-host-addresses) * [Defining Networks](howto/ipaddress#defining-networks) * [Host Interfaces](howto/ipaddress#host-interfaces) - [Inspecting Address/Network/Interface Objects](howto/ipaddress#inspecting-address-network-interface-objects) - [Networks as lists of Addresses](howto/ipaddress#networks-as-lists-of-addresses) - [Comparisons](howto/ipaddress#comparisons) - [Using IP Addresses with other modules](howto/ipaddress#using-ip-addresses-with-other-modules) - [Getting more detail when instance creation fails](howto/ipaddress#getting-more-detail-when-instance-creation-fails) + [Argument Clinic How-To](howto/clinic) - [The Goals Of Argument Clinic](howto/clinic#the-goals-of-argument-clinic) - [Basic Concepts And Usage](howto/clinic#basic-concepts-and-usage) - [Converting Your First Function](howto/clinic#converting-your-first-function) - [Advanced Topics](howto/clinic#advanced-topics) * [Symbolic default values](howto/clinic#symbolic-default-values) * [Renaming the C functions and variables generated by Argument Clinic](howto/clinic#renaming-the-c-functions-and-variables-generated-by-argument-clinic) * [Converting functions using PyArg\_UnpackTuple](howto/clinic#converting-functions-using-pyarg-unpacktuple) * [Optional Groups](howto/clinic#optional-groups) * [Using real Argument Clinic converters, instead of “legacy converters”](howto/clinic#using-real-argument-clinic-converters-instead-of-legacy-converters) * [Py\_buffer](howto/clinic#py-buffer) * [Advanced converters](howto/clinic#advanced-converters) * [Parameter default values](howto/clinic#parameter-default-values) * [The `NULL` default value](howto/clinic#the-null-default-value) * [Expressions specified as default values](howto/clinic#expressions-specified-as-default-values) * [Using a return converter](howto/clinic#using-a-return-converter) * [Cloning existing functions](howto/clinic#cloning-existing-functions) * [Calling Python code](howto/clinic#calling-python-code) * [Using a “self converter”](howto/clinic#using-a-self-converter) * [Writing a custom converter](howto/clinic#writing-a-custom-converter) * [Writing a custom return converter](howto/clinic#writing-a-custom-return-converter) * [METH\_O and METH\_NOARGS](howto/clinic#meth-o-and-meth-noargs) * [tp\_new and tp\_init functions](howto/clinic#tp-new-and-tp-init-functions) * [Changing and redirecting Clinic’s output](howto/clinic#changing-and-redirecting-clinic-s-output) * [The #ifdef trick](howto/clinic#the-ifdef-trick) * [Using Argument Clinic in Python files](howto/clinic#using-argument-clinic-in-python-files) + [Instrumenting CPython with DTrace and SystemTap](howto/instrumentation) - [Enabling the static markers](howto/instrumentation#enabling-the-static-markers) - [Static DTrace probes](howto/instrumentation#static-dtrace-probes) - [Static SystemTap markers](howto/instrumentation#static-systemtap-markers) - [Available static markers](howto/instrumentation#available-static-markers) - [SystemTap Tapsets](howto/instrumentation#systemtap-tapsets) - [Examples](howto/instrumentation#examples) * [Python Frequently Asked Questions](faq/index) + [General Python FAQ](faq/general) - [General Information](faq/general#general-information) - [Python in the real world](faq/general#python-in-the-real-world) + [Programming FAQ](faq/programming) - [General Questions](faq/programming#general-questions) - [Core Language](faq/programming#core-language) - [Numbers and strings](faq/programming#numbers-and-strings) - [Performance](faq/programming#performance) - [Sequences (Tuples/Lists)](faq/programming#sequences-tuples-lists) - [Objects](faq/programming#objects) - [Modules](faq/programming#modules) + [Design and History FAQ](faq/design) - [Why does Python use indentation for grouping of statements?](faq/design#why-does-python-use-indentation-for-grouping-of-statements) - [Why am I getting strange results with simple arithmetic operations?](faq/design#why-am-i-getting-strange-results-with-simple-arithmetic-operations) - [Why are floating-point calculations so inaccurate?](faq/design#why-are-floating-point-calculations-so-inaccurate) - [Why are Python strings immutable?](faq/design#why-are-python-strings-immutable) - [Why must ‘self’ be used explicitly in method definitions and calls?](faq/design#why-must-self-be-used-explicitly-in-method-definitions-and-calls) - [Why can’t I use an assignment in an expression?](faq/design#why-can-t-i-use-an-assignment-in-an-expression) - [Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?](faq/design#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list) - [Why is join() a string method instead of a list or tuple method?](faq/design#why-is-join-a-string-method-instead-of-a-list-or-tuple-method) - [How fast are exceptions?](faq/design#how-fast-are-exceptions) - [Why isn’t there a switch or case statement in Python?](faq/design#why-isn-t-there-a-switch-or-case-statement-in-python) - [Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?](faq/design#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation) - [Why can’t lambda expressions contain statements?](faq/design#why-can-t-lambda-expressions-contain-statements) - [Can Python be compiled to machine code, C or some other language?](faq/design#can-python-be-compiled-to-machine-code-c-or-some-other-language) - [How does Python manage memory?](faq/design#how-does-python-manage-memory) - [Why doesn’t CPython use a more traditional garbage collection scheme?](faq/design#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme) - [Why isn’t all memory freed when CPython exits?](faq/design#why-isn-t-all-memory-freed-when-cpython-exits) - [Why are there separate tuple and list data types?](faq/design#why-are-there-separate-tuple-and-list-data-types) - [How are lists implemented in CPython?](faq/design#how-are-lists-implemented-in-cpython) - [How are dictionaries implemented in CPython?](faq/design#how-are-dictionaries-implemented-in-cpython) - [Why must dictionary keys be immutable?](faq/design#why-must-dictionary-keys-be-immutable) - [Why doesn’t list.sort() return the sorted list?](faq/design#why-doesn-t-list-sort-return-the-sorted-list) - [How do you specify and enforce an interface spec in Python?](faq/design#how-do-you-specify-and-enforce-an-interface-spec-in-python) - [Why is there no goto?](faq/design#why-is-there-no-goto) - [Why can’t raw strings (r-strings) end with a backslash?](faq/design#why-can-t-raw-strings-r-strings-end-with-a-backslash) - [Why doesn’t Python have a “with” statement for attribute assignments?](faq/design#why-doesn-t-python-have-a-with-statement-for-attribute-assignments) - [Why don’t generators support the with statement?](faq/design#why-don-t-generators-support-the-with-statement) - [Why are colons required for the if/while/def/class statements?](faq/design#why-are-colons-required-for-the-if-while-def-class-statements) - [Why does Python allow commas at the end of lists and tuples?](faq/design#why-does-python-allow-commas-at-the-end-of-lists-and-tuples) + [Library and Extension FAQ](faq/library) - [General Library Questions](faq/library#general-library-questions) - [Common tasks](faq/library#common-tasks) - [Threads](faq/library#threads) - [Input and Output](faq/library#input-and-output) - [Network/Internet Programming](faq/library#network-internet-programming) - [Databases](faq/library#databases) - [Mathematics and Numerics](faq/library#mathematics-and-numerics) + [Extending/Embedding FAQ](faq/extending) - [Can I create my own functions in C?](faq/extending#can-i-create-my-own-functions-in-c) - [Can I create my own functions in C++?](faq/extending#id1) - [Writing C is hard; are there any alternatives?](faq/extending#writing-c-is-hard-are-there-any-alternatives) - [How can I execute arbitrary Python statements from C?](faq/extending#how-can-i-execute-arbitrary-python-statements-from-c) - [How can I evaluate an arbitrary Python expression from C?](faq/extending#how-can-i-evaluate-an-arbitrary-python-expression-from-c) - [How do I extract C values from a Python object?](faq/extending#how-do-i-extract-c-values-from-a-python-object) - [How do I use Py\_BuildValue() to create a tuple of arbitrary length?](faq/extending#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length) - [How do I call an object’s method from C?](faq/extending#how-do-i-call-an-object-s-method-from-c) - [How do I catch the output from PyErr\_Print() (or anything that prints to stdout/stderr)?](faq/extending#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr) - [How do I access a module written in Python from C?](faq/extending#how-do-i-access-a-module-written-in-python-from-c) - [How do I interface to C++ objects from Python?](faq/extending#how-do-i-interface-to-c-objects-from-python) - [I added a module using the Setup file and the make fails; why?](faq/extending#i-added-a-module-using-the-setup-file-and-the-make-fails-why) - [How do I debug an extension?](faq/extending#how-do-i-debug-an-extension) - [I want to compile a Python module on my Linux system, but some files are missing. Why?](faq/extending#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why) - [How do I tell “incomplete input” from “invalid input”?](faq/extending#how-do-i-tell-incomplete-input-from-invalid-input) - [How do I find undefined g++ symbols \_\_builtin\_new or \_\_pure\_virtual?](faq/extending#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual) - [Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?](faq/extending#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance) + [Python on Windows FAQ](faq/windows) - [How do I run a Python program under Windows?](faq/windows#how-do-i-run-a-python-program-under-windows) - [How do I make Python scripts executable?](faq/windows#how-do-i-make-python-scripts-executable) - [Why does Python sometimes take so long to start?](faq/windows#why-does-python-sometimes-take-so-long-to-start) - [How do I make an executable from a Python script?](faq/windows#how-do-i-make-an-executable-from-a-python-script) - [Is a `*.pyd` file the same as a DLL?](faq/windows#is-a-pyd-file-the-same-as-a-dll) - [How can I embed Python into a Windows application?](faq/windows#how-can-i-embed-python-into-a-windows-application) - [How do I keep editors from inserting tabs into my Python source?](faq/windows#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source) - [How do I check for a keypress without blocking?](faq/windows#how-do-i-check-for-a-keypress-without-blocking) + [Graphic User Interface FAQ](faq/gui) - [General GUI Questions](faq/gui#general-gui-questions) - [What GUI toolkits exist for Python?](faq/gui#what-gui-toolkits-exist-for-python) - [Tkinter questions](faq/gui#tkinter-questions) + [“Why is Python Installed on my Computer?” FAQ](faq/installed) - [What is Python?](faq/installed#what-is-python) - [Why is Python installed on my machine?](faq/installed#why-is-python-installed-on-my-machine) - [Can I delete Python?](faq/installed#can-i-delete-python) * [Glossary](glossary) * [About these documents](about) + [Contributors to the Python Documentation](about#contributors-to-the-python-documentation) * [Dealing with Bugs](bugs) + [Documentation bugs](bugs#documentation-bugs) + [Using the Python issue tracker](bugs#using-the-python-issue-tracker) + [Getting started contributing to Python yourself](bugs#getting-started-contributing-to-python-yourself) * [Copyright](copyright) * [History and License](license) + [History of the software](license#history-of-the-software) + [Terms and conditions for accessing or otherwise using Python](license#terms-and-conditions-for-accessing-or-otherwise-using-python) - [PSF LICENSE AGREEMENT FOR PYTHON 3.9.14](license#psf-license-agreement-for-python-release) - [BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0](license#beopen-com-license-agreement-for-python-2-0) - [CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1](license#cnri-license-agreement-for-python-1-6-1) - [CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2](license#cwi-license-agreement-for-python-0-9-0-through-1-2) - [ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.14 DOCUMENTATION](license#zero-clause-bsd-license-for-code-in-the-python-release-documentation) + [Licenses and Acknowledgements for Incorporated Software](license#licenses-and-acknowledgements-for-incorporated-software) - [Mersenne Twister](license#mersenne-twister) - [Sockets](license#sockets) - [Asynchronous socket services](license#asynchronous-socket-services) - [Cookie management](license#cookie-management) - [Execution tracing](license#execution-tracing) - [UUencode and UUdecode functions](license#uuencode-and-uudecode-functions) - [XML Remote Procedure Calls](license#xml-remote-procedure-calls) - [test\_epoll](license#test-epoll) - [Select kqueue](license#select-kqueue) - [SipHash24](license#siphash24) - [strtod and dtoa](license#strtod-and-dtoa) - [OpenSSL](license#openssl) - [expat](license#expat) - [libffi](license#libffi) - [zlib](license#zlib) - [cfuhash](license#cfuhash) - [libmpdec](license#libmpdec) - [W3C C14N test suite](license#w3c-c14n-test-suite)
programming_docs
python Python Module Index Python Module Index =================== [**\_**](#cap-_) | [**a**](#cap-a) | [**b**](#cap-b) | [**c**](#cap-c) | [**d**](#cap-d) | [**e**](#cap-e) | [**f**](#cap-f) | [**g**](#cap-g) | [**h**](#cap-h) | [**i**](#cap-i) | [**j**](#cap-j) | [**k**](#cap-k) | [**l**](#cap-l) | [**m**](#cap-m) | [**n**](#cap-n) | [**o**](#cap-o) | [**p**](#cap-p) | [**q**](#cap-q) | [**r**](#cap-r) | [**s**](#cap-s) | [**t**](#cap-t) | [**u**](#cap-u) | [**v**](#cap-v) | [**w**](#cap-w) | [**x**](#cap-x) | [**z**](#cap-z) | | | | | --- | --- | --- | | | | | | | **\_** | | | | [`__future__`](library/__future__#module-__future__) | *Future statement definitions* | | | [`__main__`](library/__main__#module-__main__) | *The environment where the top-level script is run.* | | | [`_thread`](library/_thread#module-_thread) | *Low-level threading API.* | | | | | | | **a** | | | | [`abc`](library/abc#module-abc) | *Abstract base classes according to :pep:`3119`.* | | | [`aifc`](library/aifc#module-aifc) | **Deprecated:** *Read and write audio files in AIFF or AIFC format.* | | | [`argparse`](library/argparse#module-argparse) | *Command-line option and argument parsing library.* | | | [`array`](library/array#module-array) | *Space efficient arrays of uniformly typed numeric values.* | | | [`ast`](library/ast#module-ast) | *Abstract Syntax Tree classes and manipulation.* | | | [`asynchat`](library/asynchat#module-asynchat) | **Deprecated:** *Support for asynchronous command/response protocols.* | | | [`asyncio`](library/asyncio#module-asyncio) | *Asynchronous I/O.* | | | [`asyncore`](library/asyncore#module-asyncore) | **Deprecated:** *A base class for developing asynchronous socket handling services.* | | | [`atexit`](library/atexit#module-atexit) | *Register and execute cleanup functions.* | | | [`audioop`](library/audioop#module-audioop) | **Deprecated:** *Manipulate raw audio data.* | | | | | | | **b** | | | | [`base64`](library/base64#module-base64) | *RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85* | | | [`bdb`](library/bdb#module-bdb) | *Debugger framework.* | | | [`binascii`](library/binascii#module-binascii) | *Tools for converting between binary and various ASCII-encoded binary representations.* | | | [`binhex`](library/binhex#module-binhex) | *Encode and decode files in binhex4 format.* | | | [`bisect`](library/bisect#module-bisect) | *Array bisection algorithms for binary searching.* | | | [`builtins`](library/builtins#module-builtins) | *The module that provides the built-in namespace.* | | | [`bz2`](library/bz2#module-bz2) | *Interfaces for bzip2 compression and decompression.* | | | | | | | **c** | | | | [`calendar`](library/calendar#module-calendar) | *Functions for working with calendars, including some emulation of the Unix cal program.* | | | [`cgi`](library/cgi#module-cgi) | **Deprecated:** *Helpers for running Python scripts via the Common Gateway Interface.* | | | [`cgitb`](library/cgitb#module-cgitb) | **Deprecated:** *Configurable traceback handler for CGI scripts.* | | | [`chunk`](library/chunk#module-chunk) | **Deprecated:** *Module to read IFF chunks.* | | | [`cmath`](library/cmath#module-cmath) | *Mathematical functions for complex numbers.* | | | [`cmd`](library/cmd#module-cmd) | *Build line-oriented command interpreters.* | | | [`code`](library/code#module-code) | *Facilities to implement read-eval-print loops.* | | | [`codecs`](library/codecs#module-codecs) | *Encode and decode data and streams.* | | | [`codeop`](library/codeop#module-codeop) | *Compile (possibly incomplete) Python code.* | | | [`collections`](library/collections#module-collections) | *Container datatypes* | | | [`collections.abc`](library/collections.abc#module-collections.abc) | *Abstract base classes for containers* | | | [`colorsys`](library/colorsys#module-colorsys) | *Conversion functions between RGB and other color systems.* | | | [`compileall`](library/compileall#module-compileall) | *Tools for byte-compiling all Python source files in a directory tree.* | | | `concurrent` | | | | [`concurrent.futures`](library/concurrent.futures#module-concurrent.futures) | *Execute computations concurrently using threads or processes.* | | | [`configparser`](library/configparser#module-configparser) | *Configuration file parser.* | | | [`contextlib`](library/contextlib#module-contextlib) | *Utilities for with-statement contexts.* | | | [`contextvars`](library/contextvars#module-contextvars) | *Context Variables* | | | [`copy`](library/copy#module-copy) | *Shallow and deep copy operations.* | | | [`copyreg`](library/copyreg#module-copyreg) | *Register pickle support functions.* | | | [`cProfile`](library/profile#module-cProfile) | | | | [`crypt`](library/crypt#module-crypt) *(Unix)* | **Deprecated:** *The crypt() function used to check Unix passwords.* | | | [`csv`](library/csv#module-csv) | *Write and read tabular data to and from delimited files.* | | | [`ctypes`](library/ctypes#module-ctypes) | *A foreign function library for Python.* | | | [`curses`](library/curses#module-curses) *(Unix)* | *An interface to the curses library, providing portable terminal handling.* | | | [`curses.ascii`](library/curses.ascii#module-curses.ascii) | *Constants and set-membership functions for ASCII characters.* | | | [`curses.panel`](library/curses.panel#module-curses.panel) | *A panel stack extension that adds depth to curses windows.* | | | [`curses.textpad`](library/curses#module-curses.textpad) | *Emacs-like input editing in a curses window.* | | | | | | | **d** | | | | [`dataclasses`](library/dataclasses#module-dataclasses) | *Generate special methods on user-defined classes.* | | | [`datetime`](library/datetime#module-datetime) | *Basic date and time types.* | | | [`dbm`](library/dbm#module-dbm) | *Interfaces to various Unix "database" formats.* | | | [`dbm.dumb`](library/dbm#module-dbm.dumb) | *Portable implementation of the simple DBM interface.* | | | [`dbm.gnu`](library/dbm#module-dbm.gnu) *(Unix)* | *GNU's reinterpretation of dbm.* | | | [`dbm.ndbm`](library/dbm#module-dbm.ndbm) *(Unix)* | *The standard "database" interface, based on ndbm.* | | | [`decimal`](library/decimal#module-decimal) | *Implementation of the General Decimal Arithmetic Specification.* | | | [`difflib`](library/difflib#module-difflib) | *Helpers for computing differences between objects.* | | | [`dis`](library/dis#module-dis) | *Disassembler for Python bytecode.* | | | [`distutils`](library/distutils#module-distutils) | *Support for building and installing Python modules into an existing Python installation.* | | | [`distutils.archive_util`](distutils/apiref#module-distutils.archive_util) | *Utility functions for creating archive files (tarballs, zip files, ...)* | | | [`distutils.bcppcompiler`](distutils/apiref#module-distutils.bcppcompiler) | | | | [`distutils.ccompiler`](distutils/apiref#module-distutils.ccompiler) | *Abstract CCompiler class* | | | [`distutils.cmd`](distutils/apiref#module-distutils.cmd) | *Provides the abstract base class :class:`~distutils.cmd.Command`. This class is subclassed by the modules in the distutils.command subpackage.* | | | [`distutils.command`](distutils/apiref#module-distutils.command) | *Contains one module for each standard Distutils command.* | | | [`distutils.command.bdist`](distutils/apiref#module-distutils.command.bdist) | *Build a binary installer for a package* | | | [`distutils.command.bdist_dumb`](distutils/apiref#module-distutils.command.bdist_dumb) | *Build a "dumb" installer - a simple archive of files* | | | [`distutils.command.bdist_msi`](distutils/apiref#module-distutils.command.bdist_msi) | *Build a binary distribution as a Windows MSI file* | | | [`distutils.command.bdist_packager`](distutils/apiref#module-distutils.command.bdist_packager) | *Abstract base class for packagers* | | | [`distutils.command.bdist_rpm`](distutils/apiref#module-distutils.command.bdist_rpm) | *Build a binary distribution as a Redhat RPM and SRPM* | | | [`distutils.command.bdist_wininst`](distutils/apiref#module-distutils.command.bdist_wininst) | *Build a Windows installer* | | | [`distutils.command.build`](distutils/apiref#module-distutils.command.build) | *Build all files of a package* | | | [`distutils.command.build_clib`](distutils/apiref#module-distutils.command.build_clib) | *Build any C libraries in a package* | | | [`distutils.command.build_ext`](distutils/apiref#module-distutils.command.build_ext) | *Build any extensions in a package* | | | [`distutils.command.build_py`](distutils/apiref#module-distutils.command.build_py) | *Build the .py/.pyc files of a package* | | | [`distutils.command.build_scripts`](distutils/apiref#module-distutils.command.build_scripts) | *Build the scripts of a package* | | | [`distutils.command.check`](distutils/apiref#module-distutils.command.check) | *Check the meta-data of a package* | | | [`distutils.command.clean`](distutils/apiref#module-distutils.command.clean) | *Clean a package build area* | | | [`distutils.command.config`](distutils/apiref#module-distutils.command.config) | *Perform package configuration* | | | [`distutils.command.install`](distutils/apiref#module-distutils.command.install) | *Install a package* | | | [`distutils.command.install_data`](distutils/apiref#module-distutils.command.install_data) | *Install data files from a package* | | | [`distutils.command.install_headers`](distutils/apiref#module-distutils.command.install_headers) | *Install C/C++ header files from a package* | | | [`distutils.command.install_lib`](distutils/apiref#module-distutils.command.install_lib) | *Install library files from a package* | | | [`distutils.command.install_scripts`](distutils/apiref#module-distutils.command.install_scripts) | *Install script files from a package* | | | [`distutils.command.register`](distutils/apiref#module-distutils.command.register) | *Register a module with the Python Package Index* | | | [`distutils.command.sdist`](distutils/apiref#module-distutils.command.sdist) | *Build a source distribution* | | | [`distutils.core`](distutils/apiref#module-distutils.core) | *The core Distutils functionality* | | | [`distutils.cygwinccompiler`](distutils/apiref#module-distutils.cygwinccompiler) | | | | [`distutils.debug`](distutils/apiref#module-distutils.debug) | *Provides the debug flag for distutils* | | | [`distutils.dep_util`](distutils/apiref#module-distutils.dep_util) | *Utility functions for simple dependency checking* | | | [`distutils.dir_util`](distutils/apiref#module-distutils.dir_util) | *Utility functions for operating on directories and directory trees* | | | [`distutils.dist`](distutils/apiref#module-distutils.dist) | *Provides the Distribution class, which represents the module distribution being built/installed/distributed* | | | [`distutils.errors`](distutils/apiref#module-distutils.errors) | *Provides standard distutils exceptions* | | | [`distutils.extension`](distutils/apiref#module-distutils.extension) | *Provides the Extension class, used to describe C/C++ extension modules in setup scripts* | | | [`distutils.fancy_getopt`](distutils/apiref#module-distutils.fancy_getopt) | *Additional getopt functionality* | | | [`distutils.file_util`](distutils/apiref#module-distutils.file_util) | *Utility functions for operating on single files* | | | [`distutils.filelist`](distutils/apiref#module-distutils.filelist) | *The FileList class, used for poking about the file system and building lists of files.* | | | [`distutils.log`](distutils/apiref#module-distutils.log) | *A simple logging mechanism, :pep:`282`-style* | | | [`distutils.msvccompiler`](distutils/apiref#module-distutils.msvccompiler) | *Microsoft Compiler* | | | [`distutils.spawn`](distutils/apiref#module-distutils.spawn) | *Provides the spawn() function* | | | [`distutils.sysconfig`](distutils/apiref#module-distutils.sysconfig) | *Low-level access to configuration information of the Python interpreter.* | | | [`distutils.text_file`](distutils/apiref#module-distutils.text_file) | *Provides the TextFile class, a simple interface to text files* | | | [`distutils.unixccompiler`](distutils/apiref#module-distutils.unixccompiler) | *UNIX C Compiler* | | | [`distutils.util`](distutils/apiref#module-distutils.util) | *Miscellaneous other utility functions* | | | [`distutils.version`](distutils/apiref#module-distutils.version) | *Implements classes that represent module version numbers.* | | | [`doctest`](library/doctest#module-doctest) | *Test pieces of code within docstrings.* | | | | | | | **e** | | | | [`email`](library/email#module-email) | *Package supporting the parsing, manipulating, and generating email messages.* | | | [`email.charset`](library/email.charset#module-email.charset) | *Character Sets* | | | [`email.contentmanager`](library/email.contentmanager#module-email.contentmanager) | *Storing and Retrieving Content from MIME Parts* | | | [`email.encoders`](library/email.encoders#module-email.encoders) | *Encoders for email message payloads.* | | | [`email.errors`](library/email.errors#module-email.errors) | *The exception classes used by the email package.* | | | [`email.generator`](library/email.generator#module-email.generator) | *Generate flat text email messages from a message structure.* | | | [`email.header`](library/email.header#module-email.header) | *Representing non-ASCII headers* | | | [`email.headerregistry`](library/email.headerregistry#module-email.headerregistry) | *Automatic Parsing of headers based on the field name* | | | [`email.iterators`](library/email.iterators#module-email.iterators) | *Iterate over a message object tree.* | | | [`email.message`](library/email.message#module-email.message) | *The base class representing email messages.* | | | [`email.mime`](library/email.mime#module-email.mime) | *Build MIME messages.* | | | [`email.parser`](library/email.parser#module-email.parser) | *Parse flat text email messages to produce a message object structure.* | | | [`email.policy`](library/email.policy#module-email.policy) | *Controlling the parsing and generating of messages* | | | [`email.utils`](library/email.utils#module-email.utils) | *Miscellaneous email package utilities.* | | | `encodings` | | | | [`encodings.idna`](library/codecs#module-encodings.idna) | *Internationalized Domain Names implementation* | | | [`encodings.mbcs`](library/codecs#module-encodings.mbcs) | *Windows ANSI codepage* | | | [`encodings.utf_8_sig`](library/codecs#module-encodings.utf_8_sig) | *UTF-8 codec with BOM signature* | | | [`ensurepip`](library/ensurepip#module-ensurepip) | *Bootstrapping the "pip" installer into an existing Python installation or virtual environment.* | | | [`enum`](library/enum#module-enum) | *Implementation of an enumeration class.* | | | [`errno`](library/errno#module-errno) | *Standard errno system symbols.* | | | | | | | **f** | | | | [`faulthandler`](library/faulthandler#module-faulthandler) | *Dump the Python traceback.* | | | [`fcntl`](library/fcntl#module-fcntl) *(Unix)* | *The fcntl() and ioctl() system calls.* | | | [`filecmp`](library/filecmp#module-filecmp) | *Compare files efficiently.* | | | [`fileinput`](library/fileinput#module-fileinput) | *Loop over standard input or a list of files.* | | | [`fnmatch`](library/fnmatch#module-fnmatch) | *Unix shell style filename pattern matching.* | | | [`formatter`](https://docs.python.org/3.9/library/formatter.html#module-formatter) | **Deprecated:** *Generic output formatter and device interface.* | | | [`fractions`](library/fractions#module-fractions) | *Rational numbers.* | | | [`ftplib`](library/ftplib#module-ftplib) | *FTP protocol client (requires sockets).* | | | [`functools`](library/functools#module-functools) | *Higher-order functions and operations on callable objects.* | | | | | | | **g** | | | | [`gc`](library/gc#module-gc) | *Interface to the cycle-detecting garbage collector.* | | | [`getopt`](library/getopt#module-getopt) | *Portable parser for command line options; support both short and long option names.* | | | [`getpass`](library/getpass#module-getpass) | *Portable reading of passwords and retrieval of the userid.* | | | [`gettext`](library/gettext#module-gettext) | *Multilingual internationalization services.* | | | [`glob`](library/glob#module-glob) | *Unix shell style pathname pattern expansion.* | | | [`graphlib`](library/graphlib#module-graphlib) | *Functionality to operate with graph-like structures* | | | [`grp`](library/grp#module-grp) *(Unix)* | *The group database (getgrnam() and friends).* | | | [`gzip`](library/gzip#module-gzip) | *Interfaces for gzip compression and decompression using file objects.* | | | | | | | **h** | | | | [`hashlib`](library/hashlib#module-hashlib) | *Secure hash and message digest algorithms.* | | | [`heapq`](library/heapq#module-heapq) | *Heap queue algorithm (a.k.a. priority queue).* | | | [`hmac`](library/hmac#module-hmac) | *Keyed-Hashing for Message Authentication (HMAC) implementation* | | | [`html`](library/html#module-html) | *Helpers for manipulating HTML.* | | | [`html.entities`](library/html.entities#module-html.entities) | *Definitions of HTML general entities.* | | | [`html.parser`](library/html.parser#module-html.parser) | *A simple parser that can handle HTML and XHTML.* | | | [`http`](library/http#module-http) | *HTTP status codes and messages* | | | [`http.client`](library/http.client#module-http.client) | *HTTP and HTTPS protocol client (requires sockets).* | | | [`http.cookiejar`](library/http.cookiejar#module-http.cookiejar) | *Classes for automatic handling of HTTP cookies.* | | | [`http.cookies`](library/http.cookies#module-http.cookies) | *Support for HTTP state management (cookies).* | | | [`http.server`](library/http.server#module-http.server) | *HTTP server and request handlers.* | | | | | | | **i** | | | | [`imaplib`](library/imaplib#module-imaplib) | *IMAP4 protocol client (requires sockets).* | | | [`imghdr`](library/imghdr#module-imghdr) | **Deprecated:** *Determine the type of image contained in a file or byte stream.* | | | [`imp`](library/imp#module-imp) | **Deprecated:** *Access the implementation of the import statement.* | | | [`importlib`](library/importlib#module-importlib) | *The implementation of the import machinery.* | | | [`importlib.abc`](library/importlib#module-importlib.abc) | *Abstract base classes related to import* | | | [`importlib.machinery`](library/importlib#module-importlib.machinery) | *Importers and path hooks* | | | [`importlib.metadata`](library/importlib.metadata#module-importlib.metadata) | *The implementation of the importlib metadata.* | | | [`importlib.resources`](library/importlib#module-importlib.resources) | *Package resource reading, opening, and access* | | | [`importlib.util`](library/importlib#module-importlib.util) | *Utility code for importers* | | | [`inspect`](library/inspect#module-inspect) | *Extract information and source code from live objects.* | | | [`io`](library/io#module-io) | *Core tools for working with streams.* | | | [`ipaddress`](library/ipaddress#module-ipaddress) | *IPv4/IPv6 manipulation library.* | | | [`itertools`](library/itertools#module-itertools) | *Functions creating iterators for efficient looping.* | | | | | | | **j** | | | | [`json`](library/json#module-json) | *Encode and decode the JSON format.* | | | [`json.tool`](library/json#module-json.tool) | *A command line to validate and pretty-print JSON.* | | | | | | | **k** | | | | [`keyword`](library/keyword#module-keyword) | *Test whether a string is a keyword in Python.* | | | | | | | **l** | | | | [`lib2to3`](https://docs.python.org/3.9/library/2to3.html#module-lib2to3) | *The 2to3 library* | | | [`linecache`](library/linecache#module-linecache) | *Provides random access to individual lines from text files.* | | | [`locale`](library/locale#module-locale) | *Internationalization services.* | | | [`logging`](library/logging#module-logging) | *Flexible event logging system for applications.* | | | [`logging.config`](library/logging.config#module-logging.config) | *Configuration of the logging module.* | | | [`logging.handlers`](library/logging.handlers#module-logging.handlers) | *Handlers for the logging module.* | | | [`lzma`](library/lzma#module-lzma) | *A Python wrapper for the liblzma compression library.* | | | | | | | **m** | | | | [`mailbox`](library/mailbox#module-mailbox) | *Manipulate mailboxes in various formats* | | | [`mailcap`](library/mailcap#module-mailcap) | **Deprecated:** *Mailcap file handling.* | | | [`marshal`](library/marshal#module-marshal) | *Convert Python objects to streams of bytes and back (with different constraints).* | | | [`math`](library/math#module-math) | *Mathematical functions (sin() etc.).* | | | [`mimetypes`](library/mimetypes#module-mimetypes) | *Mapping of filename extensions to MIME types.* | | | [`mmap`](library/mmap#module-mmap) | *Interface to memory-mapped files for Unix and Windows.* | | | [`modulefinder`](library/modulefinder#module-modulefinder) | *Find modules used by a script.* | | | [`msilib`](library/msilib#module-msilib) *(Windows)* | **Deprecated:** *Creation of Microsoft Installer files, and CAB files.* | | | [`msvcrt`](library/msvcrt#module-msvcrt) *(Windows)* | *Miscellaneous useful routines from the MS VC++ runtime.* | | | [`multiprocessing`](library/multiprocessing#module-multiprocessing) | *Process-based parallelism.* | | | [`multiprocessing.connection`](library/multiprocessing#module-multiprocessing.connection) | *API for dealing with sockets.* | | | [`multiprocessing.dummy`](library/multiprocessing#module-multiprocessing.dummy) | *Dumb wrapper around threading.* | | | [`multiprocessing.managers`](library/multiprocessing#module-multiprocessing.managers) | *Share data between process with shared objects.* | | | [`multiprocessing.pool`](library/multiprocessing#module-multiprocessing.pool) | *Create pools of processes.* | | | [`multiprocessing.shared_memory`](library/multiprocessing.shared_memory#module-multiprocessing.shared_memory) | *Provides shared memory for direct access across processes.* | | | [`multiprocessing.sharedctypes`](library/multiprocessing#module-multiprocessing.sharedctypes) | *Allocate ctypes objects from shared memory.* | | | | | | | **n** | | | | [`netrc`](library/netrc#module-netrc) | *Loading of .netrc files.* | | | [`nis`](library/nis#module-nis) *(Unix)* | **Deprecated:** *Interface to Sun's NIS (Yellow Pages) library.* | | | [`nntplib`](library/nntplib#module-nntplib) | **Deprecated:** *NNTP protocol client (requires sockets).* | | | [`numbers`](library/numbers#module-numbers) | *Numeric abstract base classes (Complex, Real, Integral, etc.).* | | | | | | | **o** | | | | [`operator`](library/operator#module-operator) | *Functions corresponding to the standard operators.* | | | [`optparse`](library/optparse#module-optparse) | **Deprecated:** *Command-line option parsing library.* | | | [`os`](library/os#module-os) | *Miscellaneous operating system interfaces.* | | | [`os.path`](library/os.path#module-os.path) | *Operations on pathnames.* | | | [`ossaudiodev`](library/ossaudiodev#module-ossaudiodev) *(Linux, FreeBSD)* | **Deprecated:** *Access to OSS-compatible audio devices.* | | | | | | | **p** | | | | [`parser`](library/parser#module-parser) | *Access parse trees for Python source code.* | | | [`pathlib`](library/pathlib#module-pathlib) | *Object-oriented filesystem paths* | | | [`pdb`](library/pdb#module-pdb) | *The Python debugger for interactive interpreters.* | | | [`pickle`](library/pickle#module-pickle) | *Convert Python objects to streams of bytes and back.* | | | [`pickletools`](library/pickletools#module-pickletools) | *Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.* | | | [`pipes`](library/pipes#module-pipes) *(Unix)* | **Deprecated:** *A Python interface to Unix shell pipelines.* | | | [`pkgutil`](library/pkgutil#module-pkgutil) | *Utilities for the import system.* | | | [`platform`](library/platform#module-platform) | *Retrieves as much platform identifying data as possible.* | | | [`plistlib`](library/plistlib#module-plistlib) | *Generate and parse Apple plist files.* | | | [`poplib`](library/poplib#module-poplib) | *POP3 protocol client (requires sockets).* | | | [`posix`](library/posix#module-posix) *(Unix)* | *The most common POSIX system calls (normally used via module os).* | | | [`pprint`](library/pprint#module-pprint) | *Data pretty printer.* | | | [`profile`](library/profile#module-profile) | *Python source profiler.* | | | [`pstats`](library/profile#module-pstats) | *Statistics object for use with the profiler.* | | | [`pty`](library/pty#module-pty) *(Linux)* | *Pseudo-Terminal Handling for Linux.* | | | [`pwd`](library/pwd#module-pwd) *(Unix)* | *The password database (getpwnam() and friends).* | | | [`py_compile`](library/py_compile#module-py_compile) | *Generate byte-code files from Python source files.* | | | [`pyclbr`](library/pyclbr#module-pyclbr) | *Supports information extraction for a Python module browser.* | | | [`pydoc`](library/pydoc#module-pydoc) | *Documentation generator and online help system.* | | | | | | | **q** | | | | [`queue`](library/queue#module-queue) | *A synchronized queue class.* | | | [`quopri`](library/quopri#module-quopri) | *Encode and decode files using the MIME quoted-printable encoding.* | | | | | | | **r** | | | | [`random`](library/random#module-random) | *Generate pseudo-random numbers with various common distributions.* | | | [`re`](library/re#module-re) | *Regular expression operations.* | | | [`readline`](library/readline#module-readline) *(Unix)* | *GNU readline support for Python.* | | | [`reprlib`](library/reprlib#module-reprlib) | *Alternate repr() implementation with size limits.* | | | [`resource`](library/resource#module-resource) *(Unix)* | *An interface to provide resource usage information on the current process.* | | | [`rlcompleter`](library/rlcompleter#module-rlcompleter) | *Python identifier completion, suitable for the GNU readline library.* | | | [`runpy`](library/runpy#module-runpy) | *Locate and run Python modules without importing them first.* | | | | | | | **s** | | | | [`sched`](library/sched#module-sched) | *General purpose event scheduler.* | | | [`secrets`](library/secrets#module-secrets) | *Generate secure random numbers for managing secrets.* | | | [`select`](library/select#module-select) | *Wait for I/O completion on multiple streams.* | | | [`selectors`](library/selectors#module-selectors) | *High-level I/O multiplexing.* | | | [`shelve`](library/shelve#module-shelve) | *Python object persistence.* | | | [`shlex`](library/shlex#module-shlex) | *Simple lexical analysis for Unix shell-like languages.* | | | [`shutil`](library/shutil#module-shutil) | *High-level file operations, including copying.* | | | [`signal`](library/signal#module-signal) | *Set handlers for asynchronous events.* | | | [`site`](library/site#module-site) | *Module responsible for site-specific configuration.* | | | [`smtpd`](library/smtpd#module-smtpd) | **Deprecated:** *A SMTP server implementation in Python.* | | | [`smtplib`](library/smtplib#module-smtplib) | *SMTP protocol client (requires sockets).* | | | [`sndhdr`](library/sndhdr#module-sndhdr) | **Deprecated:** *Determine type of a sound file.* | | | [`socket`](library/socket#module-socket) | *Low-level networking interface.* | | | [`socketserver`](library/socketserver#module-socketserver) | *A framework for network servers.* | | | [`spwd`](library/spwd#module-spwd) *(Unix)* | **Deprecated:** *The shadow password database (getspnam() and friends).* | | | [`sqlite3`](library/sqlite3#module-sqlite3) | *A DB-API 2.0 implementation using SQLite 3.x.* | | | [`ssl`](library/ssl#module-ssl) | *TLS/SSL wrapper for socket objects* | | | [`stat`](library/stat#module-stat) | *Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().* | | | [`statistics`](library/statistics#module-statistics) | *Mathematical statistics functions* | | | [`string`](library/string#module-string) | *Common string operations.* | | | [`stringprep`](library/stringprep#module-stringprep) | *String preparation, as per RFC 3453* | | | [`struct`](library/struct#module-struct) | *Interpret bytes as packed binary data.* | | | [`subprocess`](library/subprocess#module-subprocess) | *Subprocess management.* | | | [`sunau`](https://docs.python.org/3.9/library/sunau.html#module-sunau) | **Deprecated:** *Provide an interface to the Sun AU sound format.* | | | [`symbol`](library/symbol#module-symbol) | *Constants representing internal nodes of the parse tree.* | | | [`symtable`](library/symtable#module-symtable) | *Interface to the compiler's internal symbol tables.* | | | [`sys`](library/sys#module-sys) | *Access system-specific parameters and functions.* | | | [`sysconfig`](library/sysconfig#module-sysconfig) | *Python's configuration information* | | | [`syslog`](library/syslog#module-syslog) *(Unix)* | *An interface to the Unix syslog library routines.* | | | | | | | **t** | | | | [`tabnanny`](library/tabnanny#module-tabnanny) | *Tool for detecting white space related problems in Python source files in a directory tree.* | | | [`tarfile`](library/tarfile#module-tarfile) | *Read and write tar-format archive files.* | | | [`telnetlib`](library/telnetlib#module-telnetlib) | **Deprecated:** *Telnet client class.* | | | [`tempfile`](library/tempfile#module-tempfile) | *Generate temporary files and directories.* | | | [`termios`](library/termios#module-termios) *(Unix)* | *POSIX style tty control.* | | | [`test`](library/test#module-test) | *Regression tests package containing the testing suite for Python.* | | | [`test.support`](library/test#module-test.support) | *Support for Python's regression test suite.* | | | [`test.support.bytecode_helper`](library/test#module-test.support.bytecode_helper) | *Support tools for testing correct bytecode generation.* | | | [`test.support.script_helper`](library/test#module-test.support.script_helper) | *Support for Python's script execution tests.* | | | [`test.support.socket_helper`](library/test#module-test.support.socket_helper) | *Support for socket tests.* | | | [`textwrap`](library/textwrap#module-textwrap) | *Text wrapping and filling* | | | [`threading`](library/threading#module-threading) | *Thread-based parallelism.* | | | [`time`](library/time#module-time) | *Time access and conversions.* | | | [`timeit`](library/timeit#module-timeit) | *Measure the execution time of small code snippets.* | | | [`tkinter`](library/tkinter#module-tkinter) | *Interface to Tcl/Tk for graphical user interfaces* | | | [`tkinter.colorchooser`](library/tkinter.colorchooser#module-tkinter.colorchooser) *(Tk)* | *Color choosing dialog* | | | [`tkinter.commondialog`](library/dialog#module-tkinter.commondialog) *(Tk)* | *Tkinter base class for dialogs* | | | [`tkinter.dnd`](library/tkinter.dnd#module-tkinter.dnd) *(Tk)* | *Tkinter drag-and-drop interface* | | | [`tkinter.filedialog`](library/dialog#module-tkinter.filedialog) *(Tk)* | *Dialog classes for file selection* | | | [`tkinter.font`](library/tkinter.font#module-tkinter.font) *(Tk)* | *Tkinter font-wrapping class* | | | [`tkinter.messagebox`](library/tkinter.messagebox#module-tkinter.messagebox) *(Tk)* | *Various types of alert dialogs* | | | [`tkinter.scrolledtext`](library/tkinter.scrolledtext#module-tkinter.scrolledtext) *(Tk)* | *Text widget with a vertical scroll bar.* | | | [`tkinter.simpledialog`](library/dialog#module-tkinter.simpledialog) *(Tk)* | *Simple dialog windows* | | | [`tkinter.tix`](library/tkinter.tix#module-tkinter.tix) | *Tk Extension Widgets for Tkinter* | | | [`tkinter.ttk`](library/tkinter.ttk#module-tkinter.ttk) | *Tk themed widget set* | | | [`token`](library/token#module-token) | *Constants representing terminal nodes of the parse tree.* | | | [`tokenize`](library/tokenize#module-tokenize) | *Lexical scanner for Python source code.* | | | [`trace`](library/trace#module-trace) | *Trace or track Python statement execution.* | | | [`traceback`](library/traceback#module-traceback) | *Print or retrieve a stack traceback.* | | | [`tracemalloc`](library/tracemalloc#module-tracemalloc) | *Trace memory allocations.* | | | [`tty`](library/tty#module-tty) *(Unix)* | *Utility functions that perform common terminal control operations.* | | | [`turtle`](library/turtle#module-turtle) | *An educational framework for simple graphics applications* | | | [`turtledemo`](library/turtle#module-turtledemo) | *A viewer for example turtle scripts* | | | [`types`](library/types#module-types) | *Names for built-in types.* | | | [`typing`](library/typing#module-typing) | *Support for type hints (see :pep:`484`).* | | | | | | | **u** | | | | [`unicodedata`](library/unicodedata#module-unicodedata) | *Access the Unicode Database.* | | | [`unittest`](library/unittest#module-unittest) | *Unit testing framework for Python.* | | | [`unittest.mock`](library/unittest.mock#module-unittest.mock) | *Mock object library.* | | | [`urllib`](library/urllib#module-urllib) | | | | [`urllib.error`](library/urllib.error#module-urllib.error) | *Exception classes raised by urllib.request.* | | | [`urllib.parse`](library/urllib.parse#module-urllib.parse) | *Parse URLs into or assemble them from components.* | | | [`urllib.request`](library/urllib.request#module-urllib.request) | *Extensible library for opening URLs.* | | | [`urllib.response`](library/urllib.request#module-urllib.response) | *Response classes used by urllib.* | | | [`urllib.robotparser`](library/urllib.robotparser#module-urllib.robotparser) | *Load a robots.txt file and answer questions about fetchability of other URLs.* | | | [`uu`](library/uu#module-uu) | **Deprecated:** *Encode and decode files in uuencode format.* | | | [`uuid`](library/uuid#module-uuid) | *UUID objects (universally unique identifiers) according to RFC 4122* | | | | | | | **v** | | | | [`venv`](library/venv#module-venv) | *Creation of virtual environments.* | | | | | | | **w** | | | | [`warnings`](library/warnings#module-warnings) | *Issue warning messages and control their disposition.* | | | [`wave`](library/wave#module-wave) | *Provide an interface to the WAV sound format.* | | | [`weakref`](library/weakref#module-weakref) | *Support for weak references and weak dictionaries.* | | | [`webbrowser`](library/webbrowser#module-webbrowser) | *Easy-to-use controller for Web browsers.* | | | [`winreg`](library/winreg#module-winreg) *(Windows)* | *Routines and objects for manipulating the Windows registry.* | | | [`winsound`](library/winsound#module-winsound) *(Windows)* | *Access to the sound-playing machinery for Windows.* | | | [`wsgiref`](library/wsgiref#module-wsgiref) | *WSGI Utilities and Reference Implementation.* | | | [`wsgiref.handlers`](library/wsgiref#module-wsgiref.handlers) | *WSGI server/gateway base classes.* | | | [`wsgiref.headers`](library/wsgiref#module-wsgiref.headers) | *WSGI response header tools.* | | | [`wsgiref.simple_server`](library/wsgiref#module-wsgiref.simple_server) | *A simple WSGI HTTP server.* | | | [`wsgiref.util`](library/wsgiref#module-wsgiref.util) | *WSGI environment utilities.* | | | [`wsgiref.validate`](library/wsgiref#module-wsgiref.validate) | *WSGI conformance checker.* | | | | | | | **x** | | | | [`xdrlib`](library/xdrlib#module-xdrlib) | **Deprecated:** *Encoders and decoders for the External Data Representation (XDR).* | | | [`xml`](library/xml#module-xml) | *Package containing XML processing modules* | | | [`xml.dom`](library/xml.dom#module-xml.dom) | *Document Object Model API for Python.* | | | [`xml.dom.minidom`](library/xml.dom.minidom#module-xml.dom.minidom) | *Minimal Document Object Model (DOM) implementation.* | | | [`xml.dom.pulldom`](library/xml.dom.pulldom#module-xml.dom.pulldom) | *Support for building partial DOM trees from SAX events.* | | | [`xml.etree.ElementTree`](library/xml.etree.elementtree#module-xml.etree.ElementTree) | *Implementation of the ElementTree API.* | | | [`xml.parsers.expat`](library/pyexpat#module-xml.parsers.expat) | *An interface to the Expat non-validating XML parser.* | | | [`xml.parsers.expat.errors`](library/pyexpat#module-xml.parsers.expat.errors) | | | | [`xml.parsers.expat.model`](library/pyexpat#module-xml.parsers.expat.model) | | | | [`xml.sax`](library/xml.sax#module-xml.sax) | *Package containing SAX2 base classes and convenience functions.* | | | [`xml.sax.handler`](library/xml.sax.handler#module-xml.sax.handler) | *Base classes for SAX event handlers.* | | | [`xml.sax.saxutils`](library/xml.sax.utils#module-xml.sax.saxutils) | *Convenience functions and classes for use with SAX.* | | | [`xml.sax.xmlreader`](library/xml.sax.reader#module-xml.sax.xmlreader) | *Interface which SAX-compliant XML parsers must implement.* | | | `xmlrpc` | | | | [`xmlrpc.client`](library/xmlrpc.client#module-xmlrpc.client) | *XML-RPC client access.* | | | [`xmlrpc.server`](library/xmlrpc.server#module-xmlrpc.server) | *Basic XML-RPC server implementations.* | | | | | | | **z** | | | | [`zipapp`](library/zipapp#module-zipapp) | *Manage executable Python zip archives* | | | [`zipfile`](library/zipfile#module-zipfile) | *Read and write ZIP-format archive files.* | | | [`zipimport`](library/zipimport#module-zipimport) | *Support for importing Python modules from ZIP archives.* | | | [`zlib`](library/zlib#module-zlib) | *Low-level interface to compression and decompression routines compatible with gzip.* | | | [`zoneinfo`](library/zoneinfo#module-zoneinfo) | *IANA time zone support* |
programming_docs
python Dealing with Bugs Dealing with Bugs ================= Python is a mature programming language which has established a reputation for stability. In order to maintain this reputation, the developers would like to know of any deficiencies you find in Python. It can be sometimes faster to fix bugs yourself and contribute patches to Python as it streamlines the process and involves less people. Learn how to [contribute](#contributing-to-python). Documentation bugs ------------------ If you find a bug in this documentation or would like to propose an improvement, please submit a bug report on the [tracker](#using-the-tracker). If you have a suggestion on how to fix it, include that as well. If you’re short on time, you can also email documentation bug reports to [[email protected]](mailto:docs%40python.org) (behavioral bugs can be sent to [[email protected]](mailto:python-list%40python.org)). ‘docs@’ is a mailing list run by volunteers; your request will be noticed, though it may take a while to be processed. See also [Documentation bugs](https://github.com/python/cpython/issues?q=is%3Aissue+is%3Aopen+label%3Adocs) A list of documentation bugs that have been submitted to the Python issue tracker. [Issue Tracking](https://devguide.python.org/tracker/) Overview of the process involved in reporting an improvement on the tracker. [Helping with Documentation](https://devguide.python.org/docquality/#helping-with-documentation) Comprehensive guide for individuals that are interested in contributing to Python documentation. [Documentation Translations](https://devguide.python.org/documenting/#translating) A list of GitHub pages for documentation translation and their primary contacts. Using the Python issue tracker ------------------------------ Issue reports for Python itself should be submitted via the GitHub issues tracker (<https://github.com/python/cpython/issues>). The GitHub issues tracker offers a web form which allows pertinent information to be entered and submitted to the developers. The first step in filing a report is to determine whether the problem has already been reported. The advantage in doing so, aside from saving the developers’ time, is that you learn what has been done to fix it; it may be that the problem has already been fixed for the next release, or additional information is needed (in which case you are welcome to provide it if you can!). To do this, search the tracker using the search box at the top of the page. If the problem you’re reporting is not already in the list, log in to GitHub. If you don’t already have a GitHub account, create a new account using the “Sign up” link. It is not possible to submit a bug report anonymously. Being now logged in, you can submit an issue. Click on the “New issue” button in the top bar to report a new issue. The submission form has two fields, “Title” and “Comment”. For the “Title” field, enter a *very* short description of the problem; less than ten words is good. In the “Comment” field, describe the problem in detail, including what you expected to happen and what did happen. Be sure to include whether any extension modules were involved, and what hardware and software platform you were using (including version information as appropriate). Each issue report will be reviewed by a developer who will determine what needs to be done to correct the problem. You will receive an update each time an action is taken on the issue. See also [How to Report Bugs Effectively](https://www.chiark.greenend.org.uk/~sgtatham/bugs.html) Article which goes into some detail about how to create a useful bug report. This describes what kind of information is useful and why it is useful. [Bug Writing Guidelines](https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html) Information about writing a good bug report. Some of this is specific to the Mozilla project, but describes general good practices. Getting started contributing to Python yourself ----------------------------------------------- Beyond just reporting bugs that you find, you are also welcome to submit patches to fix them. You can find more information on how to get started patching Python in the [Python Developer’s Guide](https://devguide.python.org/). If you have questions, the [core-mentorship mailing list](https://mail.python.org/mailman3/lists/core-mentorship.python.org/) is a friendly place to get answers to any and all questions pertaining to the process of fixing issues in Python. python Glossary Glossary ======== `>>>` The default Python prompt of the interactive shell. Often seen for code examples which can be executed interactively in the interpreter. `...` Can refer to: * The default Python prompt of the interactive shell when entering the code for an indented code block, when within a pair of matching left and right delimiters (parentheses, square brackets, curly braces or triple quotes), or after specifying a decorator. * The [`Ellipsis`](library/constants#Ellipsis "Ellipsis") built-in constant. `2to3` A tool that tries to convert Python 2.x code to Python 3.x code by handling most of the incompatibilities which can be detected by parsing the source and traversing the parse tree. 2to3 is available in the standard library as [`lib2to3`](https://docs.python.org/3.9/library/2to3.html#module-lib2to3 "lib2to3: The 2to3 library"); a standalone entry point is provided as `Tools/scripts/2to3`. See [2to3 - Automated Python 2 to 3 code translation](https://docs.python.org/3.9/library/2to3.html#to3-reference). `abstract base class` Abstract base classes complement [duck-typing](#term-duck-typing) by providing a way to define interfaces when other techniques like [`hasattr()`](library/functions#hasattr "hasattr") would be clumsy or subtly wrong (for example with [magic methods](reference/datamodel#special-lookup)). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by [`isinstance()`](library/functions#isinstance "isinstance") and [`issubclass()`](library/functions#issubclass "issubclass"); see the [`abc`](library/abc#module-abc "abc: Abstract base classes according to :pep:`3119`.") module documentation. Python comes with many built-in ABCs for data structures (in the [`collections.abc`](library/collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") module), numbers (in the [`numbers`](library/numbers#module-numbers "numbers: Numeric abstract base classes (Complex, Real, Integral, etc.).") module), streams (in the [`io`](library/io#module-io "io: Core tools for working with streams.") module), import finders and loaders (in the [`importlib.abc`](library/importlib#module-importlib.abc "importlib.abc: Abstract base classes related to import") module). You can create your own ABCs with the [`abc`](library/abc#module-abc "abc: Abstract base classes according to :pep:`3119`.") module. `annotation` A label associated with a variable, a class attribute or a function parameter or return value, used by convention as a [type hint](#term-type-hint). Annotations of local variables cannot be accessed at runtime, but annotations of global variables, class attributes, and functions are stored in the `__annotations__` special attribute of modules, classes, and functions, respectively. See [variable annotation](#term-variable-annotation), [function annotation](#term-function-annotation), [**PEP 484**](https://www.python.org/dev/peps/pep-0484) and [**PEP 526**](https://www.python.org/dev/peps/pep-0526), which describe this functionality. `argument` A value passed to a [function](#term-function) (or [method](#term-method)) when calling the function. There are two kinds of argument: * *keyword argument*: an argument preceded by an identifier (e.g. `name=`) in a function call or passed as a value in a dictionary preceded by `**`. For example, `3` and `5` are both keyword arguments in the following calls to [`complex()`](library/functions#complex "complex"): ``` complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5}) ``` * *positional argument*: an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an [iterable](#term-iterable) preceded by `*`. For example, `3` and `5` are both positional arguments in the following calls: ``` complex(3, 5) complex(*(3, 5)) ``` Arguments are assigned to the named local variables in a function body. See the [Calls](reference/expressions#calls) section for the rules governing this assignment. Syntactically, any expression can be used to represent an argument; the evaluated value is assigned to the local variable. See also the [parameter](#term-parameter) glossary entry, the FAQ question on [the difference between arguments and parameters](faq/programming#faq-argument-vs-parameter), and [**PEP 362**](https://www.python.org/dev/peps/pep-0362). `asynchronous context manager` An object which controls the environment seen in an [`async with`](reference/compound_stmts#async-with) statement by defining [`__aenter__()`](reference/datamodel#object.__aenter__ "object.__aenter__") and [`__aexit__()`](reference/datamodel#object.__aexit__ "object.__aexit__") methods. Introduced by [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `asynchronous generator` A function which returns an [asynchronous generator iterator](#term-asynchronous-generator-iterator). It looks like a coroutine function defined with [`async def`](reference/compound_stmts#async-def) except that it contains [`yield`](reference/simple_stmts#yield) expressions for producing a series of values usable in an [`async for`](reference/compound_stmts#async-for) loop. Usually refers to an asynchronous generator function, but may refer to an *asynchronous generator iterator* in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity. An asynchronous generator function may contain [`await`](reference/expressions#await) expressions as well as [`async for`](reference/compound_stmts#async-for), and [`async with`](reference/compound_stmts#async-with) statements. `asynchronous generator iterator` An object created by a [asynchronous generator](#term-asynchronous-generator) function. This is an [asynchronous iterator](#term-asynchronous-iterator) which when called using the [`__anext__()`](reference/datamodel#object.__anext__ "object.__anext__") method returns an awaitable object which will execute the body of the asynchronous generator function until the next [`yield`](reference/simple_stmts#yield) expression. Each [`yield`](reference/simple_stmts#yield) temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the *asynchronous generator iterator* effectively resumes with another awaitable returned by [`__anext__()`](reference/datamodel#object.__anext__ "object.__anext__"), it picks up where it left off. See [**PEP 492**](https://www.python.org/dev/peps/pep-0492) and [**PEP 525**](https://www.python.org/dev/peps/pep-0525). `asynchronous iterable` An object, that can be used in an [`async for`](reference/compound_stmts#async-for) statement. Must return an [asynchronous iterator](#term-asynchronous-iterator) from its [`__aiter__()`](reference/datamodel#object.__aiter__ "object.__aiter__") method. Introduced by [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `asynchronous iterator` An object that implements the [`__aiter__()`](reference/datamodel#object.__aiter__ "object.__aiter__") and [`__anext__()`](reference/datamodel#object.__anext__ "object.__anext__") methods. `__anext__` must return an [awaitable](#term-awaitable) object. [`async for`](reference/compound_stmts#async-for) resolves the awaitables returned by an asynchronous iterator’s [`__anext__()`](reference/datamodel#object.__anext__ "object.__anext__") method until it raises a [`StopAsyncIteration`](library/exceptions#StopAsyncIteration "StopAsyncIteration") exception. Introduced by [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `attribute` A value associated with an object which is referenced by name using dotted expressions. For example, if an object *o* has an attribute *a* it would be referenced as *o.a*. `awaitable` An object that can be used in an [`await`](reference/expressions#await) expression. Can be a [coroutine](#term-coroutine) or an object with an [`__await__()`](reference/datamodel#object.__await__ "object.__await__") method. See also [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `BDFL` Benevolent Dictator For Life, a.k.a. [Guido van Rossum](https://gvanrossum.github.io/), Python’s creator. `binary file` A [file object](#term-file-object) able to read and write [bytes-like objects](#term-bytes-like-object). Examples of binary files are files opened in binary mode (`'rb'`, `'wb'` or `'rb+'`), `sys.stdin.buffer`, `sys.stdout.buffer`, and instances of [`io.BytesIO`](library/io#io.BytesIO "io.BytesIO") and [`gzip.GzipFile`](library/gzip#gzip.GzipFile "gzip.GzipFile"). See also [text file](#term-text-file) for a file object able to read and write [`str`](library/stdtypes#str "str") objects. `bytes-like object` An object that supports the [Buffer Protocol](c-api/buffer#bufferobjects) and can export a C-[contiguous](#term-contiguous) buffer. This includes all [`bytes`](library/stdtypes#bytes "bytes"), [`bytearray`](library/stdtypes#bytearray "bytearray"), and [`array.array`](library/array#array.array "array.array") objects, as well as many common [`memoryview`](library/stdtypes#memoryview "memoryview") objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket. Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include [`bytearray`](library/stdtypes#bytearray "bytearray") and a [`memoryview`](library/stdtypes#memoryview "memoryview") of a [`bytearray`](library/stdtypes#bytearray "bytearray"). Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these include [`bytes`](library/stdtypes#bytes "bytes") and a [`memoryview`](library/stdtypes#memoryview "memoryview") of a [`bytes`](library/stdtypes#bytes "bytes") object. `bytecode` Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in `.pyc` files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a [virtual machine](#term-virtual-machine) that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases. A list of bytecode instructions can be found in the documentation for [the dis module](library/dis#bytecodes). `callback` A subroutine function which is passed as an argument to be executed at some point in the future. `class` A template for creating user-defined objects. Class definitions normally contain method definitions which operate on instances of the class. `class variable` A variable defined in a class and intended to be modified only at class level (i.e., not in an instance of the class). `coercion` The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example, `int(3.15)` converts the floating point number to the integer `3`, but in `3+4.5`, each argument is of a different type (one int, one float), and both must be converted to the same type before they can be added or it will raise a [`TypeError`](library/exceptions#TypeError "TypeError"). Without coercion, all arguments of even compatible types would have to be normalized to the same value by the programmer, e.g., `float(3)+4.5` rather than just `3+4.5`. `complex number` An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary numbers are real multiples of the imaginary unit (the square root of `-1`), often written `i` in mathematics or `j` in engineering. Python has built-in support for complex numbers, which are written with this latter notation; the imaginary part is written with a `j` suffix, e.g., `3+1j`. To get access to complex equivalents of the [`math`](library/math#module-math "math: Mathematical functions (sin() etc.).") module, use [`cmath`](library/cmath#module-cmath "cmath: Mathematical functions for complex numbers."). Use of complex numbers is a fairly advanced mathematical feature. If you’re not aware of a need for them, it’s almost certain you can safely ignore them. `context manager` An object which controls the environment seen in a [`with`](reference/compound_stmts#with) statement by defining [`__enter__()`](reference/datamodel#object.__enter__ "object.__enter__") and [`__exit__()`](reference/datamodel#object.__exit__ "object.__exit__") methods. See [**PEP 343**](https://www.python.org/dev/peps/pep-0343). `context variable` A variable which can have different values depending on its context. This is similar to Thread-Local Storage in which each execution thread may have a different value for a variable. However, with context variables, there may be several contexts in one execution thread and the main usage for context variables is to keep track of variables in concurrent asynchronous tasks. See [`contextvars`](library/contextvars#module-contextvars "contextvars: Context Variables"). `contiguous` A buffer is considered contiguous exactly if it is either *C-contiguous* or *Fortran contiguous*. Zero-dimensional buffers are C and Fortran contiguous. In one-dimensional arrays, the items must be laid out in memory next to each other, in order of increasing indexes starting from zero. In multidimensional C-contiguous arrays, the last index varies the fastest when visiting items in order of memory address. However, in Fortran contiguous arrays, the first index varies the fastest. `coroutine` Coroutines are a more generalized form of subroutines. Subroutines are entered at one point and exited at another point. Coroutines can be entered, exited, and resumed at many different points. They can be implemented with the [`async def`](reference/compound_stmts#async-def) statement. See also [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `coroutine function` A function which returns a [coroutine](#term-coroutine) object. A coroutine function may be defined with the [`async def`](reference/compound_stmts#async-def) statement, and may contain [`await`](reference/expressions#await), [`async for`](reference/compound_stmts#async-for), and [`async with`](reference/compound_stmts#async-with) keywords. These were introduced by [**PEP 492**](https://www.python.org/dev/peps/pep-0492). `CPython` The canonical implementation of the Python programming language, as distributed on [python.org](https://www.python.org). The term “CPython” is used when necessary to distinguish this implementation from others such as Jython or IronPython. `decorator` A function returning another function, usually applied as a function transformation using the `@wrapper` syntax. Common examples for decorators are [`classmethod()`](library/functions#classmethod "classmethod") and [`staticmethod()`](library/functions#staticmethod "staticmethod"). The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent: ``` def f(arg): ... f = staticmethod(f) @staticmethod def f(arg): ... ``` The same concept exists for classes, but is less commonly used there. See the documentation for [function definitions](reference/compound_stmts#function) and [class definitions](reference/compound_stmts#class) for more about decorators. `descriptor` Any object which defines the methods [`__get__()`](reference/datamodel#object.__get__ "object.__get__"), [`__set__()`](reference/datamodel#object.__set__ "object.__set__"), or [`__delete__()`](reference/datamodel#object.__delete__ "object.__delete__"). When a class attribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using *a.b* to get, set or delete an attribute looks up the object named *b* in the class dictionary for *a*, but if *b* is a descriptor, the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of Python because they are the basis for many features including functions, methods, properties, class methods, static methods, and reference to super classes. For more information about descriptors’ methods, see [Implementing Descriptors](reference/datamodel#descriptors) or the [Descriptor How To Guide](howto/descriptor#descriptorhowto). `dictionary` An associative array, where arbitrary keys are mapped to values. The keys can be any object with [`__hash__()`](reference/datamodel#object.__hash__ "object.__hash__") and [`__eq__()`](reference/datamodel#object.__eq__ "object.__eq__") methods. Called a hash in Perl. `dictionary comprehension` A compact way to process all or part of the elements in an iterable and return a dictionary with the results. `results = {n: n ** 2 for n in range(10)}` generates a dictionary containing key `n` mapped to value `n ** 2`. See [Displays for lists, sets and dictionaries](reference/expressions#comprehensions). `dictionary view` The objects returned from [`dict.keys()`](library/stdtypes#dict.keys "dict.keys"), [`dict.values()`](library/stdtypes#dict.values "dict.values"), and [`dict.items()`](library/stdtypes#dict.items "dict.items") are called dictionary views. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. To force the dictionary view to become a full list use `list(dictview)`. See [Dictionary view objects](library/stdtypes#dict-views). `docstring` A string literal which appears as the first expression in a class, function or module. While ignored when the suite is executed, it is recognized by the compiler and put into the `__doc__` attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object. `duck-typing` A programming style which does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using [`type()`](library/functions#type "type") or [`isinstance()`](library/functions#isinstance "isinstance"). (Note, however, that duck-typing can be complemented with [abstract base classes](#term-abstract-base-class).) Instead, it typically employs [`hasattr()`](library/functions#hasattr "hasattr") tests or [EAFP](#term-eafp) programming. `EAFP` Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many [`try`](reference/compound_stmts#try) and [`except`](reference/compound_stmts#except) statements. The technique contrasts with the [LBYL](#term-lbyl) style common to many other languages such as C. `expression` A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also [statement](#term-statement)s which cannot be used as expressions, such as [`while`](reference/compound_stmts#while). Assignments are also statements, not expressions. `extension module` A module written in C or C++, using Python’s C API to interact with the core and with user code. `f-string` String literals prefixed with `'f'` or `'F'` are commonly called “f-strings” which is short for [formatted string literals](reference/lexical_analysis#f-strings). See also [**PEP 498**](https://www.python.org/dev/peps/pep-0498). `file object` An object exposing a file-oriented API (with methods such as `read()` or `write()`) to an underlying resource. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called *file-like objects* or *streams*. There are actually three categories of file objects: raw [binary files](#term-binary-file), buffered [binary files](#term-binary-file) and [text files](#term-text-file). Their interfaces are defined in the [`io`](library/io#module-io "io: Core tools for working with streams.") module. The canonical way to create a file object is by using the [`open()`](library/functions#open "open") function. `file-like object` A synonym for [file object](#term-file-object). `finder` An object that tries to find the [loader](#term-loader) for a module that is being imported. Since Python 3.3, there are two types of finder: [meta path finders](#term-meta-path-finder) for use with [`sys.meta_path`](library/sys#sys.meta_path "sys.meta_path"), and [path entry finders](#term-path-entry-finder) for use with [`sys.path_hooks`](library/sys#sys.path_hooks "sys.path_hooks"). See [**PEP 302**](https://www.python.org/dev/peps/pep-0302), [**PEP 420**](https://www.python.org/dev/peps/pep-0420) and [**PEP 451**](https://www.python.org/dev/peps/pep-0451) for much more detail. `floor division` Mathematical division that rounds down to nearest integer. The floor division operator is `//`. For example, the expression `11 // 4` evaluates to `2` in contrast to the `2.75` returned by float true division. Note that `(-11) // 4` is `-3` because that is `-2.75` rounded *downward*. See [**PEP 238**](https://www.python.org/dev/peps/pep-0238). `function` A series of statements which returns some value to a caller. It can also be passed zero or more [arguments](#term-argument) which may be used in the execution of the body. See also [parameter](#term-parameter), [method](#term-method), and the [Function definitions](reference/compound_stmts#function) section. `function annotation` An [annotation](#term-annotation) of a function parameter or return value. Function annotations are usually used for [type hints](#term-type-hint): for example, this function is expected to take two [`int`](library/functions#int "int") arguments and is also expected to have an [`int`](library/functions#int "int") return value: ``` def sum_two_numbers(a: int, b: int) -> int: return a + b ``` Function annotation syntax is explained in section [Function definitions](reference/compound_stmts#function). See [variable annotation](#term-variable-annotation) and [**PEP 484**](https://www.python.org/dev/peps/pep-0484), which describe this functionality. `__future__` A [future statement](reference/simple_stmts#future), `from __future__ import <feature>`, directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python. The [`__future__`](library/__future__#module-__future__ "__future__: Future statement definitions") module documents the possible values of *feature*. By importing this module and evaluating its variables, you can see when a new feature was first added to the language and when it will (or did) become the default: ``` >>> import __future__ >>> __future__.division _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) ``` `garbage collection` The process of freeing memory when it is not used anymore. Python performs garbage collection via reference counting and a cyclic garbage collector that is able to detect and break reference cycles. The garbage collector can be controlled using the [`gc`](library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module. `generator` A function which returns a [generator iterator](#term-generator-iterator). It looks like a normal function except that it contains [`yield`](reference/simple_stmts#yield) expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the [`next()`](library/functions#next "next") function. Usually refers to a generator function, but may refer to a *generator iterator* in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity. `generator iterator` An object created by a [generator](#term-generator) function. Each [`yield`](reference/simple_stmts#yield) temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the *generator iterator* resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation). `generator expression` An expression that returns an iterator. It looks like a normal expression followed by a `for` clause defining a loop variable, range, and an optional `if` clause. The combined expression generates values for an enclosing function: ``` >>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 285 ``` `generic function` A function composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. See also the [single dispatch](#term-single-dispatch) glossary entry, the [`functools.singledispatch()`](library/functools#functools.singledispatch "functools.singledispatch") decorator, and [**PEP 443**](https://www.python.org/dev/peps/pep-0443). `generic type` A [type](#term-type) that can be parameterized; typically a [container class](reference/datamodel#sequence-types) such as [`list`](library/stdtypes#list "list") or [`dict`](library/stdtypes#dict "dict"). Used for [type hints](#term-type-hint) and [annotations](#term-annotation). For more details, see [generic alias types](library/stdtypes#types-genericalias), [**PEP 483**](https://www.python.org/dev/peps/pep-0483), [**PEP 484**](https://www.python.org/dev/peps/pep-0484), [**PEP 585**](https://www.python.org/dev/peps/pep-0585), and the [`typing`](library/typing#module-typing "typing: Support for type hints (see :pep:`484`).") module. `GIL` See [global interpreter lock](#term-global-interpreter-lock). `global interpreter lock` The mechanism used by the [CPython](#term-cpython) interpreter to assure that only one thread executes Python [bytecode](#term-bytecode) at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as [`dict`](library/stdtypes#dict "dict")) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines. However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O. Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain. `hash-based pyc` A bytecode cache file that uses the hash rather than the last-modified time of the corresponding source file to determine its validity. See [Cached bytecode invalidation](reference/import#pyc-invalidation). `hashable` An object is *hashable* if it has a hash value which never changes during its lifetime (it needs a [`__hash__()`](reference/datamodel#object.__hash__ "object.__hash__") method), and can be compared to other objects (it needs an [`__eq__()`](reference/datamodel#object.__eq__ "object.__eq__") method). Hashable objects which compare equal must have the same hash value. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their [`id()`](library/functions#id "id"). `IDLE` An Integrated Development Environment for Python. IDLE is a basic editor and interpreter environment which ships with the standard distribution of Python. `immutable` An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary. `import path` A list of locations (or [path entries](#term-path-entry)) that are searched by the [path based finder](#term-path-based-finder) for modules to import. During import, this list of locations usually comes from [`sys.path`](library/sys#sys.path "sys.path"), but for subpackages it may also come from the parent package’s `__path__` attribute. `importing` The process by which Python code in one module is made available to Python code in another module. `importer` An object that both finds and loads a module; both a [finder](#term-finder) and [loader](#term-loader) object. `interactive` Python has an interactive interpreter which means you can enter statements and expressions at the interpreter prompt, immediately execute them and see their results. Just launch `python` with no arguments (possibly by selecting it from your computer’s main menu). It is a very powerful way to test out new ideas or inspect modules and packages (remember `help(x)`). `interpreted` Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. This means that source files can be run directly without explicitly creating an executable which is then run. Interpreted languages typically have a shorter development/debug cycle than compiled ones, though their programs generally also run more slowly. See also [interactive](#term-interactive). `interpreter shutdown` When asked to shut down, the Python interpreter enters a special phase where it gradually releases all allocated resources, such as modules and various critical internal structures. It also makes several calls to the [garbage collector](#term-garbage-collection). This can trigger the execution of code in user-defined destructors or weakref callbacks. Code executed during the shutdown phase can encounter various exceptions as the resources it relies on may not function anymore (common examples are library modules or the warnings machinery). The main reason for interpreter shutdown is that the `__main__` module or the script being run has finished executing. `iterable` An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as [`list`](library/stdtypes#list "list"), [`str`](library/stdtypes#str "str"), and [`tuple`](library/stdtypes#tuple "tuple")) and some non-sequence types like [`dict`](library/stdtypes#dict "dict"), [file objects](#term-file-object), and objects of any classes you define with an [`__iter__()`](reference/datamodel#object.__iter__ "object.__iter__") method or with a [`__getitem__()`](reference/datamodel#object.__getitem__ "object.__getitem__") method that implements [Sequence](#term-sequence) semantics. Iterables can be used in a [`for`](reference/compound_stmts#for) loop and in many other places where a sequence is needed ([`zip()`](library/functions#zip "zip"), [`map()`](library/functions#map "map"), …). When an iterable object is passed as an argument to the built-in function [`iter()`](library/functions#iter "iter"), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call [`iter()`](library/functions#iter "iter") or deal with iterator objects yourself. The `for` statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also [iterator](#term-iterator), [sequence](#term-sequence), and [generator](#term-generator). `iterator` An object representing a stream of data. Repeated calls to the iterator’s [`__next__()`](library/stdtypes#iterator.__next__ "iterator.__next__") method (or passing it to the built-in function [`next()`](library/functions#next "next")) return successive items in the stream. When no more data are available a [`StopIteration`](library/exceptions#StopIteration "StopIteration") exception is raised instead. At this point, the iterator object is exhausted and any further calls to its `__next__()` method just raise [`StopIteration`](library/exceptions#StopIteration "StopIteration") again. Iterators are required to have an [`__iter__()`](reference/datamodel#object.__iter__ "object.__iter__") method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a [`list`](library/stdtypes#list "list")) produces a fresh new iterator each time you pass it to the [`iter()`](library/functions#iter "iter") function or use it in a [`for`](reference/compound_stmts#for) loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container. More information can be found in [Iterator Types](library/stdtypes#typeiter). `key function` A key function or collation function is a callable that returns a value used for sorting or ordering. For example, [`locale.strxfrm()`](library/locale#locale.strxfrm "locale.strxfrm") is used to produce a sort key that is aware of locale specific sort conventions. A number of tools in Python accept key functions to control how elements are ordered or grouped. They include [`min()`](library/functions#min "min"), [`max()`](library/functions#max "max"), [`sorted()`](library/functions#sorted "sorted"), [`list.sort()`](library/stdtypes#list.sort "list.sort"), [`heapq.merge()`](library/heapq#heapq.merge "heapq.merge"), [`heapq.nsmallest()`](library/heapq#heapq.nsmallest "heapq.nsmallest"), [`heapq.nlargest()`](library/heapq#heapq.nlargest "heapq.nlargest"), and [`itertools.groupby()`](library/itertools#itertools.groupby "itertools.groupby"). There are several ways to create a key function. For example. the [`str.lower()`](library/stdtypes#str.lower "str.lower") method can serve as a key function for case insensitive sorts. Alternatively, a key function can be built from a [`lambda`](reference/expressions#lambda) expression such as `lambda r: (r[0], r[2])`. Also, the [`operator`](library/operator#module-operator "operator: Functions corresponding to the standard operators.") module provides three key function constructors: [`attrgetter()`](library/operator#operator.attrgetter "operator.attrgetter"), [`itemgetter()`](library/operator#operator.itemgetter "operator.itemgetter"), and [`methodcaller()`](library/operator#operator.methodcaller "operator.methodcaller"). See the [Sorting HOW TO](howto/sorting#sortinghowto) for examples of how to create and use key functions. `keyword argument` See [argument](#term-argument). `lambda` An anonymous inline function consisting of a single [expression](#term-expression) which is evaluated when the function is called. The syntax to create a lambda function is `lambda [parameters]: expression` `LBYL` Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the [EAFP](#term-eafp) approach and is characterized by the presence of many [`if`](reference/compound_stmts#if) statements. In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, `if key in mapping: return mapping[key]` can fail if another thread removes *key* from *mapping* after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach. `list` A built-in Python [sequence](#term-sequence). Despite its name it is more akin to an array in other languages than to a linked list since access to elements is O(1). `list comprehension` A compact way to process all or part of the elements in a sequence and return a list with the results. `result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0]` generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. The [`if`](reference/compound_stmts#if) clause is optional. If omitted, all elements in `range(256)` are processed. `loader` An object that loads a module. It must define a method named `load_module()`. A loader is typically returned by a [finder](#term-finder). See [**PEP 302**](https://www.python.org/dev/peps/pep-0302) for details and [`importlib.abc.Loader`](library/importlib#importlib.abc.Loader "importlib.abc.Loader") for an [abstract base class](#term-abstract-base-class). `magic method` An informal synonym for [special method](#term-special-method). `mapping` A container object that supports arbitrary key lookups and implements the methods specified in the [`Mapping`](library/collections.abc#collections.abc.Mapping "collections.abc.Mapping") or [`MutableMapping`](library/collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping") [abstract base classes](library/collections.abc#collections-abstract-base-classes). Examples include [`dict`](library/stdtypes#dict "dict"), [`collections.defaultdict`](library/collections#collections.defaultdict "collections.defaultdict"), [`collections.OrderedDict`](library/collections#collections.OrderedDict "collections.OrderedDict") and [`collections.Counter`](library/collections#collections.Counter "collections.Counter"). `meta path finder` A [finder](#term-finder) returned by a search of [`sys.meta_path`](library/sys#sys.meta_path "sys.meta_path"). Meta path finders are related to, but different from [path entry finders](#term-path-entry-finder). See [`importlib.abc.MetaPathFinder`](library/importlib#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") for the methods that meta path finders implement. `metaclass` The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for taking those three arguments and creating the class. Most object oriented programming languages provide a default implementation. What makes Python special is that it is possible to create custom metaclasses. Most users never need this tool, but when the need arises, metaclasses can provide powerful, elegant solutions. They have been used for logging attribute access, adding thread-safety, tracking object creation, implementing singletons, and many other tasks. More information can be found in [Metaclasses](reference/datamodel#metaclasses). `method` A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first [argument](#term-argument) (which is usually called `self`). See [function](#term-function) and [nested scope](#term-nested-scope). `method resolution order` Method Resolution Order is the order in which base classes are searched for a member during lookup. See [The Python 2.3 Method Resolution Order](https://www.python.org/download/releases/2.3/mro/) for details of the algorithm used by the Python interpreter since the 2.3 release. `module` An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of [importing](#term-importing). See also [package](#term-package). `module spec` A namespace containing the import-related information used to load a module. An instance of [`importlib.machinery.ModuleSpec`](library/importlib#importlib.machinery.ModuleSpec "importlib.machinery.ModuleSpec"). `MRO` See [method resolution order](#term-method-resolution-order). `mutable` Mutable objects can change their value but keep their [`id()`](library/functions#id "id"). See also [immutable](#term-immutable). `named tuple` The term “named tuple” applies to any type or class that inherits from tuple and whose indexable elements are also accessible using named attributes. The type or class may have other features as well. Several built-in types are named tuples, including the values returned by [`time.localtime()`](library/time#time.localtime "time.localtime") and [`os.stat()`](library/os#os.stat "os.stat"). Another example is [`sys.float_info`](library/sys#sys.float_info "sys.float_info"): ``` >>> sys.float_info[1] # indexed access 1024 >>> sys.float_info.max_exp # named field access 1024 >>> isinstance(sys.float_info, tuple) # kind of tuple True ``` Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created from a regular class definition that inherits from [`tuple`](library/stdtypes#tuple "tuple") and that defines named fields. Such a class can be written by hand or it can be created with the factory function [`collections.namedtuple()`](library/collections#collections.namedtuple "collections.namedtuple"). The latter technique also adds some extra methods that may not be found in hand-written or built-in named tuples. `namespace` The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local, global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support modularity by preventing naming conflicts. For instance, the functions [`builtins.open`](library/functions#open "open") and [`os.open()`](library/os#os.open "os.open") are distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear which module implements a function. For instance, writing [`random.seed()`](library/random#random.seed "random.seed") or [`itertools.islice()`](library/itertools#itertools.islice "itertools.islice") makes it clear that those functions are implemented by the [`random`](library/random#module-random "random: Generate pseudo-random numbers with various common distributions.") and [`itertools`](library/itertools#module-itertools "itertools: Functions creating iterators for efficient looping.") modules, respectively. `namespace package` A [**PEP 420**](https://www.python.org/dev/peps/pep-0420) [package](#term-package) which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a [regular package](#term-regular-package) because they have no `__init__.py` file. See also [module](#term-module). `nested scope` The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another function can refer to variables in the outer function. Note that nested scopes by default work only for reference and not for assignment. Local variables both read and write in the innermost scope. Likewise, global variables read and write to the global namespace. The [`nonlocal`](reference/simple_stmts#nonlocal) allows writing to outer scopes. `new-style class` Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes could use Python’s newer, versatile features like [`__slots__`](reference/datamodel#object.__slots__ "object.__slots__"), descriptors, properties, [`__getattribute__()`](reference/datamodel#object.__getattribute__ "object.__getattribute__"), class methods, and static methods. `object` Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any [new-style class](#term-new-style-class). `package` A Python [module](#term-module) which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an `__path__` attribute. See also [regular package](#term-regular-package) and [namespace package](#term-namespace-package). `parameter` A named entity in a [function](#term-function) (or method) definition that specifies an [argument](#term-argument) (or in some cases, arguments) that the function can accept. There are five kinds of parameter: * *positional-or-keyword*: specifies an argument that can be passed either [positionally](#term-argument) or as a [keyword argument](#term-argument). This is the default kind of parameter, for example *foo* and *bar* in the following: ``` def func(foo, bar=None): ... ``` * *positional-only*: specifies an argument that can be supplied only by position. Positional-only parameters can be defined by including a `/` character in the parameter list of the function definition after them, for example *posonly1* and *posonly2* in the following: ``` def func(posonly1, posonly2, /, positional_or_keyword): ... ``` * *keyword-only*: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare `*` in the parameter list of the function definition before them, for example *kw\_only1* and *kw\_only2* in the following: ``` def func(arg, *, kw_only1, kw_only2): ... ``` * *var-positional*: specifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with `*`, for example *args* in the following: ``` def func(*args, **kwargs): ... ``` * *var-keyword*: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with `**`, for example *kwargs* in the example above. Parameters can specify both optional and required arguments, as well as default values for some optional arguments. See also the [argument](#term-argument) glossary entry, the FAQ question on [the difference between arguments and parameters](faq/programming#faq-argument-vs-parameter), the [`inspect.Parameter`](library/inspect#inspect.Parameter "inspect.Parameter") class, the [Function definitions](reference/compound_stmts#function) section, and [**PEP 362**](https://www.python.org/dev/peps/pep-0362). `path entry` A single location on the [import path](#term-import-path) which the [path based finder](#term-path-based-finder) consults to find modules for importing. `path entry finder` A [finder](#term-finder) returned by a callable on [`sys.path_hooks`](library/sys#sys.path_hooks "sys.path_hooks") (i.e. a [path entry hook](#term-path-entry-hook)) which knows how to locate modules given a [path entry](#term-path-entry). See [`importlib.abc.PathEntryFinder`](library/importlib#importlib.abc.PathEntryFinder "importlib.abc.PathEntryFinder") for the methods that path entry finders implement. `path entry hook` A callable on the `sys.path_hook` list which returns a [path entry finder](#term-path-entry-finder) if it knows how to find modules on a specific [path entry](#term-path-entry). `path based finder` One of the default [meta path finders](#term-meta-path-finder) which searches an [import path](#term-import-path) for modules. `path-like object` An object representing a file system path. A path-like object is either a [`str`](library/stdtypes#str "str") or [`bytes`](library/stdtypes#bytes "bytes") object representing a path, or an object implementing the [`os.PathLike`](library/os#os.PathLike "os.PathLike") protocol. An object that supports the [`os.PathLike`](library/os#os.PathLike "os.PathLike") protocol can be converted to a [`str`](library/stdtypes#str "str") or [`bytes`](library/stdtypes#bytes "bytes") file system path by calling the [`os.fspath()`](library/os#os.fspath "os.fspath") function; [`os.fsdecode()`](library/os#os.fsdecode "os.fsdecode") and [`os.fsencode()`](library/os#os.fsencode "os.fsencode") can be used to guarantee a [`str`](library/stdtypes#str "str") or [`bytes`](library/stdtypes#bytes "bytes") result instead, respectively. Introduced by [**PEP 519**](https://www.python.org/dev/peps/pep-0519). `PEP` Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. PEPs should provide a concise technical specification and a rationale for proposed features. PEPs are intended to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions. See [**PEP 1**](https://www.python.org/dev/peps/pep-0001). `portion` A set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package, as defined in [**PEP 420**](https://www.python.org/dev/peps/pep-0420). `positional argument` See [argument](#term-argument). `provisional API` A provisional API is one which has been deliberately excluded from the standard library’s backwards compatibility guarantees. While major changes to such interfaces are not expected, as long as they are marked provisional, backwards incompatible changes (up to and including removal of the interface) may occur if deemed necessary by core developers. Such changes will not be made gratuitously – they will occur only if serious fundamental flaws are uncovered that were missed prior to the inclusion of the API. Even for provisional APIs, backwards incompatible changes are seen as a “solution of last resort” - every attempt will still be made to find a backwards compatible resolution to any identified problems. This process allows the standard library to continue to evolve over time, without locking in problematic design errors for extended periods of time. See [**PEP 411**](https://www.python.org/dev/peps/pep-0411) for more details. `provisional package` See [provisional API](#term-provisional-api). `Python 3000` Nickname for the Python 3.x release line (coined long ago when the release of version 3 was something in the distant future.) This is also abbreviated “Py3k”. `Pythonic` An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages. For example, a common idiom in Python is to loop over all elements of an iterable using a [`for`](reference/compound_stmts#for) statement. Many other languages don’t have this type of construct, so people unfamiliar with Python sometimes use a numerical counter instead: ``` for i in range(len(food)): print(food[i]) ``` As opposed to the cleaner, Pythonic method: ``` for piece in food: print(piece) ``` `qualified name` A dotted name showing the “path” from a module’s global scope to a class, function or method defined in that module, as defined in [**PEP 3155**](https://www.python.org/dev/peps/pep-3155). For top-level functions and classes, the qualified name is the same as the object’s name: ``` >>> class C: ... class D: ... def meth(self): ... pass ... >>> C.__qualname__ 'C' >>> C.D.__qualname__ 'C.D' >>> C.D.meth.__qualname__ 'C.D.meth' ``` When used to refer to modules, the *fully qualified name* means the entire dotted path to the module, including any parent packages, e.g. `email.mime.text`: ``` >>> import email.mime.text >>> email.mime.text.__name__ 'email.mime.text' ``` `reference count` The number of references to an object. When the reference count of an object drops to zero, it is deallocated. Reference counting is generally not visible to Python code, but it is a key element of the [CPython](#term-cpython) implementation. The [`sys`](library/sys#module-sys "sys: Access system-specific parameters and functions.") module defines a [`getrefcount()`](library/sys#sys.getrefcount "sys.getrefcount") function that programmers can call to return the reference count for a particular object. `regular package` A traditional [package](#term-package), such as a directory containing an `__init__.py` file. See also [namespace package](#term-namespace-package). `__slots__` A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application. `sequence` An [iterable](#term-iterable) which supports efficient element access using integer indices via the [`__getitem__()`](reference/datamodel#object.__getitem__ "object.__getitem__") special method and defines a [`__len__()`](reference/datamodel#object.__len__ "object.__len__") method that returns the length of the sequence. Some built-in sequence types are [`list`](library/stdtypes#list "list"), [`str`](library/stdtypes#str "str"), [`tuple`](library/stdtypes#tuple "tuple"), and [`bytes`](library/stdtypes#bytes "bytes"). Note that [`dict`](library/stdtypes#dict "dict") also supports [`__getitem__()`](reference/datamodel#object.__getitem__ "object.__getitem__") and [`__len__()`](reference/datamodel#object.__len__ "object.__len__"), but is considered a mapping rather than a sequence because the lookups use arbitrary [immutable](#term-immutable) keys rather than integers. The [`collections.abc.Sequence`](library/collections.abc#collections.abc.Sequence "collections.abc.Sequence") abstract base class defines a much richer interface that goes beyond just [`__getitem__()`](reference/datamodel#object.__getitem__ "object.__getitem__") and [`__len__()`](reference/datamodel#object.__len__ "object.__len__"), adding `count()`, `index()`, [`__contains__()`](reference/datamodel#object.__contains__ "object.__contains__"), and [`__reversed__()`](reference/datamodel#object.__reversed__ "object.__reversed__"). Types that implement this expanded interface can be registered explicitly using [`register()`](library/abc#abc.ABCMeta.register "abc.ABCMeta.register"). `set comprehension` A compact way to process all or part of the elements in an iterable and return a set with the results. `results = {c for c in 'abracadabra' if c not in 'abc'}` generates the set of strings `{'r', 'd'}`. See [Displays for lists, sets and dictionaries](reference/expressions#comprehensions). `single dispatch` A form of [generic function](#term-generic-function) dispatch where the implementation is chosen based on the type of a single argument. `slice` An object usually containing a portion of a [sequence](#term-sequence). A slice is created using the subscript notation, `[]` with colons between numbers when several are given, such as in `variable_name[1:3:5]`. The bracket (subscript) notation uses [`slice`](library/functions#slice "slice") objects internally. `special method` A method that is called implicitly by Python to execute a certain operation on a type, such as addition. Such methods have names starting and ending with double underscores. Special methods are documented in [Special method names](reference/datamodel#specialnames). `statement` A statement is part of a suite (a “block” of code). A statement is either an [expression](#term-expression) or one of several constructs with a keyword, such as [`if`](reference/compound_stmts#if), [`while`](reference/compound_stmts#while) or [`for`](reference/compound_stmts#for). `text encoding` A string in Python is a sequence of Unicode code points (in range `U+0000`–`U+10FFFF`). To store or transfer a string, it needs to be serialized as a sequence of bytes. Serializing a string into a sequence of bytes is known as “encoding”, and recreating the string from the sequence of bytes is known as “decoding”. There are a variety of different text serialization [codecs](library/codecs#standard-encodings), which are collectively referred to as “text encodings”. `text file` A [file object](#term-file-object) able to read and write [`str`](library/stdtypes#str "str") objects. Often, a text file actually accesses a byte-oriented datastream and handles the [text encoding](#term-text-encoding) automatically. Examples of text files are files opened in text mode (`'r'` or `'w'`), [`sys.stdin`](library/sys#sys.stdin "sys.stdin"), [`sys.stdout`](library/sys#sys.stdout "sys.stdout"), and instances of [`io.StringIO`](library/io#io.StringIO "io.StringIO"). See also [binary file](#term-binary-file) for a file object able to read and write [bytes-like objects](#term-bytes-like-object). `triple-quoted string` A string which is bound by three instances of either a quotation mark (”) or an apostrophe (‘). While they don’t provide any functionality not available with single-quoted strings, they are useful for a number of reasons. They allow you to include unescaped single and double quotes within a string and they can span multiple lines without the use of the continuation character, making them especially useful when writing docstrings. `type` The type of a Python object determines what kind of object it is; every object has a type. An object’s type is accessible as its [`__class__`](library/stdtypes#instance.__class__ "instance.__class__") attribute or can be retrieved with `type(obj)`. `type alias` A synonym for a type, created by assigning the type to an identifier. Type aliases are useful for simplifying [type hints](#term-type-hint). For example: ``` def remove_gray_shades( colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]: pass ``` could be made more readable like this: ``` Color = tuple[int, int, int] def remove_gray_shades(colors: list[Color]) -> list[Color]: pass ``` See [`typing`](library/typing#module-typing "typing: Support for type hints (see :pep:`484`).") and [**PEP 484**](https://www.python.org/dev/peps/pep-0484), which describe this functionality. `type hint` An [annotation](#term-annotation) that specifies the expected type for a variable, a class attribute, or a function parameter or return value. Type hints are optional and are not enforced by Python but they are useful to static type analysis tools, and aid IDEs with code completion and refactoring. Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using [`typing.get_type_hints()`](library/typing#typing.get_type_hints "typing.get_type_hints"). See [`typing`](library/typing#module-typing "typing: Support for type hints (see :pep:`484`).") and [**PEP 484**](https://www.python.org/dev/peps/pep-0484), which describe this functionality. `universal newlines` A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention `'\n'`, the Windows convention `'\r\n'`, and the old Macintosh convention `'\r'`. See [**PEP 278**](https://www.python.org/dev/peps/pep-0278) and [**PEP 3116**](https://www.python.org/dev/peps/pep-3116), as well as [`bytes.splitlines()`](library/stdtypes#bytes.splitlines "bytes.splitlines") for an additional use. `variable annotation` An [annotation](#term-annotation) of a variable or a class attribute. When annotating a variable or a class attribute, assignment is optional: ``` class C: field: 'annotation' ``` Variable annotations are usually used for [type hints](#term-type-hint): for example this variable is expected to take [`int`](library/functions#int "int") values: ``` count: int = 0 ``` Variable annotation syntax is explained in section [Annotated assignment statements](reference/simple_stmts#annassign). See [function annotation](#term-function-annotation), [**PEP 484**](https://www.python.org/dev/peps/pep-0484) and [**PEP 526**](https://www.python.org/dev/peps/pep-0526), which describe this functionality. `virtual environment` A cooperatively isolated runtime environment that allows Python users and applications to install and upgrade Python distribution packages without interfering with the behaviour of other Python applications running on the same system. See also [`venv`](library/venv#module-venv "venv: Creation of virtual environments."). `virtual machine` A computer defined entirely in software. Python’s virtual machine executes the [bytecode](#term-bytecode) emitted by the bytecode compiler. `Zen of Python` Listing of Python design principles and philosophies that are helpful in understanding and using the language. The listing can be found by typing “`import this`” at the interactive prompt.
programming_docs
python Download Python 3.9.14 Documentation Download Python 3.9.14 Documentation ==================================== **Last updated on: Sep 11, 2022.** To download an archive containing all the documents for this version of Python in one of various formats, follow one of links in this table. | Format | Packed as .zip | Packed as .tar.bz2 | | --- | --- | --- | | PDF (US-Letter paper size) | [Download](archives/python-3.9.14-docs-pdf-letter.zip) (ca. 13 MiB) | [Download](archives/python-3.9.14-docs-pdf-letter.tar.bz2) (ca. 13 MiB) | | PDF (A4 paper size) | [Download](archives/python-3.9.14-docs-pdf-a4.zip) (ca. 13 MiB) | [Download](archives/python-3.9.14-docs-pdf-a4.tar.bz2) (ca. 13 MiB) | | HTML | [Download](archives/python-3.9.14-docs-html.zip) (ca. 9 MiB) | [Download](archives/python-3.9.14-docs-html.tar.bz2) (ca. 6 MiB) | | Plain Text | [Download](archives/python-3.9.14-docs-text.zip) (ca. 3 MiB) | [Download](archives/python-3.9.14-docs-text.tar.bz2) (ca. 2 MiB) | | EPUB | [Download](archives/python-3.9.14-docs.epub) (ca. 5 MiB) | | These archives contain all the content in the documentation. HTML Help (`.chm`) files are made available in the "Windows" section on the [Python download page](https://www.python.org/downloads/release/python-3914/). Unpacking --------- Unix users should download the .tar.bz2 archives; these are bzipped tar archives and can be handled in the usual way using tar and the bzip2 program. The [InfoZIP](http://www.info-zip.org) unzip program can be used to handle the ZIP archives if desired. The .tar.bz2 archives provide the best compression and fastest download times. Windows users can use the ZIP archives since those are customary on that platform. These are created on Unix using the InfoZIP zip program. Problems -------- If you have comments or suggestions for the Python documentation, please send email to [[email protected]](mailto:[email protected]). python Search Search ====== Please activate JavaScript to enable the search functionality. From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. python Index Index ===== [**Symbols**](#Symbols) | [**\_**](#_) | [**A**](#A) | [**B**](#B) | [**C**](#C) | [**D**](#D) | [**E**](#E) | [**F**](#F) | [**G**](#G) | [**H**](#H) | [**I**](#I) | [**J**](#J) | [**K**](#K) | [**L**](#L) | [**M**](#M) | [**N**](#N) | [**O**](#O) | [**P**](#P) | [**Q**](#Q) | [**R**](#R) | [**S**](#S) | [**T**](#T) | [**U**](#U) | [**V**](#V) | [**W**](#W) | [**X**](#X) | [**Y**](#Y) | [**Z**](#Z) Symbols ------- | | | | --- | --- | | * ! (exclamation) + [in a command interpreter](library/cmd#index-0) + [in curses module](library/curses.ascii#index-0) + [in formatted string literal](reference/lexical_analysis#index-24) + [in glob-style wildcards](library/fnmatch#index-2), [[1]](library/glob#index-1) + [in string formatting](library/string#index-2) + [in struct format strings](library/struct#index-1) * [! (pdb command)](library/pdb#pdbcommand-!) * != + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * " (double quote) + [string literal](reference/lexical_analysis#index-16) * """ + [string literal](reference/lexical_analysis#index-17) * # (hash) + [comment](library/site#index-2), [[1]](reference/lexical_analysis#index-4), [[2]](tutorial/introduction#index-0) + [in doctests](library/doctest#index-4) + [in printf-style formatting](library/stdtypes#index-35), [[1]](library/stdtypes#index-45) + [in regular expressions](library/re#index-36) + [in string formatting](library/string#index-5) + [source encoding declaration](reference/lexical_analysis#index-5) * $ (dollar) + [environment variables expansion](library/os.path#index-8) + [in regular expressions](library/re#index-2) + [in template strings](library/string#index-11) + [interpolation in configuration files](library/configparser#index-2) * % (percent) + [datetime format](library/datetime#index-0), [[1]](library/time#index-11), [[2]](library/time#index-9) + [environment variables expansion (Windows)](library/os.path#index-8), [[1]](library/winreg#index-0) + [interpolation in configuration files](library/configparser#index-1) + [operator](library/stdtypes#index-13), [[1]](reference/expressions#index-68) + [printf-style formatting](library/stdtypes#index-33), [[1]](library/stdtypes#index-43) * %= + [augmented assignment](reference/simple_stmts#index-14) * & (ampersand) + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-74) * &= + [augmented assignment](reference/simple_stmts#index-14) * ' (single quote) + [string literal](reference/lexical_analysis#index-16) * ''' + [string literal](reference/lexical_analysis#index-17) * () (parentheses) + [call](reference/expressions#index-47) + [class definition](reference/compound_stmts#index-31) + [function definition](reference/compound_stmts#index-19) + [generator expression](reference/expressions#index-22) + [in assignment target list](reference/simple_stmts#index-6) + [in printf-style formatting](library/stdtypes#index-34), [[1]](library/stdtypes#index-44) + [in regular expressions](library/re#index-14) + [tuple display](reference/expressions#index-8) * (? + [in regular expressions](library/re#index-15) * (?! + [in regular expressions](library/re#index-21) * (?# + [in regular expressions](library/re#index-19) * (?: + [in regular expressions](library/re#index-16) * (?<! + [in regular expressions](library/re#index-23) * (?<= + [in regular expressions](library/re#index-22) * (?= + [in regular expressions](library/re#index-20) * (?P< + [in regular expressions](library/re#index-17) * (?P= + [in regular expressions](library/re#index-18) * \* (asterisk) + [function definition](reference/compound_stmts#index-23) + [import statement](reference/simple_stmts#index-37) + [in argparse module](library/argparse#index-1) + [in assignment target list](reference/simple_stmts#index-6) + [in AST grammar](library/ast#index-1) + [in expression lists](reference/expressions#index-92) + [in function calls](reference/expressions#index-49), [[1]](tutorial/controlflow#index-2) + [in glob-style wildcards](library/fnmatch#index-2), [[1]](library/glob#index-1) + [in printf-style formatting](library/stdtypes#index-34), [[1]](library/stdtypes#index-44) + [in regular expressions](library/re#index-3) + [operator](library/stdtypes#index-13), [[1]](reference/expressions#index-65) * \*\* + [function definition](reference/compound_stmts#index-23) + [in dictionary displays](reference/expressions#index-18) + [in function calls](reference/expressions#index-50), [[1]](tutorial/controlflow#index-3) + [in glob-style wildcards](library/glob#index-2) + [operator](library/stdtypes#index-13), [[1]](reference/expressions#index-58) * \*\*= + [augmented assignment](reference/simple_stmts#index-14) * \*= + [augmented assignment](reference/simple_stmts#index-14) * \*? + [in regular expressions](library/re#index-6) * + (plus) + [binary operator](library/stdtypes#index-13), [[1]](reference/expressions#index-69) + [in argparse module](library/argparse#index-2) + [in doctests](library/doctest#index-4) + [in printf-style formatting](library/stdtypes#index-35), [[1]](library/stdtypes#index-45) + [in regular expressions](library/re#index-4) + [in string formatting](library/string#index-4) + [unary operator](library/stdtypes#index-13), [[1]](reference/expressions#index-61) * += + [augmented assignment](reference/simple_stmts#index-14) * +? + [in regular expressions](library/re#index-6) * [, (comma)](reference/expressions#index-10) + [argument list](reference/expressions#index-47) + [expression list](reference/compound_stmts#index-31), [[1]](reference/expressions#index-15), [[2]](reference/expressions#index-16), [[3]](reference/expressions#index-90), [[4]](reference/simple_stmts#index-18) + [identifier list](reference/simple_stmts#index-43), [[1]](reference/simple_stmts#index-45) + [import statement](reference/simple_stmts#index-34) + [in dictionary displays](reference/expressions#index-17) + [in string formatting](library/string#index-6) + [in target list](reference/simple_stmts#index-6) + [parameter list](reference/compound_stmts#index-19) + [slicing](reference/expressions#index-44) + [with statement](reference/compound_stmts#index-16) * - (minus) + [binary operator](library/stdtypes#index-13), [[1]](reference/expressions#index-70) + [in doctests](library/doctest#index-4) + [in glob-style wildcards](library/fnmatch#index-2), [[1]](library/glob#index-1) + [in printf-style formatting](library/stdtypes#index-35), [[1]](library/stdtypes#index-45) + [in regular expressions](library/re#index-10) + [in string formatting](library/string#index-4) + [unary operator](library/stdtypes#index-13), [[1]](reference/expressions#index-60) * --annotate + [pickletools command line option](library/pickletools#cmdoption-pickletools-a) * --best + [gzip command line option](library/gzip#cmdoption-gzip-best) * --buffer + [unittest command line option](library/unittest#cmdoption-unittest-b) * --catch + [unittest command line option](library/unittest#cmdoption-unittest-c) * --check-hash-based-pycs default|always|never + [command line option](using/cmdline#cmdoption-check-hash-based-pycs) * --compact + [json.tool command line option](library/json#cmdoption-json-tool-indent) * --compress + [zipapp command line option](library/zipapp#cmdoption-zipapp-c) * --count + [trace command line option](library/trace#cmdoption-trace-c) * --coverdir=<dir> + [trace command line option](library/trace#cmdoption-trace-coverdir) * --create <tarfile> <source1> ... <sourceN> + [tarfile command line option](library/tarfile#cmdoption-tarfile-create) * --create <zipfile> <source1> ... <sourceN> + [zipfile command line option](library/zipfile#cmdoption-zipfile-create) * --decompress + [gzip command line option](library/gzip#cmdoption-gzip-d) * --details + [inspect command line option](library/inspect#cmdoption-inspect-details) * --exact + [tokenize command line option](library/tokenize#cmdoption-tokenize-e) * --extract <tarfile> [<output\_dir>] + [tarfile command line option](library/tarfile#cmdoption-tarfile-extract) * --extract <zipfile> <output\_dir> + [zipfile command line option](library/zipfile#cmdoption-zipfile-extract) * --failfast + [unittest command line option](library/unittest#cmdoption-unittest-f) * --fast + [gzip command line option](library/gzip#cmdoption-gzip-fast) * --file=<file> + [trace command line option](library/trace#cmdoption-trace-f) * --hardlink-dupes + [compileall command line option](library/compileall#cmdoption-compileall-hardlink-dupes) * --help + [ast command line option](library/ast#cmdoption-ast-h) + [command line option](using/cmdline#cmdoption-help) + [gzip command line option](library/gzip#cmdoption-gzip-h) + [json.tool command line option](library/json#cmdoption-json-tool-h) + [timeit command line option](library/timeit#cmdoption-timeit-h) + [tokenize command line option](library/tokenize#cmdoption-tokenize-h) + [trace command line option](library/trace#cmdoption-trace-help) + [zipapp command line option](library/zipapp#cmdoption-zipapp-h) * --ignore-dir=<dir> + [trace command line option](library/trace#cmdoption-trace-ignore-dir) * --ignore-module=<mod> + [trace command line option](library/trace#cmdoption-trace-ignore-module) * --include-attributes + [ast command line option](library/ast#cmdoption-ast-a) * --indent + [json.tool command line option](library/json#cmdoption-json-tool-indent) * --indent <indent> + [ast command line option](library/ast#cmdoption-ast-indent) * --indentlevel=<num> + [pickletools command line option](library/pickletools#cmdoption-pickletools-l) * --info + [zipapp command line option](library/zipapp#cmdoption-zipapp-info) * --invalidation-mode [timestamp|checked-hash|unchecked-hash] + [compileall command line option](library/compileall#cmdoption-compileall-invalidation-mode) * --json-lines + [json.tool command line option](library/json#cmdoption-json-tool-json-lines) * --list <tarfile> + [tarfile command line option](library/tarfile#cmdoption-tarfile-list) * --list <zipfile> + [zipfile command line option](library/zipfile#cmdoption-zipfile-list) * --listfuncs + [trace command line option](library/trace#cmdoption-trace-l) * --locals + [unittest command line option](library/unittest#cmdoption-unittest-locals) * --main=<mainfn> + [zipapp command line option](library/zipapp#cmdoption-zipapp-m) * --memo + [pickletools command line option](library/pickletools#cmdoption-pickletools-m) * --missing + [trace command line option](library/trace#cmdoption-trace-m) * --mode <mode> + [ast command line option](library/ast#cmdoption-ast-mode) * --no-ensure-ascii + [json.tool command line option](library/json#cmdoption-json-tool-no-ensure-ascii) * --no-indent + [json.tool command line option](library/json#cmdoption-json-tool-indent) * --no-report + [trace command line option](library/trace#cmdoption-trace-no-report) * --no-type-comments + [ast command line option](library/ast#cmdoption-ast-no-type-comments) * --number=N + [timeit command line option](library/timeit#cmdoption-timeit-n) * --output=<file> + [pickletools command line option](library/pickletools#cmdoption-pickletools-o) * --output=<output> + [zipapp command line option](library/zipapp#cmdoption-zipapp-o) * --pattern pattern + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-p) * --preamble=<preamble> + [pickletools command line option](library/pickletools#cmdoption-pickletools-p) * --process + [timeit command line option](library/timeit#cmdoption-timeit-p) * --python=<interpreter> + [zipapp command line option](library/zipapp#cmdoption-zipapp-p) * --repeat=N + [timeit command line option](library/timeit#cmdoption-timeit-r) * --report + [trace command line option](library/trace#cmdoption-trace-r) * --setup=S + [timeit command line option](library/timeit#cmdoption-timeit-s) * --sort-keys + [json.tool command line option](library/json#cmdoption-json-tool-sort-keys) * --start-directory directory + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-s) * --summary + [trace command line option](library/trace#cmdoption-trace-s) * --tab + [json.tool command line option](library/json#cmdoption-json-tool-indent) * --test <tarfile> + [tarfile command line option](library/tarfile#cmdoption-tarfile-test) * --test <zipfile> + [zipfile command line option](library/zipfile#cmdoption-zipfile-test) * --timing + [trace command line option](library/trace#cmdoption-trace-g) * --top-level-directory directory + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-t) * --trace + [trace command line option](library/trace#cmdoption-trace-t) * --trackcalls + [trace command line option](library/trace#cmdoption-trace-trackcalls) * --unit=U + [timeit command line option](library/timeit#cmdoption-timeit-u) * --user-base + [site command line option](library/site#cmdoption-site-user-base) * --user-site + [site command line option](library/site#cmdoption-site-user-site) * --verbose + [tarfile command line option](library/tarfile#cmdoption-tarfile-v) + [timeit command line option](library/timeit#cmdoption-timeit-v) + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-v) * --version + [command line option](using/cmdline#cmdoption-version) + [trace command line option](library/trace#cmdoption-trace-version) * -= + [augmented assignment](reference/simple_stmts#index-14) * -> + [function annotations](reference/compound_stmts#index-25), [[1]](tutorial/controlflow#index-5) * -? + [command line option](using/cmdline#cmdoption) * -a + [ast command line option](library/ast#cmdoption-ast-a) + [pickletools command line option](library/pickletools#cmdoption-pickletools-a) * -B + [command line option](using/cmdline#id1) * -b + [command line option](using/cmdline#cmdoption-b) + [compileall command line option](library/compileall#cmdoption-compileall-b) + [unittest command line option](library/unittest#cmdoption-unittest-b) * -C + [trace command line option](library/trace#cmdoption-trace-coverdir) * -c + [trace command line option](library/trace#cmdoption-trace-c) + [unittest command line option](library/unittest#cmdoption-unittest-c) + [zipapp command line option](library/zipapp#cmdoption-zipapp-c) * -c <command> + [command line option](using/cmdline#cmdoption-c) * -c <tarfile> <source1> ... <sourceN> + [tarfile command line option](library/tarfile#cmdoption-tarfile-c) * -c <zipfile> <source1> ... <sourceN> + [zipfile command line option](library/zipfile#cmdoption-zipfile-c) * -d + [command line option](using/cmdline#cmdoption-d) + [gzip command line option](library/gzip#cmdoption-gzip-d) * -d destdir + [compileall command line option](library/compileall#cmdoption-compileall-d) * -E + [command line option](using/cmdline#cmdoption-e) * -e + [tokenize command line option](library/tokenize#cmdoption-tokenize-e) * -e <tarfile> [<output\_dir>] + [tarfile command line option](library/tarfile#cmdoption-tarfile-e) | * -e <zipfile> <output\_dir> + [zipfile command line option](library/zipfile#cmdoption-zipfile-e) * -e dir + [compileall command line option](library/compileall#cmdoption-compileall-e) * -f + [compileall command line option](library/compileall#cmdoption-compileall-f) + [trace command line option](library/trace#cmdoption-trace-f) + [unittest command line option](library/unittest#cmdoption-unittest-f) * -g + [trace command line option](library/trace#cmdoption-trace-g) * -h + [ast command line option](library/ast#cmdoption-ast-h) + [command line option](using/cmdline#cmdoption-h) + [gzip command line option](library/gzip#cmdoption-gzip-h) + [json.tool command line option](library/json#cmdoption-json-tool-h) + [timeit command line option](library/timeit#cmdoption-timeit-h) + [tokenize command line option](library/tokenize#cmdoption-tokenize-h) + [zipapp command line option](library/zipapp#cmdoption-zipapp-h) * -I + [command line option](using/cmdline#id2) * -i + [command line option](using/cmdline#cmdoption-i) * -i <indent> + [ast command line option](library/ast#cmdoption-ast-i) * -i list + [compileall command line option](library/compileall#cmdoption-compileall-i) * -J + [command line option](using/cmdline#cmdoption-j) * -j N + [compileall command line option](library/compileall#cmdoption-compileall-j) * -k + [unittest command line option](library/unittest#cmdoption-unittest-k) * -l + [compileall command line option](library/compileall#cmdoption-compileall-l) + [pickletools command line option](library/pickletools#cmdoption-pickletools-l) + [trace command line option](library/trace#cmdoption-trace-l) * -l <tarfile> + [tarfile command line option](library/tarfile#cmdoption-tarfile-l) * -l <zipfile> + [zipfile command line option](library/zipfile#cmdoption-zipfile-l) * -m + [pickletools command line option](library/pickletools#cmdoption-pickletools-m) + [trace command line option](library/trace#cmdoption-trace-m) * -m <mainfn> + [zipapp command line option](library/zipapp#cmdoption-zipapp-m) * -m <mode> + [ast command line option](library/ast#cmdoption-ast-m) * -m <module-name> + [command line option](using/cmdline#cmdoption-m) * -n N + [timeit command line option](library/timeit#cmdoption-timeit-n) * -O + [command line option](using/cmdline#cmdoption-o) * -o + [pickletools command line option](library/pickletools#cmdoption-pickletools-o) * -o <output> + [zipapp command line option](library/zipapp#cmdoption-zipapp-o) * -o level + [compileall command line option](library/compileall#cmdoption-compileall-o) * -OO + [command line option](using/cmdline#cmdoption-oo) * -p + [pickletools command line option](library/pickletools#cmdoption-pickletools-p) + [timeit command line option](library/timeit#cmdoption-timeit-p) + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-p) * -p <interpreter> + [zipapp command line option](library/zipapp#cmdoption-zipapp-p) * -p prepend\_prefix + [compileall command line option](library/compileall#cmdoption-compileall-p) * -q + [command line option](using/cmdline#cmdoption-q) + [compileall command line option](library/compileall#cmdoption-compileall-q) * -R + [command line option](using/cmdline#cmdoption-r) + [trace command line option](library/trace#cmdoption-trace-no-report) * -r + [compileall command line option](library/compileall#cmdoption-compileall-r) + [trace command line option](library/trace#cmdoption-trace-r) * -r N + [timeit command line option](library/timeit#cmdoption-timeit-r) * -S + [command line option](using/cmdline#id3) * -s + [command line option](using/cmdline#cmdoption-s) + [trace command line option](library/trace#cmdoption-trace-s) + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-s) * -s S + [timeit command line option](library/timeit#cmdoption-timeit-s) * -s strip\_prefix + [compileall command line option](library/compileall#cmdoption-compileall-s) * -T + [trace command line option](library/trace#cmdoption-trace-trackcalls) * -t + [trace command line option](library/trace#cmdoption-trace-t) + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-t) * -t <tarfile> + [tarfile command line option](library/tarfile#cmdoption-tarfile-t) * -t <zipfile> + [zipfile command line option](library/zipfile#cmdoption-zipfile-t) * -u + [command line option](using/cmdline#cmdoption-u) + [timeit command line option](library/timeit#cmdoption-timeit-u) * -V + [command line option](using/cmdline#cmdoption-v) * -v + [command line option](using/cmdline#id4) + [tarfile command line option](library/tarfile#cmdoption-tarfile-v) + [timeit command line option](library/timeit#cmdoption-timeit-v) + [unittest-discover command line option](library/unittest#cmdoption-unittest-discover-v) * -W arg + [command line option](using/cmdline#cmdoption-w) * -X + [command line option](using/cmdline#id5) * -x + [command line option](using/cmdline#cmdoption-x) * -x regex + [compileall command line option](library/compileall#cmdoption-compileall-x) * . (dot) + [attribute reference](reference/expressions#index-39) + [in glob-style wildcards](library/glob#index-1) + [in numeric literal](reference/lexical_analysis#index-28) + [in pathnames](library/os#index-39), [[1]](library/os#index-44) + [in printf-style formatting](library/stdtypes#index-34), [[1]](library/stdtypes#index-44) + [in regular expressions](library/re#index-0) + [in string formatting](library/string#index-2) + [in Tkinter](library/tkinter#index-2) * .. + [in pathnames](library/os#index-40) * [**...**](glossary#term-1) + [ellipsis literal](library/constants#index-0), [[1]](library/stdtypes#index-61), [[2]](reference/datamodel#index-8) + [in doctests](library/doctest#index-3) + [interpreter prompt](library/doctest#index-0), [[1]](library/sys#index-26) + [placeholder](library/pprint#index-0), [[1]](library/reprlib#index-0), [[2]](library/textwrap#index-0) * .ini + [file](library/configparser#index-0) * .pdbrc + [file](library/pdb#index-2) * / (slash) + [function definition](reference/compound_stmts#index-23) + [in pathnames](library/os#index-41), [[1]](library/os#index-43) + [operator](library/stdtypes#index-13), [[1]](reference/expressions#index-67) * // + [operator](library/stdtypes#index-13), [[1]](reference/expressions#index-67) * //= + [augmented assignment](reference/simple_stmts#index-14) * /= + [augmented assignment](reference/simple_stmts#index-14) * 0b + [integer literal](reference/lexical_analysis#index-27) * 0o + [integer literal](reference/lexical_analysis#index-27) * 0x + [integer literal](reference/lexical_analysis#index-27) * [2-digit years](library/time#index-3) * [**2to3**](glossary#term-2to3) * : (colon) + [annotated variable](reference/simple_stmts#index-15) + [compound statement](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-16), [[2]](reference/compound_stmts#index-19), [[3]](reference/compound_stmts#index-3), [[4]](reference/compound_stmts#index-31), [[5]](reference/compound_stmts#index-4), [[6]](reference/compound_stmts#index-6) + [function annotations](reference/compound_stmts#index-25), [[1]](tutorial/controlflow#index-5) + [in dictionary expressions](reference/expressions#index-17) + [in formatted string literal](reference/lexical_analysis#index-24) + [in SQL statements](library/sqlite3#index-3) + [in string formatting](library/string#index-2) + [lambda expression](reference/expressions#index-89) + [path separator (POSIX)](library/os#index-45) + [slicing](reference/expressions#index-44) * [; (semicolon)](library/os#index-45), [[1]](reference/compound_stmts#index-1) * < (less) + [in string formatting](library/string#index-3) + [in struct format strings](library/struct#index-1) + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * << + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-71) * <<= + [augmented assignment](reference/simple_stmts#index-14) * <= + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * [<BLANKLINE>](library/doctest#index-2) * = (equals) + [assignment statement](reference/simple_stmts#index-4) + [class definition](reference/datamodel#index-82) + [for help in debugging using string literals](reference/lexical_analysis#index-24) + [function definition](reference/compound_stmts#index-22) + [in function calls](reference/expressions#index-47) + [in string formatting](library/string#index-3) + [in struct format strings](library/struct#index-1) * == + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * > (greater) + [in string formatting](library/string#index-3) + [in struct format strings](library/struct#index-1) + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * >= + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-77) * >> + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-71) * >>= + [augmented assignment](reference/simple_stmts#index-14) * [**>>>**](glossary#term-0) + [interpreter prompt](library/doctest#index-0), [[1]](library/sys#index-26) * ? (question mark) + [in a command interpreter](library/cmd#index-0) + [in argparse module](library/argparse#index-0) + [in AST grammar](library/ast#index-0) + [in glob-style wildcards](library/fnmatch#index-2), [[1]](library/glob#index-1) + [in regular expressions](library/re#index-5) + [in SQL statements](library/sqlite3#index-2) + [in struct format strings](library/struct#index-2), [[1]](library/struct#index-3) + [replacement character](library/codecs#index-1) * ?? + [in regular expressions](library/re#index-6) * @ (at) + [class definition](reference/compound_stmts#index-32) + [function definition](reference/compound_stmts#index-20) + [in struct format strings](library/struct#index-1) + [operator](reference/expressions#index-66) * [] (square brackets) + [in assignment target list](reference/simple_stmts#index-6) + [in glob-style wildcards](library/fnmatch#index-2), [[1]](library/glob#index-1) + [in regular expressions](library/re#index-9) + [in string formatting](library/string#index-2) + [list expression](reference/expressions#index-15) + [subscription](reference/expressions#index-41) * \ (backslash) + [escape sequence](library/codecs#index-1), [[1]](reference/lexical_analysis#index-22) + [in pathnames (Windows)](library/os#index-42) + [in regular expressions](library/re#index-11), [[1]](library/re#index-24), [[2]](library/re#index-8) * \\ + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \A + [in regular expressions](library/re#index-25) * \a + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \B + [in regular expressions](library/re#index-27) * \b + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-26), [[1]](library/re#index-35) * \D + [in regular expressions](library/re#index-29) * \d + [in regular expressions](library/re#index-28) * \f + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \g + [in regular expressions](library/re#index-37) * \N + [escape sequence](library/codecs#index-3), [[1]](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \n + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \r + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \S + [in regular expressions](library/re#index-31) * \s + [in regular expressions](library/re#index-30) * \t + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \U + [escape sequence](library/codecs#index-1), [[1]](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \u + [escape sequence](library/codecs#index-1), [[1]](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \v + [escape sequence](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \W + [in regular expressions](library/re#index-33) * \w + [in regular expressions](library/re#index-32) * \x + [escape sequence](library/codecs#index-1), [[1]](reference/lexical_analysis#index-22) + [in regular expressions](library/re#index-35) * \Z + [in regular expressions](library/re#index-34) * ^ (caret) + [in curses module](library/curses.ascii#index-0) + [in regular expressions](library/re#index-1), [[1]](library/re#index-12) + [in string formatting](library/string#index-3) + [marker](library/doctest#index-1), [[1]](library/traceback#index-1) + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-75) * ^= + [augmented assignment](reference/simple_stmts#index-14) * {} (curly brackets) + [dictionary expression](reference/expressions#index-17) + [in formatted string literal](reference/lexical_analysis#index-24) + [in regular expressions](library/re#index-7) + [in string formatting](library/string#index-2) + [set expression](reference/expressions#index-16) * | (vertical bar) + [in regular expressions](library/re#index-13) + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-76) * |= + [augmented assignment](reference/simple_stmts#index-14) * ~ (tilde) + [home directory expansion](library/os.path#index-1) + [operator](library/stdtypes#index-16), [[1]](reference/expressions#index-62) | \_ -- | | | | --- | --- | | * \_ (underscore) + [gettext](library/gettext#index-4) + [in numeric literal](reference/lexical_analysis#index-27), [[1]](reference/lexical_analysis#index-28) + [in string formatting](library/string#index-8) * [\_, identifiers](reference/lexical_analysis#index-14) * [\_\_, identifiers](reference/lexical_analysis#index-14) * [\_\_abs\_\_() (in module operator)](library/operator#operator.__abs__) + [(object method)](reference/datamodel#object.__abs__) * [\_\_add\_\_() (in module operator)](library/operator#operator.__add__) + [(object method)](reference/datamodel#object.__add__) * [\_\_aenter\_\_() (object method)](reference/datamodel#object.__aenter__) * [\_\_aexit\_\_() (object method)](reference/datamodel#object.__aexit__) * [\_\_aiter\_\_() (object method)](reference/datamodel#object.__aiter__) * [\_\_all\_\_](tutorial/modules#index-8) + [(optional module attribute)](reference/simple_stmts#index-38) + [(package variable)](c-api/import#index-0) * [\_\_and\_\_() (in module operator)](library/operator#operator.__and__) + [(object method)](reference/datamodel#object.__and__) * [\_\_anext\_\_() (agen method)](reference/expressions#agen.__anext__) + [(object method)](reference/datamodel#object.__anext__) * [\_\_annotations\_\_ (class attribute)](reference/datamodel#index-48) + [(function attribute)](reference/datamodel#index-34) + [(module attribute)](reference/datamodel#index-43) * [\_\_args\_\_ (genericalias attribute)](library/stdtypes#genericalias.__args__) * [\_\_await\_\_() (object method)](reference/datamodel#object.__await__) * [\_\_bases\_\_ (class attribute)](library/stdtypes#class.__bases__), [[1]](reference/datamodel#index-48) * [\_\_bool\_\_() (object method)](reference/datamodel#index-94), [[1]](reference/datamodel#object.__bool__) * [\_\_breakpointhook\_\_ (in module sys)](library/sys#sys.__breakpointhook__) * [\_\_bytes\_\_() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__bytes__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__bytes__) + [(object method)](reference/datamodel#object.__bytes__) * [\_\_cached\_\_](reference/import#__cached__) * [\_\_call\_\_() (email.headerregistry.HeaderRegistry method)](library/email.headerregistry#email.headerregistry.HeaderRegistry.__call__) + [(object method)](reference/datamodel#object.__call__), [[1]](reference/expressions#index-56) + [(weakref.finalize method)](library/weakref#weakref.finalize.__call__) * [\_\_callback\_\_ (weakref.ref attribute)](library/weakref#weakref.ref.__callback__) * [\_\_cause\_\_ (exception attribute)](reference/simple_stmts#index-29) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.__cause__) * [\_\_ceil\_\_() (fractions.Fraction method)](library/fractions#fractions.Fraction.__ceil__) + [(object method)](reference/datamodel#object.__ceil__) * [\_\_class\_\_ (instance attribute)](library/stdtypes#instance.__class__), [[1]](reference/datamodel#index-52) + [(method cell)](reference/datamodel#index-88) + [(module attribute)](reference/datamodel#index-79) + [(unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.__class__) * [\_\_class\_getitem\_\_() (object class method)](reference/datamodel#object.__class_getitem__) * [\_\_classcell\_\_ (class namespace entry)](reference/datamodel#index-88) * [\_\_closure\_\_ (function attribute)](reference/datamodel#index-34) * [\_\_code\_\_ (function attribute)](reference/datamodel#index-34) + [(function object attribute)](library/stdtypes#index-58) * [\_\_complex\_\_() (object method)](reference/datamodel#object.__complex__) * [\_\_concat\_\_() (in module operator)](library/operator#operator.__concat__) * [\_\_contains\_\_() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__contains__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__contains__) + [(in module operator)](library/operator#operator.__contains__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__contains__) + [(object method)](reference/datamodel#object.__contains__) * [\_\_context\_\_ (exception attribute)](reference/simple_stmts#index-29) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.__context__) * [\_\_copy\_\_() (copy protocol)](library/copy#index-1) * [\_\_debug\_\_](reference/simple_stmts#index-19) + [(built-in variable)](library/constants#__debug__) * [\_\_deepcopy\_\_() (copy protocol)](library/copy#index-1) * [\_\_defaults\_\_ (function attribute)](reference/datamodel#index-34) * [\_\_del\_\_() (io.IOBase method)](library/io#io.IOBase.__del__) + [(object method)](reference/datamodel#object.__del__) * [\_\_delattr\_\_() (object method)](reference/datamodel#object.__delattr__) * [\_\_delete\_\_() (object method)](reference/datamodel#object.__delete__) * [\_\_delitem\_\_() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__delitem__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__delitem__) + [(in module operator)](library/operator#operator.__delitem__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__delitem__) + [(mailbox.MH method)](library/mailbox#mailbox.MH.__delitem__) + [(object method)](reference/datamodel#object.__delitem__) * [\_\_dict\_\_ (class attribute)](reference/datamodel#index-48) + [(function attribute)](reference/datamodel#index-34) + [(instance attribute)](reference/datamodel#index-52) + [(module attribute)](c-api/module#index-3), [[1]](reference/datamodel#index-44) + [(object attribute)](library/stdtypes#object.__dict__) * [\_\_dir\_\_ (module attribute)](reference/datamodel#index-79) * [\_\_dir\_\_() (object method)](reference/datamodel#object.__dir__) + [(unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.__dir__) * [\_\_displayhook\_\_ (in module sys)](library/sys#sys.__displayhook__) * [\_\_divmod\_\_() (object method)](reference/datamodel#object.__divmod__) * [\_\_doc\_\_ (class attribute)](reference/datamodel#index-48) + [(function attribute)](reference/datamodel#index-34) + [(method attribute)](reference/datamodel#index-36) + [(module attribute)](c-api/module#index-2), [[1]](reference/datamodel#index-43) + [(types.ModuleType attribute)](library/types#types.ModuleType.__doc__) * [\_\_enter\_\_() (contextmanager method)](library/stdtypes#contextmanager.__enter__) + [(object method)](reference/datamodel#object.__enter__) + [(winreg.PyHKEY method)](library/winreg#winreg.PyHKEY.__enter__) * [\_\_eq\_\_() (email.charset.Charset method)](library/email.charset#email.charset.Charset.__eq__) + [(email.header.Header method)](library/email.header#email.header.Header.__eq__) + [(in module operator)](library/operator#operator.__eq__) + [(instance method)](library/stdtypes#index-9) + [(memoryview method)](library/stdtypes#memoryview.__eq__) + [(object method)](reference/datamodel#object.__eq__) * [\_\_excepthook\_\_ (in module sys)](library/sys#sys.__excepthook__) * [\_\_exit\_\_() (contextmanager method)](library/stdtypes#contextmanager.__exit__) + [(object method)](reference/datamodel#object.__exit__) + [(winreg.PyHKEY method)](library/winreg#winreg.PyHKEY.__exit__) * [\_\_file\_\_](reference/import#__file__) + [(module attribute)](c-api/module#index-2), [[1]](c-api/module#index-5), [[2]](reference/datamodel#index-43) * [\_\_float\_\_() (object method)](reference/datamodel#object.__float__) * [\_\_floor\_\_() (fractions.Fraction method)](library/fractions#fractions.Fraction.__floor__) + [(object method)](reference/datamodel#object.__floor__) * [\_\_floordiv\_\_() (in module operator)](library/operator#operator.__floordiv__) + [(object method)](reference/datamodel#object.__floordiv__) * [\_\_format\_\_](library/functions#index-3) * [\_\_format\_\_() (datetime.date method)](library/datetime#datetime.date.__format__) + [(datetime.datetime method)](library/datetime#datetime.datetime.__format__) + [(datetime.time method)](library/datetime#datetime.time.__format__) + [(ipaddress.IPv4Address method)](library/ipaddress#ipaddress.IPv4Address.__format__) + [(ipaddress.IPv6Address method)](library/ipaddress#ipaddress.IPv6Address.__format__) + [(object method)](reference/datamodel#object.__format__) * [\_\_fspath\_\_() (os.PathLike method)](library/os#os.PathLike.__fspath__) * [\_\_func\_\_ (method attribute)](reference/datamodel#index-36) * [**\_\_future\_\_**](glossary#term-future) + [future statement](reference/simple_stmts#index-40) * [\_\_future\_\_ (module)](library/__future__#module-__future__) * [\_\_ge\_\_() (in module operator)](library/operator#operator.__ge__) + [(instance method)](library/stdtypes#index-9) + [(object method)](reference/datamodel#object.__ge__) * [\_\_get\_\_() (object method)](reference/datamodel#object.__get__) * [\_\_getattr\_\_ (module attribute)](reference/datamodel#index-79) * [\_\_getattr\_\_() (object method)](reference/datamodel#object.__getattr__) * [\_\_getattribute\_\_() (object method)](reference/datamodel#object.__getattribute__) * [\_\_getitem\_\_() (email.headerregistry.HeaderRegistry method)](library/email.headerregistry#email.headerregistry.HeaderRegistry.__getitem__) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__getitem__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__getitem__) + [(in module operator)](library/operator#operator.__getitem__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__getitem__) + [(mapping object method)](reference/datamodel#index-67) + [(object method)](reference/datamodel#object.__getitem__) + [(re.Match method)](library/re#re.Match.__getitem__) * [\_\_getnewargs\_\_() (object method)](library/pickle#object.__getnewargs__) * [\_\_getnewargs\_ex\_\_() (object method)](library/pickle#object.__getnewargs_ex__) * [\_\_getstate\_\_() (copy protocol)](library/pickle#index-7) + [(object method)](library/pickle#object.__getstate__) * [\_\_globals\_\_ (function attribute)](reference/datamodel#index-34) * [\_\_gt\_\_() (in module operator)](library/operator#operator.__gt__) + [(instance method)](library/stdtypes#index-9) + [(object method)](reference/datamodel#object.__gt__) * [\_\_hash\_\_() (object method)](reference/datamodel#object.__hash__) * [\_\_iadd\_\_() (in module operator)](library/operator#operator.__iadd__) + [(object method)](reference/datamodel#object.__iadd__) * [\_\_iand\_\_() (in module operator)](library/operator#operator.__iand__) + [(object method)](reference/datamodel#object.__iand__) * [\_\_iconcat\_\_() (in module operator)](library/operator#operator.__iconcat__) * [\_\_ifloordiv\_\_() (in module operator)](library/operator#operator.__ifloordiv__) + [(object method)](reference/datamodel#object.__ifloordiv__) * [\_\_ilshift\_\_() (in module operator)](library/operator#operator.__ilshift__) + [(object method)](reference/datamodel#object.__ilshift__) * [\_\_imatmul\_\_() (in module operator)](library/operator#operator.__imatmul__) + [(object method)](reference/datamodel#object.__imatmul__) * [\_\_imod\_\_() (in module operator)](library/operator#operator.__imod__) + [(object method)](reference/datamodel#object.__imod__) * \_\_import\_\_ + [built-in function](c-api/import#index-1) * [\_\_import\_\_() (built-in function)](library/functions#__import__) + [(in module importlib)](library/importlib#importlib.__import__) * [\_\_imul\_\_() (in module operator)](library/operator#operator.__imul__) + [(object method)](reference/datamodel#object.__imul__) * [\_\_index\_\_() (in module operator)](library/operator#operator.__index__) + [(object method)](reference/datamodel#object.__index__) * [\_\_init\_\_() (difflib.HtmlDiff method)](library/difflib#difflib.HtmlDiff.__init__) + [(logging.Handler method)](library/logging#logging.Handler.__init__) + [(logging.logging.Formatter method)](howto/logging#logging.logging.Formatter.__init__) + [(object method)](reference/datamodel#object.__init__) * [\_\_init\_subclass\_\_() (object class method)](reference/datamodel#object.__init_subclass__) * [\_\_instancecheck\_\_() (class method)](reference/datamodel#class.__instancecheck__) * [\_\_int\_\_() (object method)](reference/datamodel#object.__int__) * [\_\_interactivehook\_\_ (in module sys)](library/sys#sys.__interactivehook__) * [\_\_inv\_\_() (in module operator)](library/operator#operator.__inv__) * [\_\_invert\_\_() (in module operator)](library/operator#operator.__invert__) + [(object method)](reference/datamodel#object.__invert__) * [\_\_ior\_\_() (in module operator)](library/operator#operator.__ior__) + [(object method)](reference/datamodel#object.__ior__) * [\_\_ipow\_\_() (in module operator)](library/operator#operator.__ipow__) + [(object method)](reference/datamodel#object.__ipow__) * [\_\_irshift\_\_() (in module operator)](library/operator#operator.__irshift__) + [(object method)](reference/datamodel#object.__irshift__) * [\_\_isub\_\_() (in module operator)](library/operator#operator.__isub__) + [(object method)](reference/datamodel#object.__isub__) * [\_\_iter\_\_() (container method)](library/stdtypes#container.__iter__) + [(iterator method)](library/stdtypes#iterator.__iter__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__iter__) + [(object method)](reference/datamodel#object.__iter__) + [(unittest.TestSuite method)](library/unittest#unittest.TestSuite.__iter__) * [\_\_itruediv\_\_() (in module operator)](library/operator#operator.__itruediv__) + [(object method)](reference/datamodel#object.__itruediv__) * [\_\_ixor\_\_() (in module operator)](library/operator#operator.__ixor__) + [(object method)](reference/datamodel#object.__ixor__) * [\_\_kwdefaults\_\_ (function attribute)](reference/datamodel#index-34) * [\_\_le\_\_() (in module operator)](library/operator#operator.__le__) + [(instance method)](library/stdtypes#index-9) + [(object method)](reference/datamodel#object.__le__) | * [\_\_len\_\_() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__len__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__len__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__len__) + [(mapping object method)](reference/datamodel#index-78) + [(object method)](reference/datamodel#object.__len__) * [\_\_length\_hint\_\_() (object method)](reference/datamodel#object.__length_hint__) * [\_\_loader\_\_](reference/import#__loader__) + [(module attribute)](c-api/module#index-2) + [(types.ModuleType attribute)](library/types#types.ModuleType.__loader__) * [\_\_lshift\_\_() (in module operator)](library/operator#operator.__lshift__) + [(object method)](reference/datamodel#object.__lshift__) * [\_\_lt\_\_() (in module operator)](library/operator#operator.__lt__) + [(instance method)](library/stdtypes#index-9) + [(object method)](reference/datamodel#object.__lt__) * \_\_main\_\_ + [module](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](library/runpy#index-0), [[4]](library/runpy#index-4), [[5]](reference/executionmodel#index-10), [[6]](reference/toplevel_components#index-2), [[7]](reference/toplevel_components#index-3) * [\_\_main\_\_ (module)](library/__main__#module-__main__) * [\_\_matmul\_\_() (in module operator)](library/operator#operator.__matmul__) + [(object method)](reference/datamodel#object.__matmul__) * [\_\_missing\_\_()](library/stdtypes#index-51) + [(collections.defaultdict method)](library/collections#collections.defaultdict.__missing__) + [(object method)](reference/datamodel#object.__missing__) * [\_\_mod\_\_() (in module operator)](library/operator#operator.__mod__) + [(object method)](reference/datamodel#object.__mod__) * [\_\_module\_\_ (class attribute)](reference/datamodel#index-48) + [(function attribute)](reference/datamodel#index-34) + [(method attribute)](reference/datamodel#index-36) * [\_\_mro\_\_ (class attribute)](library/stdtypes#class.__mro__) * [\_\_mul\_\_() (in module operator)](library/operator#operator.__mul__) + [(object method)](reference/datamodel#object.__mul__) * [\_\_name\_\_](reference/import#__name__) + [(class attribute)](reference/datamodel#index-48) + [(definition attribute)](library/stdtypes#definition.__name__) + [(function attribute)](reference/datamodel#index-34) + [(method attribute)](reference/datamodel#index-36) + [(module attribute)](c-api/module#index-2), [[1]](c-api/module#index-4), [[2]](reference/datamodel#index-43) + [(types.ModuleType attribute)](library/types#types.ModuleType.__name__) * [\_\_ne\_\_() (email.charset.Charset method)](library/email.charset#email.charset.Charset.__ne__) + [(email.header.Header method)](library/email.header#email.header.Header.__ne__) + [(in module operator)](library/operator#operator.__ne__) + [(instance method)](library/stdtypes#index-9) + [(object method)](reference/datamodel#object.__ne__) * [\_\_neg\_\_() (in module operator)](library/operator#operator.__neg__) + [(object method)](reference/datamodel#object.__neg__) * [\_\_new\_\_() (object method)](reference/datamodel#object.__new__) * [\_\_next\_\_() (csv.csvreader method)](library/csv#csv.csvreader.__next__) + [(generator method)](reference/expressions#generator.__next__) + [(iterator method)](library/stdtypes#iterator.__next__) * [\_\_not\_\_() (in module operator)](library/operator#operator.__not__) * [\_\_optional\_keys\_\_ (typing.TypedDict attribute)](library/typing#typing.TypedDict.__optional_keys__) * [\_\_or\_\_() (in module operator)](library/operator#operator.__or__) + [(object method)](reference/datamodel#object.__or__) * [\_\_origin\_\_ (genericalias attribute)](library/stdtypes#genericalias.__origin__) * [\_\_package\_\_](reference/import#__package__) + [(module attribute)](c-api/module#index-2) + [(types.ModuleType attribute)](library/types#types.ModuleType.__package__) * [\_\_parameters\_\_ (genericalias attribute)](library/stdtypes#genericalias.__parameters__) * [\_\_path\_\_](reference/import#__path__) * [\_\_pos\_\_() (in module operator)](library/operator#operator.__pos__) + [(object method)](reference/datamodel#object.__pos__) * [\_\_pow\_\_() (in module operator)](library/operator#operator.__pow__) + [(object method)](reference/datamodel#object.__pow__) * [\_\_prepare\_\_ (metaclass method)](reference/datamodel#index-85) * [\_\_qualname\_\_ (definition attribute)](library/stdtypes#definition.__qualname__) * [\_\_radd\_\_() (object method)](reference/datamodel#object.__radd__) * [\_\_rand\_\_() (object method)](reference/datamodel#object.__rand__) * [\_\_rdivmod\_\_() (object method)](reference/datamodel#object.__rdivmod__) * [\_\_reduce\_\_() (object method)](library/pickle#object.__reduce__) * [\_\_reduce\_ex\_\_() (object method)](library/pickle#object.__reduce_ex__) * [\_\_repr\_\_() (multiprocessing.managers.BaseProxy method)](library/multiprocessing#multiprocessing.managers.BaseProxy.__repr__) + [(netrc.netrc method)](library/netrc#netrc.netrc.__repr__) + [(object method)](reference/datamodel#object.__repr__) * [\_\_required\_keys\_\_ (typing.TypedDict attribute)](library/typing#typing.TypedDict.__required_keys__) * [\_\_reversed\_\_() (object method)](reference/datamodel#object.__reversed__) * [\_\_rfloordiv\_\_() (object method)](reference/datamodel#object.__rfloordiv__) * [\_\_rlshift\_\_() (object method)](reference/datamodel#object.__rlshift__) * [\_\_rmatmul\_\_() (object method)](reference/datamodel#object.__rmatmul__) * [\_\_rmod\_\_() (object method)](reference/datamodel#object.__rmod__) * [\_\_rmul\_\_() (object method)](reference/datamodel#object.__rmul__) * [\_\_ror\_\_() (object method)](reference/datamodel#object.__ror__) * [\_\_round\_\_() (fractions.Fraction method)](library/fractions#fractions.Fraction.__round__) + [(object method)](reference/datamodel#object.__round__) * [\_\_rpow\_\_() (object method)](reference/datamodel#object.__rpow__) * [\_\_rrshift\_\_() (object method)](reference/datamodel#object.__rrshift__) * [\_\_rshift\_\_() (in module operator)](library/operator#operator.__rshift__) + [(object method)](reference/datamodel#object.__rshift__) * [\_\_rsub\_\_() (object method)](reference/datamodel#object.__rsub__) * [\_\_rtruediv\_\_() (object method)](reference/datamodel#object.__rtruediv__) * [\_\_rxor\_\_() (object method)](reference/datamodel#object.__rxor__) * [\_\_self\_\_ (method attribute)](reference/datamodel#index-36) * [\_\_set\_\_() (object method)](reference/datamodel#object.__set__) * [\_\_set\_name\_\_() (object method)](reference/datamodel#object.__set_name__) * [\_\_setattr\_\_() (object method)](reference/datamodel#object.__setattr__) * [\_\_setitem\_\_() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__setitem__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__setitem__) + [(in module operator)](library/operator#operator.__setitem__) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.__setitem__) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.__setitem__) + [(object method)](reference/datamodel#object.__setitem__) * [\_\_setstate\_\_() (copy protocol)](library/pickle#index-7) + [(object method)](library/pickle#object.__setstate__) * [**\_\_slots\_\_**](glossary#term-slots) * [\_\_spec\_\_](reference/import#__spec__) + [(types.ModuleType attribute)](library/types#types.ModuleType.__spec__) * [\_\_stderr\_\_ (in module sys)](library/sys#sys.__stderr__) * [\_\_stdin\_\_ (in module sys)](library/sys#sys.__stdin__) * [\_\_stdout\_\_ (in module sys)](library/sys#sys.__stdout__) * [\_\_str\_\_() (datetime.date method)](library/datetime#datetime.date.__str__) + [(datetime.datetime method)](library/datetime#datetime.datetime.__str__) + [(datetime.time method)](library/datetime#datetime.time.__str__) + [(email.charset.Charset method)](library/email.charset#email.charset.Charset.__str__) + [(email.header.Header method)](library/email.header#email.header.Header.__str__) + [(email.headerregistry.Address method)](library/email.headerregistry#email.headerregistry.Address.__str__) + [(email.headerregistry.Group method)](library/email.headerregistry#email.headerregistry.Group.__str__) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.__str__) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.__str__) + [(multiprocessing.managers.BaseProxy method)](library/multiprocessing#multiprocessing.managers.BaseProxy.__str__) + [(object method)](reference/datamodel#object.__str__) * [\_\_sub\_\_() (in module operator)](library/operator#operator.__sub__) + [(object method)](reference/datamodel#object.__sub__) * [\_\_subclasscheck\_\_() (class method)](reference/datamodel#class.__subclasscheck__) * [\_\_subclasses\_\_() (class method)](library/stdtypes#class.__subclasses__) * [\_\_subclasshook\_\_() (abc.ABCMeta method)](library/abc#abc.ABCMeta.__subclasshook__) * [\_\_suppress\_context\_\_ (traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.__suppress_context__) * [\_\_total\_\_ (typing.TypedDict attribute)](library/typing#typing.TypedDict.__total__) * [\_\_traceback\_\_ (exception attribute)](reference/simple_stmts#index-27) * [\_\_truediv\_\_() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.__truediv__) + [(in module operator)](library/operator#operator.__truediv__) + [(object method)](reference/datamodel#object.__truediv__) * [\_\_trunc\_\_() (object method)](reference/datamodel#object.__trunc__) * [\_\_unraisablehook\_\_ (in module sys)](library/sys#sys.__unraisablehook__) * [\_\_xor\_\_() (in module operator)](library/operator#operator.__xor__) + [(object method)](reference/datamodel#object.__xor__) * [\_anonymous\_ (ctypes.Structure attribute)](library/ctypes#ctypes.Structure._anonymous_) * [\_asdict() (collections.somenamedtuple method)](library/collections#collections.somenamedtuple._asdict) * [\_b\_base\_ (ctypes.\_CData attribute)](library/ctypes#ctypes._CData._b_base_) * [\_b\_needsfree\_ (ctypes.\_CData attribute)](library/ctypes#ctypes._CData._b_needsfree_) * [\_callmethod() (multiprocessing.managers.BaseProxy method)](library/multiprocessing#multiprocessing.managers.BaseProxy._callmethod) * [\_CData (class in ctypes)](library/ctypes#ctypes._CData) * [\_clear\_type\_cache() (in module sys)](library/sys#sys._clear_type_cache) * [\_current\_frames() (in module sys)](library/sys#sys._current_frames) * [\_debugmallocstats() (in module sys)](library/sys#sys._debugmallocstats) * [\_enablelegacywindowsfsencoding() (in module sys)](library/sys#sys._enablelegacywindowsfsencoding) * [\_exit() (in module os)](library/os#os._exit) * [\_field\_defaults (collections.somenamedtuple attribute)](library/collections#collections.somenamedtuple._field_defaults) * [\_fields (ast.AST attribute)](library/ast#ast.AST._fields) + [(collections.somenamedtuple attribute)](library/collections#collections.somenamedtuple._fields) * [\_fields\_ (ctypes.Structure attribute)](library/ctypes#ctypes.Structure._fields_) * [\_flush() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler._flush) * [\_frozen (C type)](c-api/import#c._frozen) * [\_FuncPtr (class in ctypes)](library/ctypes#ctypes._FuncPtr) * [\_get\_child\_mock() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock._get_child_mock) * [\_getframe() (in module sys)](library/sys#sys._getframe) * [\_getvalue() (multiprocessing.managers.BaseProxy method)](library/multiprocessing#multiprocessing.managers.BaseProxy._getvalue) * [\_handle (ctypes.PyDLL attribute)](library/ctypes#ctypes.PyDLL._handle) * [\_inittab (C type)](c-api/import#c._inittab) * [\_length\_ (ctypes.Array attribute)](library/ctypes#ctypes.Array._length_) * \_locale + [module](library/locale#index-0) * [\_make() (collections.somenamedtuple class method)](library/collections#collections.somenamedtuple._make) * [\_makeResult() (unittest.TextTestRunner method)](library/unittest#unittest.TextTestRunner._makeResult) * [\_name (ctypes.PyDLL attribute)](library/ctypes#ctypes.PyDLL._name) * [\_objects (ctypes.\_CData attribute)](library/ctypes#ctypes._CData._objects) * [\_pack\_ (ctypes.Structure attribute)](library/ctypes#ctypes.Structure._pack_) * [\_parse() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations._parse) * [\_Pointer (class in ctypes)](library/ctypes#ctypes._Pointer) * [\_Py\_c\_diff (C function)](c-api/complex#c._Py_c_diff) * [\_Py\_c\_neg (C function)](c-api/complex#c._Py_c_neg) * [\_Py\_c\_pow (C function)](c-api/complex#c._Py_c_pow) * [\_Py\_c\_prod (C function)](c-api/complex#c._Py_c_prod) * [\_Py\_c\_quot (C function)](c-api/complex#c._Py_c_quot) * [\_Py\_c\_sum (C function)](c-api/complex#c._Py_c_sum) * [\_Py\_InitializeMain (C function)](c-api/init_config#c._Py_InitializeMain) * [\_Py\_NoneStruct (C variable)](c-api/allocation#c._Py_NoneStruct) * [\_PyBytes\_Resize (C function)](c-api/bytes#c._PyBytes_Resize) * [\_PyCFunctionFast (C type)](c-api/structures#c._PyCFunctionFast) * [\_PyCFunctionFastWithKeywords (C type)](c-api/structures#c._PyCFunctionFastWithKeywords) * [\_PyFrameEvalFunction (C type)](c-api/init#c._PyFrameEvalFunction) * [\_PyInterpreterState\_GetEvalFrameFunc (C function)](c-api/init#c._PyInterpreterState_GetEvalFrameFunc) * [\_PyInterpreterState\_SetEvalFrameFunc (C function)](c-api/init#c._PyInterpreterState_SetEvalFrameFunc) * [\_PyObject\_New (C function)](c-api/allocation#c._PyObject_New) * [\_PyObject\_NewVar (C function)](c-api/allocation#c._PyObject_NewVar) * [\_PyTuple\_Resize (C function)](c-api/tuple#c._PyTuple_Resize) * [\_replace() (collections.somenamedtuple method)](library/collections#collections.somenamedtuple._replace) * [\_setroot() (xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree._setroot) * [\_SimpleCData (class in ctypes)](library/ctypes#ctypes._SimpleCData) * [\_structure() (in module email.iterators)](library/email.iterators#email.iterators._structure) * \_thread + [module](c-api/init#index-39) * [\_thread (module)](library/_thread#module-_thread) * [\_type\_ (ctypes.\_Pointer attribute)](library/ctypes#ctypes._Pointer._type_) + [(ctypes.Array attribute)](library/ctypes#ctypes.Array._type_) * [\_write() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler._write) * [\_xoptions (in module sys)](library/sys#sys._xoptions) | A - | | | | --- | --- | | * [A (in module re)](library/re#re.A) * [A-LAW](library/aifc#index-2), [[1]](library/sndhdr#index-0) * [a-LAW](library/audioop#index-1) * [a2b\_base64() (in module binascii)](library/binascii#binascii.a2b_base64) * [a2b\_hex() (in module binascii)](library/binascii#binascii.a2b_hex) * [a2b\_hqx() (in module binascii)](library/binascii#binascii.a2b_hqx) * [a2b\_qp() (in module binascii)](library/binascii#binascii.a2b_qp) * [a2b\_uu() (in module binascii)](library/binascii#binascii.a2b_uu) * [a85decode() (in module base64)](library/base64#base64.a85decode) * [a85encode() (in module base64)](library/base64#base64.a85encode) * [ABC (class in abc)](library/abc#abc.ABC) * [abc (module)](library/abc#module-abc) * [ABCMeta (class in abc)](library/abc#abc.ABCMeta) * [abiflags (in module sys)](library/sys#sys.abiflags) * [abort()](c-api/sys#index-1) + [(asyncio.DatagramTransport method)](library/asyncio-protocol#asyncio.DatagramTransport.abort) + [(asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.abort) + [(ftplib.FTP method)](library/ftplib#ftplib.FTP.abort) + [(in module os)](library/os#os.abort) + [(threading.Barrier method)](library/threading#threading.Barrier.abort) * [above() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.above) * [ABOVE\_NORMAL\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.ABOVE_NORMAL_PRIORITY_CLASS) * abs + [built-in function](c-api/number#index-2), [[1]](reference/datamodel#index-99) * [abs() (built-in function)](library/functions#abs) + [(decimal.Context method)](library/decimal#decimal.Context.abs) + [(in module operator)](library/operator#operator.abs) * [abspath() (in module os.path)](library/os.path#os.path.abspath) * [**abstract base class**](glossary#term-abstract-base-class) * [AbstractAsyncContextManager (class in contextlib)](library/contextlib#contextlib.AbstractAsyncContextManager) * [AbstractBasicAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.AbstractBasicAuthHandler) * [AbstractChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.AbstractChildWatcher) * [abstractclassmethod() (in module abc)](library/abc#abc.abstractclassmethod) * [AbstractContextManager (class in contextlib)](library/contextlib#contextlib.AbstractContextManager) * [AbstractDigestAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.AbstractDigestAuthHandler) * [AbstractEventLoop (class in asyncio)](library/asyncio-eventloop#asyncio.AbstractEventLoop) * [AbstractEventLoopPolicy (class in asyncio)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy) * [AbstractFormatter (class in formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.AbstractFormatter) * [abstractmethod() (in module abc)](library/abc#abc.abstractmethod) * [abstractproperty() (in module abc)](library/abc#abc.abstractproperty) * [AbstractSet (class in typing)](library/typing#typing.AbstractSet) * [abstractstaticmethod() (in module abc)](library/abc#abc.abstractstaticmethod) * [AbstractWriter (class in formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.AbstractWriter) * [accept() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.accept) + [(multiprocessing.connection.Listener method)](library/multiprocessing#multiprocessing.connection.Listener.accept) + [(socket.socket method)](library/socket#socket.socket.accept) * [access() (in module os)](library/os#os.access) * [accumulate() (in module itertools)](library/itertools#itertools.accumulate) * [aclose() (agen method)](reference/expressions#agen.aclose) + [(contextlib.AsyncExitStack method)](library/contextlib#contextlib.AsyncExitStack.aclose) * [acos() (in module cmath)](library/cmath#cmath.acos) + [(in module math)](library/math#math.acos) * [acosh() (in module cmath)](library/cmath#cmath.acosh) + [(in module math)](library/math#math.acosh) * [acquire() (\_thread.lock method)](library/_thread#_thread.lock.acquire) + [(asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.acquire) + [(asyncio.Lock method)](library/asyncio-sync#asyncio.Lock.acquire) + [(asyncio.Semaphore method)](library/asyncio-sync#asyncio.Semaphore.acquire) + [(logging.Handler method)](library/logging#logging.Handler.acquire) + [(multiprocessing.Lock method)](library/multiprocessing#multiprocessing.Lock.acquire) + [(multiprocessing.RLock method)](library/multiprocessing#multiprocessing.RLock.acquire) + [(threading.Condition method)](library/threading#threading.Condition.acquire) + [(threading.Lock method)](library/threading#threading.Lock.acquire) + [(threading.RLock method)](library/threading#threading.RLock.acquire) + [(threading.Semaphore method)](library/threading#threading.Semaphore.acquire) * [acquire\_lock() (in module imp)](library/imp#imp.acquire_lock) * [Action (class in argparse)](library/argparse#argparse.Action) * [action (optparse.Option attribute)](library/optparse#optparse.Option.action) * [ACTIONS (optparse.Option attribute)](library/optparse#optparse.Option.ACTIONS) * [active\_children() (in module multiprocessing)](library/multiprocessing#multiprocessing.active_children) * [active\_count() (in module threading)](library/threading#threading.active_count) * [actual() (tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.actual) * [Add (class in ast)](library/ast#ast.Add) * [add() (decimal.Context method)](library/decimal#decimal.Context.add) + [(frozenset method)](library/stdtypes#frozenset.add) + [(graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.add) + [(in module audioop)](library/audioop#audioop.add) + [(in module operator)](library/operator#operator.add) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.add) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.add) + [(msilib.RadioButtonGroup method)](library/msilib#msilib.RadioButtonGroup.add) + [(pstats.Stats method)](library/profile#pstats.Stats.add) + [(tarfile.TarFile method)](library/tarfile#tarfile.TarFile.add) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.add) * [add\_alias() (in module email.charset)](library/email.charset#email.charset.add_alias) * [add\_alternative() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.add_alternative) * [add\_argument() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.add_argument) * [add\_argument\_group() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.add_argument_group) * [add\_attachment() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.add_attachment) * [add\_cgi\_vars() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.add_cgi_vars) * [add\_charset() (in module email.charset)](library/email.charset#email.charset.add_charset) * [add\_child\_handler() (asyncio.AbstractChildWatcher method)](library/asyncio-policy#asyncio.AbstractChildWatcher.add_child_handler) * [add\_codec() (in module email.charset)](library/email.charset#email.charset.add_codec) * [add\_cookie\_header() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.add_cookie_header) * [add\_data() (in module msilib)](library/msilib#msilib.add_data) * [add\_dll\_directory() (in module os)](library/os#os.add_dll_directory) * [add\_done\_callback() (asyncio.Future method)](library/asyncio-future#asyncio.Future.add_done_callback) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.add_done_callback) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.add_done_callback) * [add\_fallback() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.add_fallback) * [add\_file() (msilib.Directory method)](library/msilib#msilib.Directory.add_file) * [add\_flag() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.add_flag) + [(mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.add_flag) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.add_flag) * [add\_flowing\_data() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.add_flowing_data) * [add\_folder() (mailbox.Maildir method)](library/mailbox#mailbox.Maildir.add_folder) + [(mailbox.MH method)](library/mailbox#mailbox.MH.add_folder) * [add\_get\_handler() (email.contentmanager.ContentManager method)](library/email.contentmanager#email.contentmanager.ContentManager.add_get_handler) * [add\_handler() (urllib.request.OpenerDirector method)](library/urllib.request#urllib.request.OpenerDirector.add_handler) * [add\_header() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.add_header) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.add_header) + [(urllib.request.Request method)](library/urllib.request#urllib.request.Request.add_header) + [(wsgiref.headers.Headers method)](library/wsgiref#wsgiref.headers.Headers.add_header) * [add\_history() (in module readline)](library/readline#readline.add_history) * [add\_hor\_rule() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.add_hor_rule) * [add\_include\_dir() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.add_include_dir) * [add\_label() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.add_label) * [add\_label\_data() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.add_label_data) * [add\_library() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.add_library) * [add\_library\_dir() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.add_library_dir) * [add\_line\_break() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.add_line_break) * [add\_link\_object() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.add_link_object) * [add\_literal\_data() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.add_literal_data) * [add\_mutually\_exclusive\_group() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.add_mutually_exclusive_group) * [add\_option() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.add_option) * [add\_parent() (urllib.request.BaseHandler method)](library/urllib.request#urllib.request.BaseHandler.add_parent) * [add\_password() (urllib.request.HTTPPasswordMgr method)](library/urllib.request#urllib.request.HTTPPasswordMgr.add_password) + [(urllib.request.HTTPPasswordMgrWithPriorAuth method)](library/urllib.request#urllib.request.HTTPPasswordMgrWithPriorAuth.add_password) * [add\_reader() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.add_reader) * [add\_related() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.add_related) * [add\_runtime\_library\_dir() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.add_runtime_library_dir) * [add\_section() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.add_section) + [(configparser.RawConfigParser method)](library/configparser#configparser.RawConfigParser.add_section) * [add\_sequence() (mailbox.MHMessage method)](library/mailbox#mailbox.MHMessage.add_sequence) * [add\_set\_handler() (email.contentmanager.ContentManager method)](library/email.contentmanager#email.contentmanager.ContentManager.add_set_handler) * [add\_signal\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.add_signal_handler) * [add\_stream() (in module msilib)](library/msilib#msilib.add_stream) * [add\_subparsers() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.add_subparsers) * [add\_tables() (in module msilib)](library/msilib#msilib.add_tables) * [add\_type() (in module mimetypes)](library/mimetypes#mimetypes.add_type) * [add\_unredirected\_header() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.add_unredirected_header) * [add\_writer() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.add_writer) * [addAsyncCleanup() (unittest.IsolatedAsyncioTestCase method)](library/unittest#unittest.IsolatedAsyncioTestCase.addAsyncCleanup) * [addaudithook() (in module sys)](library/sys#sys.addaudithook) * [addch() (curses.window method)](library/curses#curses.window.addch) * [addClassCleanup() (unittest.TestCase class method)](library/unittest#unittest.TestCase.addClassCleanup) * [addCleanup() (unittest.TestCase method)](library/unittest#unittest.TestCase.addCleanup) * [addcomponent() (turtle.Shape method)](library/turtle#turtle.Shape.addcomponent) * [addError() (unittest.TestResult method)](library/unittest#unittest.TestResult.addError) * [addExpectedFailure() (unittest.TestResult method)](library/unittest#unittest.TestResult.addExpectedFailure) * [addFailure() (unittest.TestResult method)](library/unittest#unittest.TestResult.addFailure) * [addfile() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.addfile) * [addFilter() (logging.Handler method)](library/logging#logging.Handler.addFilter) + [(logging.Logger method)](library/logging#logging.Logger.addFilter) * [addHandler() (logging.Logger method)](library/logging#logging.Logger.addHandler) * [addinfourl (class in urllib.response)](library/urllib.request#urllib.response.addinfourl) * [addition](reference/expressions#index-69) * [addLevelName() (in module logging)](library/logging#logging.addLevelName) * [addModuleCleanup() (in module unittest)](library/unittest#unittest.addModuleCleanup) * [addnstr() (curses.window method)](library/curses#curses.window.addnstr) * [AddPackagePath() (in module modulefinder)](library/modulefinder#modulefinder.AddPackagePath) * [addr (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.addr) * [addr\_spec (email.headerregistry.Address attribute)](library/email.headerregistry#email.headerregistry.Address.addr_spec) * [Address (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.Address) * [address (email.headerregistry.SingleAddressHeader attribute)](library/email.headerregistry#email.headerregistry.SingleAddressHeader.address) + [(multiprocessing.connection.Listener attribute)](library/multiprocessing#multiprocessing.connection.Listener.address) + [(multiprocessing.managers.BaseManager attribute)](library/multiprocessing#multiprocessing.managers.BaseManager.address) * [address\_exclude() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.address_exclude) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.address_exclude) * [address\_family (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.address_family) * [address\_string() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.address_string) * [addresses (email.headerregistry.AddressHeader attribute)](library/email.headerregistry#email.headerregistry.AddressHeader.addresses) + [(email.headerregistry.Group attribute)](library/email.headerregistry#email.headerregistry.Group.addresses) * [AddressHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.AddressHeader) * [addressof() (in module ctypes)](library/ctypes#ctypes.addressof) * [AddressValueError](library/ipaddress#ipaddress.AddressValueError) * [addshape() (in module turtle)](library/turtle#turtle.addshape) * [addsitedir() (in module site)](library/site#site.addsitedir) * [addSkip() (unittest.TestResult method)](library/unittest#unittest.TestResult.addSkip) * [addstr() (curses.window method)](library/curses#curses.window.addstr) * [addSubTest() (unittest.TestResult method)](library/unittest#unittest.TestResult.addSubTest) * [addSuccess() (unittest.TestResult method)](library/unittest#unittest.TestResult.addSuccess) * [addTest() (unittest.TestSuite method)](library/unittest#unittest.TestSuite.addTest) * [addTests() (unittest.TestSuite method)](library/unittest#unittest.TestSuite.addTests) * [addTypeEqualityFunc() (unittest.TestCase method)](library/unittest#unittest.TestCase.addTypeEqualityFunc) * [addUnexpectedSuccess() (unittest.TestResult method)](library/unittest#unittest.TestResult.addUnexpectedSuccess) * [adjust\_int\_max\_str\_digits() (in module test.support)](library/test#test.support.adjust_int_max_str_digits) * [adjusted() (decimal.Decimal method)](library/decimal#decimal.Decimal.adjusted) * [adler32() (in module zlib)](library/zlib#zlib.adler32) * [ADPCM, Intel/DVI](library/audioop#index-1) * [adpcm2lin() (in module audioop)](library/audioop#audioop.adpcm2lin) * [AF\_ALG (in module socket)](library/socket#socket.AF_ALG) * [AF\_CAN (in module socket)](library/socket#socket.AF_CAN) * [AF\_INET (in module socket)](library/socket#socket.AF_INET) * [AF\_INET6 (in module socket)](library/socket#socket.AF_INET6) * [AF\_LINK (in module socket)](library/socket#socket.AF_LINK) * [AF\_PACKET (in module socket)](library/socket#socket.AF_PACKET) * [AF\_QIPCRTR (in module socket)](library/socket#socket.AF_QIPCRTR) * [AF\_RDS (in module socket)](library/socket#socket.AF_RDS) * [AF\_UNIX (in module socket)](library/socket#socket.AF_UNIX) * [AF\_VSOCK (in module socket)](library/socket#socket.AF_VSOCK) * [aifc (module)](library/aifc#module-aifc) * [aifc() (aifc.aifc method)](library/aifc#aifc.aifc.aifc) * [AIFF](library/aifc#index-0), [[1]](library/chunk#index-0) * [aiff() (aifc.aifc method)](library/aifc#aifc.aifc.aiff) * [AIFF-C](library/aifc#index-0), [[1]](library/chunk#index-0) * [alarm() (in module signal)](library/signal#signal.alarm) * [alaw2lin() (in module audioop)](library/audioop#audioop.alaw2lin) * [ALERT\_DESCRIPTION\_HANDSHAKE\_FAILURE (in module ssl)](library/ssl#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE) * [ALERT\_DESCRIPTION\_INTERNAL\_ERROR (in module ssl)](library/ssl#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR) * [AlertDescription (class in ssl)](library/ssl#ssl.AlertDescription) * [algorithms\_available (in module hashlib)](library/hashlib#hashlib.algorithms_available) * [algorithms\_guaranteed (in module hashlib)](library/hashlib#hashlib.algorithms_guaranteed) * Alias + [Generic](library/stdtypes#index-53) * [alias (class in ast)](library/ast#ast.alias) + [(pdb command)](library/pdb#pdbcommand-alias) * [alignment() (in module ctypes)](library/ctypes#ctypes.alignment) * [alive (weakref.finalize attribute)](library/weakref#weakref.finalize.alive) * [all() (built-in function)](library/functions#all) * [all\_errors (in module ftplib)](library/ftplib#ftplib.all_errors) * [all\_features (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.all_features) * [all\_frames (tracemalloc.Filter attribute)](library/tracemalloc#tracemalloc.Filter.all_frames) * [all\_properties (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.all_properties) * [all\_suffixes() (in module importlib.machinery)](library/importlib#importlib.machinery.all_suffixes) * [all\_tasks() (in module asyncio)](library/asyncio-task#asyncio.all_tasks) * [allocate\_lock() (in module \_thread)](library/_thread#_thread.allocate_lock) * [allocfunc (C type)](c-api/typeobj#c.allocfunc) * [allow\_reuse\_address (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.allow_reuse_address) * [allowed\_domains() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.allowed_domains) * [alt() (in module curses.ascii)](library/curses.ascii#curses.ascii.alt) * [ALT\_DIGITS (in module locale)](library/locale#locale.ALT_DIGITS) * [altsep (in module os)](library/os#os.altsep) * [altzone (in module time)](library/time#time.altzone) * [ALWAYS\_EQ (in module test.support)](library/test#test.support.ALWAYS_EQ) * [ALWAYS\_TYPED\_ACTIONS (optparse.Option attribute)](library/optparse#optparse.Option.ALWAYS_TYPED_ACTIONS) * [AMPER (in module token)](library/token#token.AMPER) * [AMPEREQUAL (in module token)](library/token#token.AMPEREQUAL) * and + [bitwise](reference/expressions#index-74) + [operator](library/stdtypes#index-4), [[1]](library/stdtypes#index-6), [[2]](reference/expressions#index-84) * [And (class in ast)](library/ast#ast.And) * [and\_() (in module operator)](library/operator#operator.and_) * [AnnAssign (class in ast)](library/ast#ast.AnnAssign) * annotated + [assignment](reference/simple_stmts#index-15) * [Annotated (in module typing)](library/typing#typing.Annotated) * [**annotation**](glossary#term-annotation) + [(inspect.Parameter attribute)](library/inspect#inspect.Parameter.annotation) * annotations + [function](reference/compound_stmts#index-25), [[1]](tutorial/controlflow#index-5) * [announce() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.announce) * anonymous + [function](reference/expressions#index-89) * [answer\_challenge() (in module multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.answer_challenge) * [anticipate\_failure() (in module test.support)](library/test#test.support.anticipate_failure) * [Any (in module typing)](library/typing#typing.Any) * [ANY (in module unittest.mock)](library/unittest.mock#unittest.mock.ANY) * [any() (built-in function)](library/functions#any) * [AnyStr (in module typing)](library/typing#typing.AnyStr) * [api\_version (in module sys)](library/sys#sys.api_version) * [apilevel (in module sqlite3)](library/sqlite3#sqlite3.apilevel) * [apop() (poplib.POP3 method)](library/poplib#poplib.POP3.apop) * [APPDATA](https://docs.python.org/3.9/whatsnew/2.6.html#index-5) * [append() (array.array method)](library/array#array.array.append) + [(collections.deque method)](library/collections#collections.deque.append) + [(email.header.Header method)](library/email.header#email.header.Header.append) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.append) + [(msilib.CAB method)](library/msilib#msilib.CAB.append) + [(pipes.Template method)](library/pipes#pipes.Template.append) + [(sequence method)](library/stdtypes#index-22) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.append) * [append\_history\_file() (in module readline)](library/readline#readline.append_history_file) * [appendChild() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.appendChild) * [appendleft() (collections.deque method)](library/collections#collections.deque.appendleft) * [application\_uri() (in module wsgiref.util)](library/wsgiref#wsgiref.util.application_uri) * [apply (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-apply) * [apply() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.apply) * [apply\_async() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.apply_async) * [apply\_defaults() (inspect.BoundArguments method)](library/inspect#inspect.BoundArguments.apply_defaults) * [architecture() (in module platform)](library/platform#platform.architecture) * [archive (zipimport.zipimporter attribute)](library/zipimport#zipimport.zipimporter.archive) * [aRepr (in module reprlib)](library/reprlib#reprlib.aRepr) * [arg (class in ast)](library/ast#ast.arg) * [argparse (module)](library/argparse#module-argparse) * [args (BaseException attribute)](library/exceptions#BaseException.args) + [(functools.partial attribute)](library/functools#functools.partial.args) + [(inspect.BoundArguments attribute)](library/inspect#inspect.BoundArguments.args) + [(pdb command)](library/pdb#pdbcommand-args) + [(subprocess.CompletedProcess attribute)](library/subprocess#subprocess.CompletedProcess.args) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.args) * [args\_from\_interpreter\_flags() (in module test.support)](library/test#test.support.args_from_interpreter_flags) * [argtypes (ctypes.\_FuncPtr attribute)](library/ctypes#ctypes._FuncPtr.argtypes) * [**argument**](glossary#term-argument) + [call semantics](reference/expressions#index-47) + [difference from parameter](faq/programming#index-1) + [function](reference/datamodel#index-32) + [function definition](reference/compound_stmts#index-22) | * [ArgumentDefaultsHelpFormatter (class in argparse)](library/argparse#argparse.ArgumentDefaultsHelpFormatter) * [ArgumentError](library/ctypes#ctypes.ArgumentError) * [ArgumentParser (class in argparse)](library/argparse#argparse.ArgumentParser) * [arguments (class in ast)](library/ast#ast.arguments) + [(inspect.BoundArguments attribute)](library/inspect#inspect.BoundArguments.arguments) * [argv (in module sys)](c-api/init#index-30), [[1]](library/sys#sys.argv) * [arithmetic](library/stdtypes#index-13) + [conversion](reference/expressions#index-1) + [operation, binary](reference/expressions#index-64) + [operation, unary](reference/expressions#index-59) * [ArithmeticError](library/exceptions#ArithmeticError) * array + [module](library/stdtypes#index-38), [[1]](reference/datamodel#index-25) * [array (class in array)](library/array#array.array) * [Array (class in ctypes)](library/ctypes#ctypes.Array) * [array (module)](library/array#module-array) * [Array() (in module multiprocessing)](library/multiprocessing#multiprocessing.Array) + [(in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.Array) + [(multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Array) * [arrays](library/array#index-0) * [arraysize (sqlite3.Cursor attribute)](library/sqlite3#sqlite3.Cursor.arraysize) * [article() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.article) * as + [except clause](reference/compound_stmts#index-11) + [import statement](reference/simple_stmts#index-35) + [keyword](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-16), [[2]](reference/simple_stmts#index-34) + [with statement](reference/compound_stmts#index-16) * [as\_bytes() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.as_bytes) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.as_bytes) * [as\_completed() (in module asyncio)](library/asyncio-task#asyncio.as_completed) + [(in module concurrent.futures)](library/concurrent.futures#concurrent.futures.as_completed) * [as\_file() (in module importlib.resources)](library/importlib#importlib.resources.as_file) * [as\_integer\_ratio() (decimal.Decimal method)](library/decimal#decimal.Decimal.as_integer_ratio) + [(float method)](library/stdtypes#float.as_integer_ratio) + [(fractions.Fraction method)](library/fractions#fractions.Fraction.as_integer_ratio) + [(int method)](library/stdtypes#int.as_integer_ratio) * [AS\_IS (in module formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.AS_IS) * [as\_posix() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.as_posix) * [as\_string() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.as_string) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.as_string) * [as\_tuple() (decimal.Decimal method)](library/decimal#decimal.Decimal.as_tuple) * [as\_uri() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.as_uri) * [ASCII](reference/introduction#index-1), [[1]](reference/lexical_analysis#index-16) * ascii + [(in module re)](library/re#re.ASCII) + [built-in function](c-api/object#index-1) * [ascii() (built-in function)](library/functions#ascii) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.ascii) * [ascii\_letters (in module string)](library/string#string.ascii_letters) * [ascii\_lowercase (in module string)](library/string#string.ascii_lowercase) * [ascii\_uppercase (in module string)](library/string#string.ascii_uppercase) * [asctime() (in module time)](library/time#time.asctime) * [asdict() (in module dataclasses)](library/dataclasses#dataclasses.asdict) * [asend() (agen method)](reference/expressions#agen.asend) * [asin() (in module cmath)](library/cmath#cmath.asin) + [(in module math)](library/math#math.asin) * [asinh() (in module cmath)](library/cmath#cmath.asinh) + [(in module math)](library/math#math.asinh) * [askcolor() (in module tkinter.colorchooser)](library/tkinter.colorchooser#tkinter.colorchooser.askcolor) * [askdirectory() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.askdirectory) * [askfloat() (in module tkinter.simpledialog)](library/dialog#tkinter.simpledialog.askfloat) * [askinteger() (in module tkinter.simpledialog)](library/dialog#tkinter.simpledialog.askinteger) * [askokcancel() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.askokcancel) * [askopenfile() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.askopenfile) * [askopenfilename() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.askopenfilename) * [askopenfilenames() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.askopenfilenames) * [askopenfiles() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.askopenfiles) * [askquestion() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.askquestion) * [askretrycancel() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.askretrycancel) * [asksaveasfile() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.asksaveasfile) * [asksaveasfilename() (in module tkinter.filedialog)](library/dialog#tkinter.filedialog.asksaveasfilename) * [askstring() (in module tkinter.simpledialog)](library/dialog#tkinter.simpledialog.askstring) * [askyesno() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.askyesno) * [askyesnocancel() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.askyesnocancel) * assert + [statement](library/exceptions#index-2), [**[1]**](reference/simple_stmts#index-18) * [Assert (class in ast)](library/ast#ast.Assert) * [assert\_any\_await() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_any_await) * [assert\_any\_call() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_any_call) * [assert\_awaited() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_awaited) * [assert\_awaited\_once() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_awaited_once) * [assert\_awaited\_once\_with() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_awaited_once_with) * [assert\_awaited\_with() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_awaited_with) * [assert\_called() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_called) * [assert\_called\_once() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_called_once) * [assert\_called\_once\_with() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_called_once_with) * [assert\_called\_with() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_called_with) * [assert\_has\_awaits() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_has_awaits) * [assert\_has\_calls() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_has_calls) * [assert\_line\_data() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.assert_line_data) * [assert\_not\_awaited() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.assert_not_awaited) * [assert\_not\_called() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.assert_not_called) * [assert\_python\_failure() (in module test.support.script\_helper)](library/test#test.support.script_helper.assert_python_failure) * [assert\_python\_ok() (in module test.support.script\_helper)](library/test#test.support.script_helper.assert_python_ok) * [assertAlmostEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertAlmostEqual) * [assertCountEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertCountEqual) * [assertDictEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertDictEqual) * [assertEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertEqual) * [assertFalse() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertFalse) * [assertGreater() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertGreater) * [assertGreaterEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertGreaterEqual) * [assertIn() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIn) * [assertInBytecode() (test.support.bytecode\_helper.BytecodeTestCase method)](library/test#test.support.bytecode_helper.BytecodeTestCase.assertInBytecode) * [AssertionError](library/exceptions#AssertionError) + [exception](reference/simple_stmts#index-19) * assertions + [debugging](reference/simple_stmts#index-18) * [assertIs() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIs) * [assertIsInstance() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIsInstance) * [assertIsNone() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIsNone) * [assertIsNot() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIsNot) * [assertIsNotNone() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertIsNotNone) * [assertLess() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertLess) * [assertLessEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertLessEqual) * [assertListEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertListEqual) * [assertLogs() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertLogs) * [assertMultiLineEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertMultiLineEqual) * [assertNotAlmostEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertNotAlmostEqual) * [assertNotEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertNotEqual) * [assertNotIn() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertNotIn) * [assertNotInBytecode() (test.support.bytecode\_helper.BytecodeTestCase method)](library/test#test.support.bytecode_helper.BytecodeTestCase.assertNotInBytecode) * [assertNotIsInstance() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertNotIsInstance) * [assertNotRegex() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertNotRegex) * [assertRaises() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertRaises) * [assertRaisesRegex() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertRaisesRegex) * [assertRegex() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertRegex) * [asserts (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-asserts) * [assertSequenceEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertSequenceEqual) * [assertSetEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertSetEqual) * [assertTrue() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertTrue) * [assertTupleEqual() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertTupleEqual) * [assertWarns() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertWarns) * [assertWarnsRegex() (unittest.TestCase method)](library/unittest#unittest.TestCase.assertWarnsRegex) * [Assign (class in ast)](library/ast#ast.Assign) * assignment + [annotated](reference/simple_stmts#index-15) + [attribute](reference/simple_stmts#index-4), [[1]](reference/simple_stmts#index-8) + [augmented](reference/simple_stmts#index-14) + [class attribute](reference/datamodel#index-46) + [class instance attribute](reference/datamodel#index-50) + [slice](library/stdtypes#index-22) + [slicing](reference/simple_stmts#index-12) + [statement](reference/datamodel#index-22), [[1]](reference/simple_stmts#index-4) + [subscript](library/stdtypes#index-22) + [subscription](reference/simple_stmts#index-9) + [target list](reference/simple_stmts#index-6) * [AST (class in ast)](library/ast#ast.AST) * [ast (module)](library/ast#module-ast) * ast command line option + [--help](library/ast#cmdoption-ast-h) + [--include-attributes](library/ast#cmdoption-ast-a) + [--indent <indent>](library/ast#cmdoption-ast-indent) + [--mode <mode>](library/ast#cmdoption-ast-mode) + [--no-type-comments](library/ast#cmdoption-ast-no-type-comments) + [-a](library/ast#cmdoption-ast-a) + [-h](library/ast#cmdoption-ast-h) + [-i <indent>](library/ast#cmdoption-ast-i) + [-m <mode>](library/ast#cmdoption-ast-m) * [astimezone() (datetime.datetime method)](library/datetime#datetime.datetime.astimezone) * [astuple() (in module dataclasses)](library/dataclasses#dataclasses.astuple) * async + [keyword](reference/compound_stmts#index-38) * [ASYNC (in module token)](library/token#token.ASYNC) * async def + [statement](reference/compound_stmts#index-37) * async for + [in comprehensions](reference/expressions#index-12) + [statement](reference/compound_stmts#index-39) * async with + [statement](reference/compound_stmts#index-40) * [async\_chat (class in asynchat)](library/asynchat#asynchat.async_chat) * [async\_chat.ac\_in\_buffer\_size (in module asynchat)](library/asynchat#asynchat.async_chat.ac_in_buffer_size) * [async\_chat.ac\_out\_buffer\_size (in module asynchat)](library/asynchat#asynchat.async_chat.ac_out_buffer_size) * [AsyncContextManager (class in typing)](library/typing#typing.AsyncContextManager) * [asynccontextmanager() (in module contextlib)](library/contextlib#contextlib.asynccontextmanager) * [AsyncExitStack (class in contextlib)](library/contextlib#contextlib.AsyncExitStack) * [AsyncFor (class in ast)](library/ast#ast.AsyncFor) * [AsyncFunctionDef (class in ast)](library/ast#ast.AsyncFunctionDef) * [AsyncGenerator (class in collections.abc)](library/collections.abc#collections.abc.AsyncGenerator) + [(class in typing)](library/typing#typing.AsyncGenerator) * [AsyncGeneratorType (in module types)](library/types#types.AsyncGeneratorType) * [asynchat (module)](library/asynchat#module-asynchat) * [**asynchronous context manager**](glossary#term-asynchronous-context-manager) * [**asynchronous generator**](glossary#term-asynchronous-generator) + [asynchronous iterator](reference/datamodel#index-39) + [function](reference/datamodel#index-39) * [**asynchronous generator iterator**](glossary#term-asynchronous-generator-iterator) * [**asynchronous iterable**](glossary#term-asynchronous-iterable) * [**asynchronous iterator**](glossary#term-asynchronous-iterator) * asynchronous-generator + [object](reference/expressions#index-35) * [asyncio (module)](library/asyncio#module-asyncio) * [asyncio.subprocess.DEVNULL (built-in variable)](library/asyncio-subprocess#asyncio.subprocess.DEVNULL) * [asyncio.subprocess.PIPE (built-in variable)](library/asyncio-subprocess#asyncio.subprocess.PIPE) * [asyncio.subprocess.Process (built-in class)](library/asyncio-subprocess#asyncio.subprocess.Process) * [asyncio.subprocess.STDOUT (built-in variable)](library/asyncio-subprocess#asyncio.subprocess.STDOUT) * [AsyncIterable (class in collections.abc)](library/collections.abc#collections.abc.AsyncIterable) + [(class in typing)](library/typing#typing.AsyncIterable) * [AsyncIterator (class in collections.abc)](library/collections.abc#collections.abc.AsyncIterator) + [(class in typing)](library/typing#typing.AsyncIterator) * [AsyncMock (class in unittest.mock)](library/unittest.mock#unittest.mock.AsyncMock) * [asyncore (module)](library/asyncore#module-asyncore) * [AsyncResult (class in multiprocessing.pool)](library/multiprocessing#multiprocessing.pool.AsyncResult) * [asyncSetUp() (unittest.IsolatedAsyncioTestCase method)](library/unittest#unittest.IsolatedAsyncioTestCase.asyncSetUp) * [asyncTearDown() (unittest.IsolatedAsyncioTestCase method)](library/unittest#unittest.IsolatedAsyncioTestCase.asyncTearDown) * [AsyncWith (class in ast)](library/ast#ast.AsyncWith) * [AT (in module token)](library/token#token.AT) * [at\_eof() (asyncio.StreamReader method)](library/asyncio-stream#asyncio.StreamReader.at_eof) * [atan() (in module cmath)](library/cmath#cmath.atan) + [(in module math)](library/math#math.atan) * [atan2() (in module math)](library/math#math.atan2) * [atanh() (in module cmath)](library/cmath#cmath.atanh) + [(in module math)](library/math#math.atanh) * [ATEQUAL (in module token)](library/token#token.ATEQUAL) * [atexit (module)](library/atexit#module-atexit) + [(weakref.finalize attribute)](library/weakref#weakref.finalize.atexit) * [athrow() (agen method)](reference/expressions#agen.athrow) * [atof() (in module locale)](library/locale#locale.atof) * [atoi() (in module locale)](library/locale#locale.atoi) * [atom](reference/expressions#index-2) * [attach() (email.message.Message method)](library/email.compat32-message#email.message.Message.attach) * [attach\_loop() (asyncio.AbstractChildWatcher method)](library/asyncio-policy#asyncio.AbstractChildWatcher.attach_loop) * [attach\_mock() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.attach_mock) * [AttlistDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.AttlistDeclHandler) * [attrgetter() (in module operator)](library/operator#operator.attrgetter) * [attrib (xml.etree.ElementTree.Element attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.attrib) * [attribute](reference/datamodel#index-5), [**[1]**](glossary#term-attribute) + [assignment](reference/simple_stmts#index-4), [[1]](reference/simple_stmts#index-8) + [assignment, class](reference/datamodel#index-46) + [assignment, class instance](reference/datamodel#index-50) + [class](reference/datamodel#index-45) + [class instance](reference/datamodel#index-49) + [deletion](reference/simple_stmts#index-23) + [generic special](reference/datamodel#index-5) + [reference](reference/expressions#index-39) + [special](reference/datamodel#index-5) * [Attribute (class in ast)](library/ast#ast.Attribute) * [AttributeError](library/exceptions#AttributeError) + [exception](reference/expressions#index-40) * [attributes (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.attributes) * [AttributesImpl (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.AttributesImpl) * [AttributesNSImpl (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.AttributesNSImpl) * [attroff() (curses.window method)](library/curses#curses.window.attroff) * [attron() (curses.window method)](library/curses#curses.window.attron) * [attrset() (curses.window method)](library/curses#curses.window.attrset) * [Audio Interchange File Format](library/aifc#index-0), [[1]](library/chunk#index-0) * [AUDIO\_FILE\_ENCODING\_ADPCM\_G721 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G721) * [AUDIO\_FILE\_ENCODING\_ADPCM\_G722 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G722) * [AUDIO\_FILE\_ENCODING\_ADPCM\_G723\_3 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3) * [AUDIO\_FILE\_ENCODING\_ADPCM\_G723\_5 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5) * [AUDIO\_FILE\_ENCODING\_ALAW\_8 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_ALAW_8) * [AUDIO\_FILE\_ENCODING\_DOUBLE (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_DOUBLE) * [AUDIO\_FILE\_ENCODING\_FLOAT (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_FLOAT) * [AUDIO\_FILE\_ENCODING\_LINEAR\_16 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_16) * [AUDIO\_FILE\_ENCODING\_LINEAR\_24 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_24) * [AUDIO\_FILE\_ENCODING\_LINEAR\_32 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_32) * [AUDIO\_FILE\_ENCODING\_LINEAR\_8 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_8) * [AUDIO\_FILE\_ENCODING\_MULAW\_8 (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_ENCODING_MULAW_8) * [AUDIO\_FILE\_MAGIC (in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.AUDIO_FILE_MAGIC) * [AUDIODEV](library/ossaudiodev#index-1) * [audioop (module)](library/audioop#module-audioop) * [audit events](library/audit_events#index-0) * [audit() (in module sys)](library/sys#sys.audit) * [auditing](library/sys#index-2) * [AugAssign (class in ast)](library/ast#ast.AugAssign) * augmented + [assignment](reference/simple_stmts#index-14) * [auth() (ftplib.FTP\_TLS method)](library/ftplib#ftplib.FTP_TLS.auth) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.auth) * [authenticate() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.authenticate) * [AuthenticationError](library/multiprocessing#multiprocessing.AuthenticationError) * [authenticators() (netrc.netrc method)](library/netrc#netrc.netrc.authenticators) * [authkey (multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.authkey) * [auto (class in enum)](library/enum#enum.auto) * [autorange() (timeit.Timer method)](library/timeit#timeit.Timer.autorange) * [available\_timezones() (in module zoneinfo)](library/zoneinfo#zoneinfo.available_timezones) * [avg() (in module audioop)](library/audioop#audioop.avg) * [avgpp() (in module audioop)](library/audioop#audioop.avgpp) * [avoids\_symlink\_attacks (shutil.rmtree attribute)](library/shutil#shutil.rmtree.avoids_symlink_attacks) * await + [in comprehensions](reference/expressions#index-13) + [keyword](reference/compound_stmts#index-38), [[1]](reference/expressions#index-57) * [Await (class in ast)](library/ast#ast.Await) * [AWAIT (in module token)](library/token#token.AWAIT) * [await\_args (unittest.mock.AsyncMock attribute)](library/unittest.mock#unittest.mock.AsyncMock.await_args) * [await\_args\_list (unittest.mock.AsyncMock attribute)](library/unittest.mock#unittest.mock.AsyncMock.await_args_list) * [await\_count (unittest.mock.AsyncMock attribute)](library/unittest.mock#unittest.mock.AsyncMock.await_count) * [**awaitable**](glossary#term-awaitable) * [Awaitable (class in collections.abc)](library/collections.abc#collections.abc.Awaitable) + [(class in typing)](library/typing#typing.Awaitable) | B - | | | | --- | --- | | * b" + [bytes literal](reference/lexical_analysis#index-18) * b' + [bytes literal](reference/lexical_analysis#index-18) * [b16decode() (in module base64)](library/base64#base64.b16decode) * [b16encode() (in module base64)](library/base64#base64.b16encode) * [b2a\_base64() (in module binascii)](library/binascii#binascii.b2a_base64) * [b2a\_hex() (in module binascii)](library/binascii#binascii.b2a_hex) * [b2a\_hqx() (in module binascii)](library/binascii#binascii.b2a_hqx) * [b2a\_qp() (in module binascii)](library/binascii#binascii.b2a_qp) * [b2a\_uu() (in module binascii)](library/binascii#binascii.b2a_uu) * [b32decode() (in module base64)](library/base64#base64.b32decode) * [b32encode() (in module base64)](library/base64#base64.b32encode) * [b64decode() (in module base64)](library/base64#base64.b64decode) * [b64encode() (in module base64)](library/base64#base64.b64encode) * [b85decode() (in module base64)](library/base64#base64.b85decode) * [b85encode() (in module base64)](library/base64#base64.b85encode) * [Babyl (class in mailbox)](library/mailbox#mailbox.Babyl) * [BabylMessage (class in mailbox)](library/mailbox#mailbox.BabylMessage) * [back() (in module turtle)](library/turtle#turtle.back) * [backslash character](reference/lexical_analysis#index-6) * backslashreplace + [error handler's name](library/codecs#index-1) * [backslashreplace\_errors() (in module codecs)](library/codecs#codecs.backslashreplace_errors) * [backup() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.backup) * [backward() (in module turtle)](library/turtle#turtle.backward) * [BadGzipFile](library/gzip#gzip.BadGzipFile) * [BadStatusLine](library/http.client#http.client.BadStatusLine) * [BadZipFile](library/zipfile#zipfile.BadZipFile) * [BadZipfile](library/zipfile#zipfile.BadZipfile) * [Balloon (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Balloon) * [Barrier (class in multiprocessing)](library/multiprocessing#multiprocessing.Barrier) + [(class in threading)](library/threading#threading.Barrier) * [Barrier() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Barrier) * base64 + [encoding](library/base64#index-0) + [module](library/binascii#index-0) * [base64 (module)](library/base64#module-base64) * [base\_exec\_prefix (in module sys)](library/sys#sys.base_exec_prefix) * [base\_prefix (in module sys)](library/sys#sys.base_prefix) * [BaseCGIHandler (class in wsgiref.handlers)](library/wsgiref#wsgiref.handlers.BaseCGIHandler) * [BaseCookie (class in http.cookies)](library/http.cookies#http.cookies.BaseCookie) * [BaseException](library/exceptions#BaseException) * [BaseHandler (class in urllib.request)](library/urllib.request#urllib.request.BaseHandler) + [(class in wsgiref.handlers)](library/wsgiref#wsgiref.handlers.BaseHandler) * [BaseHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.BaseHeader) * [BaseHTTPRequestHandler (class in http.server)](library/http.server#http.server.BaseHTTPRequestHandler) * [BaseManager (class in multiprocessing.managers)](library/multiprocessing#multiprocessing.managers.BaseManager) * [basename() (in module os.path)](library/os.path#os.path.basename) * [BaseProtocol (class in asyncio)](library/asyncio-protocol#asyncio.BaseProtocol) * [BaseProxy (class in multiprocessing.managers)](library/multiprocessing#multiprocessing.managers.BaseProxy) * [BaseRequestHandler (class in socketserver)](library/socketserver#socketserver.BaseRequestHandler) * [BaseRotatingHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.BaseRotatingHandler) * [BaseSelector (class in selectors)](library/selectors#selectors.BaseSelector) * [BaseServer (class in socketserver)](library/socketserver#socketserver.BaseServer) * [basestring (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-basestring) * [BaseTransport (class in asyncio)](library/asyncio-protocol#asyncio.BaseTransport) * [basicConfig() (in module logging)](library/logging#logging.basicConfig) * [BasicContext (class in decimal)](library/decimal#decimal.BasicContext) * [BasicInterpolation (class in configparser)](library/configparser#configparser.BasicInterpolation) * [BasicTestRunner (class in test.support)](library/test#test.support.BasicTestRunner) * [baudrate() (in module curses)](library/curses#curses.baudrate) * [bbox() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.bbox) * [BDADDR\_ANY (in module socket)](library/socket#socket.BDADDR_ANY) * [BDADDR\_LOCAL (in module socket)](library/socket#socket.BDADDR_LOCAL) * bdb + [module](library/pdb#index-1) * [Bdb (class in bdb)](library/bdb#bdb.Bdb) * [bdb (module)](library/bdb#module-bdb) * [BdbQuit](library/bdb#bdb.BdbQuit) * [**BDFL**](glossary#term-bdfl) * [bdist\_msi (class in distutils.command.bdist\_msi)](distutils/apiref#distutils.command.bdist_msi.bdist_msi) * [beep() (in module curses)](library/curses#curses.beep) * [Beep() (in module winsound)](library/winsound#winsound.Beep) * [BEFORE\_ASYNC\_WITH (opcode)](library/dis#opcode-BEFORE_ASYNC_WITH) * [begin\_fill() (in module turtle)](library/turtle#turtle.begin_fill) * [begin\_poly() (in module turtle)](library/turtle#turtle.begin_poly) * [below() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.below) * [BELOW\_NORMAL\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.BELOW_NORMAL_PRIORITY_CLASS) * [Benchmarking](library/timeit#index-0) * [benchmarking](library/time#index-12), [[1]](library/time#index-6), [[2]](library/time#index-7) * [betavariate() (in module random)](library/random#random.betavariate) * [bgcolor() (in module turtle)](library/turtle#turtle.bgcolor) * [bgpic() (in module turtle)](library/turtle#turtle.bgpic) * [bias() (in module audioop)](library/audioop#audioop.bias) * [bidirectional() (in module unicodedata)](library/unicodedata#unicodedata.bidirectional) * [bigaddrspacetest() (in module test.support)](library/test#test.support.bigaddrspacetest) * [BigEndianStructure (class in ctypes)](library/ctypes#ctypes.BigEndianStructure) * [bigmemtest() (in module test.support)](library/test#test.support.bigmemtest) * [bin() (built-in function)](library/functions#bin) * binary + [arithmetic operation](reference/expressions#index-64) + [bitwise operation](reference/expressions#index-73) + [data, packing](library/struct#index-0) + [literals](library/stdtypes#index-12) * [Binary (class in msilib)](library/msilib#msilib.Binary) + [(class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.Binary) * [**binary file**](glossary#term-binary-file) * [binary literal](reference/lexical_analysis#index-26) * [binary mode](library/functions#index-7) * [binary semaphores](library/_thread#index-0) * [BINARY\_ADD (opcode)](library/dis#opcode-BINARY_ADD) * [BINARY\_AND (opcode)](library/dis#opcode-BINARY_AND) * [BINARY\_FLOOR\_DIVIDE (opcode)](library/dis#opcode-BINARY_FLOOR_DIVIDE) * [BINARY\_LSHIFT (opcode)](library/dis#opcode-BINARY_LSHIFT) * [BINARY\_MATRIX\_MULTIPLY (opcode)](library/dis#opcode-BINARY_MATRIX_MULTIPLY) * [BINARY\_MODULO (opcode)](library/dis#opcode-BINARY_MODULO) * [BINARY\_MULTIPLY (opcode)](library/dis#opcode-BINARY_MULTIPLY) * [BINARY\_OR (opcode)](library/dis#opcode-BINARY_OR) * [BINARY\_POWER (opcode)](library/dis#opcode-BINARY_POWER) * [BINARY\_RSHIFT (opcode)](library/dis#opcode-BINARY_RSHIFT) * [BINARY\_SUBSCR (opcode)](library/dis#opcode-BINARY_SUBSCR) * [BINARY\_SUBTRACT (opcode)](library/dis#opcode-BINARY_SUBTRACT) * [BINARY\_TRUE\_DIVIDE (opcode)](library/dis#opcode-BINARY_TRUE_DIVIDE) * [BINARY\_XOR (opcode)](library/dis#opcode-BINARY_XOR) * [binaryfunc (C type)](c-api/typeobj#c.binaryfunc) * [BinaryIO (class in typing)](library/typing#typing.BinaryIO) * [binascii (module)](library/binascii#module-binascii) * [bind (widgets)](library/tkinter#index-6) * [bind() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.bind) + [(inspect.Signature method)](library/inspect#inspect.Signature.bind) + [(socket.socket method)](library/socket#socket.socket.bind) * [bind\_partial() (inspect.Signature method)](library/inspect#inspect.Signature.bind_partial) * [bind\_port() (in module test.support.socket\_helper)](library/test#test.support.socket_helper.bind_port) * [bind\_textdomain\_codeset() (in module gettext)](library/gettext#gettext.bind_textdomain_codeset) * [bind\_unix\_socket() (in module test.support.socket\_helper)](library/test#test.support.socket_helper.bind_unix_socket) * binding + [global name](reference/simple_stmts#index-43) + [name](reference/compound_stmts#index-19), [[1]](reference/compound_stmts#index-19), [[2]](reference/compound_stmts#index-31), [[3]](reference/executionmodel#index-4), [[4]](reference/simple_stmts#index-34), [[5]](reference/simple_stmts#index-36), [[6]](reference/simple_stmts#index-4) * [bindtextdomain() (in module gettext)](library/gettext#gettext.bindtextdomain) + [(in module locale)](library/locale#locale.bindtextdomain) * binhex + [module](library/binascii#index-0) * [binhex (module)](library/binhex#module-binhex) * [binhex() (in module binhex)](library/binhex#binhex.binhex) * [BinOp (class in ast)](library/ast#ast.BinOp) * [bisect (module)](library/bisect#module-bisect) * [bisect() (in module bisect)](library/bisect#bisect.bisect) * [bisect\_left() (in module bisect)](library/bisect#bisect.bisect_left) * [bisect\_right() (in module bisect)](library/bisect#bisect.bisect_right) * [bit\_length() (int method)](library/stdtypes#int.bit_length) * [BitAnd (class in ast)](library/ast#ast.BitAnd) * [bitmap() (msilib.Dialog method)](library/msilib#msilib.Dialog.bitmap) * [BitOr (class in ast)](library/ast#ast.BitOr) * bitwise + [and](reference/expressions#index-74) + [operation, binary](reference/expressions#index-73) + [operation, unary](reference/expressions#index-59) + [operations](library/stdtypes#index-16) + [or](reference/expressions#index-76) + [xor](reference/expressions#index-75) * [BitXor (class in ast)](library/ast#ast.BitXor) * [bk() (in module turtle)](library/turtle#turtle.bk) * [bkgd() (curses.window method)](library/curses#curses.window.bkgd) * [bkgdset() (curses.window method)](library/curses#curses.window.bkgdset) * [blake2b() (in module hashlib)](library/hashlib#hashlib.blake2b) * [blake2b, blake2s](library/hashlib#index-4) * [blake2b.MAX\_DIGEST\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2b.MAX_DIGEST_SIZE) * [blake2b.MAX\_KEY\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2b.MAX_KEY_SIZE) * [blake2b.PERSON\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2b.PERSON_SIZE) * [blake2b.SALT\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2b.SALT_SIZE) * [blake2s() (in module hashlib)](library/hashlib#hashlib.blake2s) * [blake2s.MAX\_DIGEST\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2s.MAX_DIGEST_SIZE) * [blake2s.MAX\_KEY\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2s.MAX_KEY_SIZE) * [blake2s.PERSON\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2s.PERSON_SIZE) * [blake2s.SALT\_SIZE (in module hashlib)](library/hashlib#hashlib.blake2s.SALT_SIZE) * [blank line](reference/lexical_analysis#index-7) * [block](reference/executionmodel#index-1) + [code](reference/executionmodel#index-0) * [block\_size (hmac.HMAC attribute)](library/hmac#hmac.HMAC.block_size) * [blocked\_domains() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.blocked_domains) * [BlockingIOError](library/exceptions#BlockingIOError), [[1]](library/io#io.BlockingIOError) * [blocksize (http.client.HTTPConnection attribute)](library/http.client#http.client.HTTPConnection.blocksize) * [BNF](reference/expressions#index-0), [[1]](reference/introduction#index-0) * [body() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.body) + [(tkinter.simpledialog.Dialog method)](library/dialog#tkinter.simpledialog.Dialog.body) * [body\_encode() (email.charset.Charset method)](library/email.charset#email.charset.Charset.body_encode) * [body\_encoding (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.body_encoding) * [body\_line\_iterator() (in module email.iterators)](library/email.iterators#email.iterators.body_line_iterator) * [BOLD (in module tkinter.font)](library/tkinter.font#tkinter.font.BOLD) * [BOM (in module codecs)](library/codecs#codecs.BOM) * [BOM\_BE (in module codecs)](library/codecs#codecs.BOM_BE) | * [BOM\_LE (in module codecs)](library/codecs#codecs.BOM_LE) * [BOM\_UTF16 (in module codecs)](library/codecs#codecs.BOM_UTF16) * [BOM\_UTF16\_BE (in module codecs)](library/codecs#codecs.BOM_UTF16_BE) * [BOM\_UTF16\_LE (in module codecs)](library/codecs#codecs.BOM_UTF16_LE) * [BOM\_UTF32 (in module codecs)](library/codecs#codecs.BOM_UTF32) * [BOM\_UTF32\_BE (in module codecs)](library/codecs#codecs.BOM_UTF32_BE) * [BOM\_UTF32\_LE (in module codecs)](library/codecs#codecs.BOM_UTF32_LE) * [BOM\_UTF8 (in module codecs)](library/codecs#codecs.BOM_UTF8) * [bool (built-in class)](library/functions#bool) * Boolean + [object](library/stdtypes#index-11), [[1]](reference/datamodel#index-11) + [operation](reference/expressions#index-82) + [operations](library/stdtypes#index-1), [[1]](library/stdtypes#index-5) + [type](library/functions#index-0) + [values](library/stdtypes#index-62) * [BOOLEAN\_STATES (configparser.ConfigParser attribute)](library/configparser#configparser.ConfigParser.BOOLEAN_STATES) * [BoolOp (class in ast)](library/ast#ast.BoolOp) * [bootstrap() (in module ensurepip)](library/ensurepip#ensurepip.bootstrap) * [border() (curses.window method)](library/curses#curses.window.border) * [bottom() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.bottom) * [bottom\_panel() (in module curses.panel)](library/curses.panel#curses.panel.bottom_panel) * [BoundArguments (class in inspect)](library/inspect#inspect.BoundArguments) * [BoundaryError](library/email.errors#email.errors.BoundaryError) * [BoundedSemaphore (class in asyncio)](library/asyncio-sync#asyncio.BoundedSemaphore) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.BoundedSemaphore) + [(class in threading)](library/threading#threading.BoundedSemaphore) * [BoundedSemaphore() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.BoundedSemaphore) * [box() (curses.window method)](library/curses#curses.window.box) * [bpformat() (bdb.Breakpoint method)](library/bdb#bdb.Breakpoint.bpformat) * [bpprint() (bdb.Breakpoint method)](library/bdb#bdb.Breakpoint.bpprint) * break + [statement](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [[2]](reference/compound_stmts#index-5), [[3]](reference/compound_stmts#index-7), [**[4]**](reference/simple_stmts#index-30) * [Break (class in ast)](library/ast#ast.Break) * [break (pdb command)](library/pdb#pdbcommand-break) * [break\_anywhere() (bdb.Bdb method)](library/bdb#bdb.Bdb.break_anywhere) * [break\_here() (bdb.Bdb method)](library/bdb#bdb.Bdb.break_here) * [break\_long\_words (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.break_long_words) * [break\_on\_hyphens (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.break_on_hyphens) * [Breakpoint (class in bdb)](library/bdb#bdb.Breakpoint) * [breakpoint() (built-in function)](library/functions#breakpoint) * [breakpointhook() (in module sys)](library/sys#sys.breakpointhook) * [breakpoints](library/idle#index-4) * [broadcast\_address (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.broadcast_address) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.broadcast_address) * [broken (threading.Barrier attribute)](library/threading#threading.Barrier.broken) * [BrokenBarrierError](library/threading#threading.BrokenBarrierError) * [BrokenExecutor](library/concurrent.futures#concurrent.futures.BrokenExecutor) * [BrokenPipeError](library/exceptions#BrokenPipeError) * [BrokenProcessPool](library/concurrent.futures#concurrent.futures.process.BrokenProcessPool) * [BrokenThreadPool](library/concurrent.futures#concurrent.futures.thread.BrokenThreadPool) * [BROWSER](library/webbrowser#index-0), [[1]](library/webbrowser#index-1) * [BsdDbShelf (class in shelve)](library/shelve#shelve.BsdDbShelf) * [buf (multiprocessing.shared\_memory.SharedMemory attribute)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory.buf) * [buffer (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-buffer) + [(io.TextIOBase attribute)](library/io#io.TextIOBase.buffer) + [(unittest.TestResult attribute)](library/unittest#unittest.TestResult.buffer) * buffer interface + [(see buffer protocol)](c-api/buffer#index-0) * buffer object + [(see buffer protocol)](c-api/buffer#index-0) * [buffer protocol](c-api/buffer#index-0) + [binary sequence types](library/stdtypes#index-37) + [str (built-in class)](library/stdtypes#index-29) * [buffer size, I/O](library/functions#index-7) * [buffer\_info() (array.array method)](library/array#array.array.buffer_info) * [buffer\_size (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.buffer_size) * [buffer\_text (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.buffer_text) * [buffer\_updated() (asyncio.BufferedProtocol method)](library/asyncio-protocol#asyncio.BufferedProtocol.buffer_updated) * [buffer\_used (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.buffer_used) * [BufferedIOBase (class in io)](library/io#io.BufferedIOBase) * [BufferedProtocol (class in asyncio)](library/asyncio-protocol#asyncio.BufferedProtocol) * [BufferedRandom (class in io)](library/io#io.BufferedRandom) * [BufferedReader (class in io)](library/io#io.BufferedReader) * [BufferedRWPair (class in io)](library/io#io.BufferedRWPair) * [BufferedWriter (class in io)](library/io#io.BufferedWriter) * [BufferError](library/exceptions#BufferError) * [BufferingHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.BufferingHandler) * [BufferTooShort](library/multiprocessing#multiprocessing.BufferTooShort) * [bufsize() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.bufsize) * [BUILD\_CONST\_KEY\_MAP (opcode)](library/dis#opcode-BUILD_CONST_KEY_MAP) * [BUILD\_LIST (opcode)](library/dis#opcode-BUILD_LIST) * [BUILD\_MAP (opcode)](library/dis#opcode-BUILD_MAP) * [build\_opener() (in module urllib.request)](library/urllib.request#urllib.request.build_opener) * [build\_py (class in distutils.command.build\_py)](distutils/apiref#distutils.command.build_py.build_py) * [build\_py\_2to3 (class in distutils.command.build\_py)](distutils/apiref#distutils.command.build_py.build_py_2to3) * [BUILD\_SET (opcode)](library/dis#opcode-BUILD_SET) * [BUILD\_SLICE (opcode)](library/dis#opcode-BUILD_SLICE) * [BUILD\_STRING (opcode)](library/dis#opcode-BUILD_STRING) * [BUILD\_TUPLE (opcode)](library/dis#opcode-BUILD_TUPLE) * built-in + [method](reference/datamodel#index-41) + [types](library/stdtypes#index-0) * built-in function + [\_\_import\_\_](c-api/import#index-1) + [abs](c-api/number#index-2), [[1]](reference/datamodel#index-99) + [ascii](c-api/object#index-1) + [bytes](c-api/object#index-3), [[1]](reference/datamodel#index-73) + [call](reference/expressions#index-53) + [chr](reference/datamodel#index-19) + [classmethod](c-api/structures#index-0) + [compile](c-api/import#index-2), [[1]](library/parser#index-2), [[2]](library/stdtypes#index-58), [[3]](library/types#index-3), [[4]](reference/simple_stmts#index-44) + [complex](library/stdtypes#index-13), [[1]](reference/datamodel#index-100) + [divmod](c-api/number#index-0), [[1]](reference/datamodel#index-96), [[2]](reference/datamodel#index-97) + [eval](library/parser#index-1), [[1]](library/pprint#index-1), [[2]](library/pprint#index-2), [[3]](library/stdtypes#index-59), [[4]](reference/simple_stmts#index-44), [[5]](reference/toplevel_components#index-6) + [exec](library/functions#index-1), [[1]](library/parser#index-1), [[2]](library/stdtypes#index-59), [[3]](reference/simple_stmts#index-44) + [float](c-api/number#index-5), [[1]](library/stdtypes#index-13), [[2]](reference/datamodel#index-100) + [hash](c-api/object#index-6), [[1]](c-api/typeobj#index-2), [[2]](library/stdtypes#index-20), [[3]](reference/datamodel#index-76) + [help](tutorial/stdlib#index-0) + [id](reference/datamodel#index-1) + [int](c-api/number#index-4), [[1]](library/stdtypes#index-13), [[2]](reference/datamodel#index-100) + [len](c-api/dict#index-2), [[1]](c-api/list#index-1), [[2]](c-api/mapping#index-0), [[3]](c-api/object#index-8), [[4]](c-api/sequence#index-0), [[5]](c-api/set#index-1), [[6]](library/stdtypes#index-19), [[7]](library/stdtypes#index-50), [[8]](reference/datamodel#index-15), [[9]](reference/datamodel#index-26), [[10]](reference/datamodel#index-29), [[11]](reference/datamodel#index-94) + [max](library/stdtypes#index-19) + [min](library/stdtypes#index-19) + [object](reference/datamodel#index-40), [[1]](reference/expressions#index-53) + [open](reference/datamodel#index-53), [[1]](tutorial/inputoutput#index-0) + [ord](reference/datamodel#index-19) + [pow](c-api/number#index-1), [[1]](c-api/number#index-3), [[2]](reference/datamodel#index-96), [[3]](reference/datamodel#index-96), [[4]](reference/datamodel#index-97), [[5]](reference/datamodel#index-98) + [print](reference/datamodel#index-74) + [range](reference/compound_stmts#index-8) + [repr](c-api/object#index-0), [[1]](c-api/typeobj#index-1), [[2]](extending/newtypes#index-3), [[3]](reference/simple_stmts#index-3) + [round](reference/datamodel#index-101) + [slice](library/dis#index-0), [[1]](reference/datamodel#index-65) + [staticmethod](c-api/structures#index-1) + [tuple](c-api/list#index-2), [[1]](c-api/sequence#index-1) + [type](c-api/object#index-7), [[1]](library/stdtypes#index-60), [[2]](reference/datamodel#index-1), [[3]](reference/datamodel#index-82) * built-in method + [call](reference/expressions#index-53) + [object](reference/datamodel#index-41), [[1]](reference/expressions#index-53) * [builtin\_module\_names (in module sys)](library/sys#sys.builtin_module_names) * [BuiltinFunctionType (in module types)](library/types#types.BuiltinFunctionType) * [BuiltinImporter (class in importlib.machinery)](library/importlib#importlib.machinery.BuiltinImporter) * [BuiltinMethodType (in module types)](library/types#types.BuiltinMethodType) * builtins + [module](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](reference/toplevel_components#index-2), [[4]](tutorial/modules#index-7) * [builtins (module)](library/builtins#module-builtins) * [ButtonBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.ButtonBox) * [buttonbox() (tkinter.simpledialog.Dialog method)](library/dialog#tkinter.simpledialog.Dialog.buttonbox) * [bye() (in module turtle)](library/turtle#turtle.bye) * [byref() (in module ctypes)](library/ctypes#ctypes.byref) * [byte](reference/datamodel#index-21) * byte-code + [file](library/imp#index-1), [[1]](library/py_compile#index-0) * [byte\_compile() (in module distutils.util)](distutils/apiref#distutils.util.byte_compile) * [bytearray](reference/datamodel#index-24) + [formatting](library/stdtypes#index-43) + [interpolation](library/stdtypes#index-43) + [methods](library/stdtypes#index-41) + [object](c-api/bytearray#index-0), [[1]](library/stdtypes#index-21), [[2]](library/stdtypes#index-38), [[3]](library/stdtypes#index-40) * [bytearray (built-in class)](library/stdtypes#bytearray) * [bytecode](reference/datamodel#index-55), [**[1]**](glossary#term-bytecode) * [Bytecode (class in dis)](library/dis#dis.Bytecode) * [Bytecode.codeobj (in module dis)](library/dis#dis.Bytecode.codeobj) * [Bytecode.first\_line (in module dis)](library/dis#dis.Bytecode.first_line) * [BYTECODE\_SUFFIXES (in module importlib.machinery)](library/importlib#importlib.machinery.BYTECODE_SUFFIXES) * [BytecodeTestCase (class in test.support.bytecode\_helper)](library/test#test.support.bytecode_helper.BytecodeTestCase) * [byteorder (in module sys)](library/sys#sys.byteorder) * [bytes](reference/datamodel#index-21) + [built-in function](c-api/object#index-3), [[1]](reference/datamodel#index-73) + [formatting](library/stdtypes#index-43) + [interpolation](library/stdtypes#index-43) + [methods](library/stdtypes#index-41) + [object](c-api/bytes#index-0), [[1]](library/stdtypes#index-38), [[2]](library/stdtypes#index-39) + [str (built-in class)](library/stdtypes#index-29) * [bytes (built-in class)](library/stdtypes#bytes) + [(uuid.UUID attribute)](library/uuid#uuid.UUID.bytes) * [bytes literal](reference/lexical_analysis#index-16) * [**bytes-like object**](glossary#term-bytes-like-object) * [bytes\_le (uuid.UUID attribute)](library/uuid#uuid.UUID.bytes_le) * [BytesFeedParser (class in email.parser)](library/email.parser#email.parser.BytesFeedParser) * [BytesGenerator (class in email.generator)](library/email.generator#email.generator.BytesGenerator) * [BytesHeaderParser (class in email.parser)](library/email.parser#email.parser.BytesHeaderParser) * [BytesIO (class in io)](library/io#io.BytesIO) * [BytesParser (class in email.parser)](library/email.parser#email.parser.BytesParser) * [ByteString (class in collections.abc)](library/collections.abc#collections.abc.ByteString) + [(class in typing)](library/typing#typing.ByteString) * [byteswap() (array.array method)](library/array#array.array.byteswap) + [(in module audioop)](library/audioop#audioop.byteswap) * [BytesWarning](library/exceptions#BytesWarning) * [bz2 (module)](library/bz2#module-bz2) * [BZ2Compressor (class in bz2)](library/bz2#bz2.BZ2Compressor) * [BZ2Decompressor (class in bz2)](library/bz2#bz2.BZ2Decompressor) * [BZ2File (class in bz2)](library/bz2#bz2.BZ2File) | C - | | | | --- | --- | | * [C](reference/lexical_analysis#index-22) + [language](library/stdtypes#index-11), [[1]](library/stdtypes#index-15), [[2]](reference/datamodel#index-13), [[3]](reference/datamodel#index-4), [[4]](reference/datamodel#index-40), [[5]](reference/expressions#index-77) + [structures](library/struct#index-0) * [C-contiguous](c-api/buffer#index-2), [[1]](glossary#index-10) * [C14NWriterTarget (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.C14NWriterTarget) * [c\_bool (class in ctypes)](library/ctypes#ctypes.c_bool) * [C\_BUILTIN (in module imp)](library/imp#imp.C_BUILTIN) * [c\_byte (class in ctypes)](library/ctypes#ctypes.c_byte) * [c\_char (class in ctypes)](library/ctypes#ctypes.c_char) * [c\_char\_p (class in ctypes)](library/ctypes#ctypes.c_char_p) * [c\_contiguous (memoryview attribute)](library/stdtypes#memoryview.c_contiguous) * [c\_double (class in ctypes)](library/ctypes#ctypes.c_double) * [C\_EXTENSION (in module imp)](library/imp#imp.C_EXTENSION) * [c\_float (class in ctypes)](library/ctypes#ctypes.c_float) * [c\_int (class in ctypes)](library/ctypes#ctypes.c_int) * [c\_int16 (class in ctypes)](library/ctypes#ctypes.c_int16) * [c\_int32 (class in ctypes)](library/ctypes#ctypes.c_int32) * [c\_int64 (class in ctypes)](library/ctypes#ctypes.c_int64) * [c\_int8 (class in ctypes)](library/ctypes#ctypes.c_int8) * [c\_long (class in ctypes)](library/ctypes#ctypes.c_long) * [c\_longdouble (class in ctypes)](library/ctypes#ctypes.c_longdouble) * [c\_longlong (class in ctypes)](library/ctypes#ctypes.c_longlong) * [c\_short (class in ctypes)](library/ctypes#ctypes.c_short) * [c\_size\_t (class in ctypes)](library/ctypes#ctypes.c_size_t) * [c\_ssize\_t (class in ctypes)](library/ctypes#ctypes.c_ssize_t) * [c\_ubyte (class in ctypes)](library/ctypes#ctypes.c_ubyte) * [c\_uint (class in ctypes)](library/ctypes#ctypes.c_uint) * [c\_uint16 (class in ctypes)](library/ctypes#ctypes.c_uint16) * [c\_uint32 (class in ctypes)](library/ctypes#ctypes.c_uint32) * [c\_uint64 (class in ctypes)](library/ctypes#ctypes.c_uint64) * [c\_uint8 (class in ctypes)](library/ctypes#ctypes.c_uint8) * [c\_ulong (class in ctypes)](library/ctypes#ctypes.c_ulong) * [c\_ulonglong (class in ctypes)](library/ctypes#ctypes.c_ulonglong) * [c\_ushort (class in ctypes)](library/ctypes#ctypes.c_ushort) * [c\_void\_p (class in ctypes)](library/ctypes#ctypes.c_void_p) * [c\_wchar (class in ctypes)](library/ctypes#ctypes.c_wchar) * [c\_wchar\_p (class in ctypes)](library/ctypes#ctypes.c_wchar_p) * [CAB (class in msilib)](library/msilib#msilib.CAB) * [cache() (in module functools)](library/functools#functools.cache) * [cache\_from\_source() (in module imp)](library/imp#imp.cache_from_source) + [(in module importlib.util)](library/importlib#importlib.util.cache_from_source) * [cached (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.cached) * [cached\_property() (in module functools)](library/functools#functools.cached_property) * [CacheFTPHandler (class in urllib.request)](library/urllib.request#urllib.request.CacheFTPHandler) * [calcobjsize() (in module test.support)](library/test#test.support.calcobjsize) * [calcsize() (in module struct)](library/struct#struct.calcsize) * [calcvobjsize() (in module test.support)](library/test#test.support.calcvobjsize) * [Calendar (class in calendar)](library/calendar#calendar.Calendar) * [calendar (module)](library/calendar#module-calendar) * [calendar() (in module calendar)](library/calendar#calendar.calendar) * [call](reference/expressions#index-47) + [built-in function](reference/expressions#index-53) + [built-in method](reference/expressions#index-53) + [class instance](reference/expressions#index-55) + [class object](reference/datamodel#index-45), [[1]](reference/datamodel#index-47), [[2]](reference/expressions#index-54) + [function](reference/datamodel#index-32), [[1]](reference/expressions#index-52), [[2]](reference/expressions#index-53) + [instance](reference/datamodel#index-93), [[1]](reference/expressions#index-56) + [method](reference/expressions#index-53) + [procedure](reference/simple_stmts#index-3) + [user-defined function](reference/expressions#index-52) * [Call (class in ast)](library/ast#ast.Call) * [call() (in module subprocess)](library/subprocess#subprocess.call) + [(in module unittest.mock)](library/unittest.mock#unittest.mock.call) * [call\_args (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.call_args) * [call\_args\_list (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.call_args_list) * [call\_at() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.call_at) * [call\_count (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.call_count) * [call\_exception\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.call_exception_handler) * [CALL\_FUNCTION (opcode)](library/dis#opcode-CALL_FUNCTION) * [CALL\_FUNCTION\_EX (opcode)](library/dis#opcode-CALL_FUNCTION_EX) * [CALL\_FUNCTION\_KW (opcode)](library/dis#opcode-CALL_FUNCTION_KW) * [call\_later() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.call_later) * [call\_list() (unittest.mock.call method)](library/unittest.mock#unittest.mock.call.call_list) * [CALL\_METHOD (opcode)](library/dis#opcode-CALL_METHOD) * [call\_soon() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.call_soon) * [call\_soon\_threadsafe() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.call_soon_threadsafe) * [call\_tracing() (in module sys)](library/sys#sys.call_tracing) * callable + [object](reference/datamodel#index-32), [[1]](reference/expressions#index-47) * [Callable (class in collections.abc)](library/collections.abc#collections.abc.Callable) + [(in module typing)](library/typing#typing.Callable) * [callable() (built-in function)](library/functions#callable) * [CallableProxyType (in module weakref)](library/weakref#weakref.CallableProxyType) * [**callback**](glossary#term-callback) + [(optparse.Option attribute)](library/optparse#optparse.Option.callback) * [callback() (contextlib.ExitStack method)](library/contextlib#contextlib.ExitStack.callback) * [callback\_args (optparse.Option attribute)](library/optparse#optparse.Option.callback_args) * [callback\_kwargs (optparse.Option attribute)](library/optparse#optparse.Option.callback_kwargs) * [callbacks (in module gc)](library/gc#gc.callbacks) * [called (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.called) * [CalledProcessError](library/subprocess#subprocess.CalledProcessError) * [calloc()](c-api/memory#index-0) * [CAN\_BCM (in module socket)](library/socket#socket.CAN_BCM) * [can\_change\_color() (in module curses)](library/curses#curses.can_change_color) * [can\_fetch() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.can_fetch) * [CAN\_ISOTP (in module socket)](library/socket#socket.CAN_ISOTP) * [CAN\_J1939 (in module socket)](library/socket#socket.CAN_J1939) * [CAN\_RAW\_FD\_FRAMES (in module socket)](library/socket#socket.CAN_RAW_FD_FRAMES) * [CAN\_RAW\_JOIN\_FILTERS (in module socket)](library/socket#socket.CAN_RAW_JOIN_FILTERS) * [can\_symlink() (in module test.support)](library/test#test.support.can_symlink) * [can\_write\_eof() (asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.can_write_eof) + [(asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.can_write_eof) * [can\_xattr() (in module test.support)](library/test#test.support.can_xattr) * [cancel() (asyncio.Future method)](library/asyncio-future#asyncio.Future.cancel) + [(asyncio.Handle method)](library/asyncio-eventloop#asyncio.Handle.cancel) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.cancel) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.cancel) + [(sched.scheduler method)](library/sched#sched.scheduler.cancel) + [(threading.Timer method)](library/threading#threading.Timer.cancel) + [(tkinter.dnd.DndHandler method)](library/tkinter.dnd#tkinter.dnd.DndHandler.cancel) * [cancel\_command() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.cancel_command) * [cancel\_dump\_traceback\_later() (in module faulthandler)](library/faulthandler#faulthandler.cancel_dump_traceback_later) * [cancel\_join\_thread() (multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.cancel_join_thread) * [cancelled() (asyncio.Future method)](library/asyncio-future#asyncio.Future.cancelled) + [(asyncio.Handle method)](library/asyncio-eventloop#asyncio.Handle.cancelled) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.cancelled) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.cancelled) * [CancelledError](library/asyncio-exceptions#asyncio.CancelledError), [[1]](library/concurrent.futures#concurrent.futures.CancelledError) * [CannotSendHeader](library/http.client#http.client.CannotSendHeader) * [CannotSendRequest](library/http.client#http.client.CannotSendRequest) * [canonic() (bdb.Bdb method)](library/bdb#bdb.Bdb.canonic) * [canonical() (decimal.Context method)](library/decimal#decimal.Context.canonical) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.canonical) * [canonicalize() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.canonicalize) * [capa() (poplib.POP3 method)](library/poplib#poplib.POP3.capa) * [capitalize() (bytearray method)](library/stdtypes#bytearray.capitalize) + [(bytes method)](library/stdtypes#bytes.capitalize) + [(str method)](library/stdtypes#str.capitalize) * Capsule + [object](c-api/capsule#index-0) * [captured\_stderr() (in module test.support)](library/test#test.support.captured_stderr) * [captured\_stdin() (in module test.support)](library/test#test.support.captured_stdin) * [captured\_stdout() (in module test.support)](library/test#test.support.captured_stdout) * [captureWarnings() (in module logging)](library/logging#logging.captureWarnings) * [capwords() (in module string)](library/string#string.capwords) * [casefold() (str method)](library/stdtypes#str.casefold) * [cast() (in module ctypes)](library/ctypes#ctypes.cast) + [(in module typing)](library/typing#typing.cast) + [(memoryview method)](library/stdtypes#memoryview.cast) * [cat() (in module nis)](library/nis#nis.cat) * [catch\_threading\_exception() (in module test.support)](library/test#test.support.catch_threading_exception) * [catch\_unraisable\_exception() (in module test.support)](library/test#test.support.catch_unraisable_exception) * [catch\_warnings (class in warnings)](library/warnings#warnings.catch_warnings) * [category() (in module unicodedata)](library/unicodedata#unicodedata.category) * [cbreak() (in module curses)](library/curses#curses.cbreak) * [CC](https://docs.python.org/3.9/whatsnew/2.3.html#index-24) * [ccc() (ftplib.FTP\_TLS method)](library/ftplib#ftplib.FTP_TLS.ccc) * [CCompiler (class in distutils.ccompiler)](distutils/apiref#distutils.ccompiler.CCompiler) * [cdf() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.cdf) * [CDLL (class in ctypes)](library/ctypes#ctypes.CDLL) * [ceil() (in module math)](library/math#math.ceil), [[1]](library/stdtypes#index-15) * [CellType (in module types)](library/types#types.CellType) * [center() (bytearray method)](library/stdtypes#bytearray.center) + [(bytes method)](library/stdtypes#bytes.center) + [(str method)](library/stdtypes#str.center) * [CERT\_NONE (in module ssl)](library/ssl#ssl.CERT_NONE) * [CERT\_OPTIONAL (in module ssl)](library/ssl#ssl.CERT_OPTIONAL) * [CERT\_REQUIRED (in module ssl)](library/ssl#ssl.CERT_REQUIRED) * [cert\_store\_stats() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.cert_store_stats) * [cert\_time\_to\_seconds() (in module ssl)](library/ssl#ssl.cert_time_to_seconds) * [CertificateError](library/ssl#ssl.CertificateError) * [certificates](library/ssl#index-17) * [CFLAGS](install/index#index-10), [[1]](install/index#index-9), [[2]](https://docs.python.org/3.9/whatsnew/2.3.html#index-25) * [CFUNCTYPE() (in module ctypes)](library/ctypes#ctypes.CFUNCTYPE) * [cget() (tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.cget) * CGI + [debugging](library/cgi#index-5) + [exceptions](library/cgitb#index-0) + [protocol](library/cgi#index-0) + [security](library/cgi#index-2) + [tracebacks](library/cgitb#index-0) * [cgi (module)](library/cgi#module-cgi) * [cgi\_directories (http.server.CGIHTTPRequestHandler attribute)](library/http.server#http.server.CGIHTTPRequestHandler.cgi_directories) * [CGIHandler (class in wsgiref.handlers)](library/wsgiref#wsgiref.handlers.CGIHandler) * [CGIHTTPRequestHandler (class in http.server)](library/http.server#http.server.CGIHTTPRequestHandler) * [cgitb (module)](library/cgitb#module-cgitb) * [CGIXMLRPCRequestHandler (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler) * [chain() (in module itertools)](library/itertools#itertools.chain) * chaining + [comparisons](library/stdtypes#index-7), [[1]](reference/expressions#index-78) + [exception](reference/simple_stmts#index-29) * [ChainMap (class in collections)](library/collections#collections.ChainMap) + [(class in typing)](library/typing#typing.ChainMap) * [change\_cwd() (in module test.support)](library/test#test.support.change_cwd) * [change\_root() (in module distutils.util)](distutils/apiref#distutils.util.change_root) * [CHANNEL\_BINDING\_TYPES (in module ssl)](library/ssl#ssl.CHANNEL_BINDING_TYPES) * [channel\_class (smtpd.SMTPServer attribute)](library/smtpd#smtpd.SMTPServer.channel_class) * [channels() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.channels) * [CHAR\_MAX (in module locale)](library/locale#locale.CHAR_MAX) * [character](library/unicodedata#index-0), [[1]](reference/datamodel#index-19), [[2]](reference/expressions#index-43) * [CharacterDataHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.CharacterDataHandler) * [characters() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.characters) * [characters\_written (BlockingIOError attribute)](library/exceptions#BlockingIOError.characters_written) * [Charset (class in email.charset)](library/email.charset#email.charset.Charset) * [charset() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.charset) * [chdir() (in module os)](library/os#os.chdir) * [check (lzma.LZMADecompressor attribute)](library/lzma#lzma.LZMADecompressor.check) * [check() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.check) + [(in module tabnanny)](library/tabnanny#tabnanny.check) * [check\_\_all\_\_() (in module test.support)](library/test#test.support.check__all__) * [check\_call() (in module subprocess)](library/subprocess#subprocess.check_call) * [check\_environ() (in module distutils.util)](distutils/apiref#distutils.util.check_environ) * [check\_free\_after\_iterating() (in module test.support)](library/test#test.support.check_free_after_iterating) * [check\_hostname (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.check_hostname) * [check\_impl\_detail() (in module test.support)](library/test#test.support.check_impl_detail) * [check\_no\_resource\_warning() (in module test.support)](library/test#test.support.check_no_resource_warning) * [check\_output() (doctest.OutputChecker method)](library/doctest#doctest.OutputChecker.check_output) + [(in module subprocess)](library/subprocess#subprocess.check_output) * [check\_returncode() (subprocess.CompletedProcess method)](library/subprocess#subprocess.CompletedProcess.check_returncode) * [check\_syntax\_error() (in module test.support)](library/test#test.support.check_syntax_error) * [check\_syntax\_warning() (in module test.support)](library/test#test.support.check_syntax_warning) * [check\_unused\_args() (string.Formatter method)](library/string#string.Formatter.check_unused_args) * [check\_warnings() (in module test.support)](library/test#test.support.check_warnings) * [checkbox() (msilib.Dialog method)](library/msilib#msilib.Dialog.checkbox) * [checkcache() (in module linecache)](library/linecache#linecache.checkcache) * [CHECKED\_HASH (py\_compile.PycInvalidationMode attribute)](library/py_compile#py_compile.PycInvalidationMode.CHECKED_HASH) * [checkfuncname() (in module bdb)](library/bdb#bdb.checkfuncname) * [CheckList (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.CheckList) * [checksizeof() (in module test.support)](library/test#test.support.checksizeof) * checksum + [Cyclic Redundancy Check](library/zlib#index-0) * [chflags() (in module os)](library/os#os.chflags) * [chgat() (curses.window method)](library/curses#curses.window.chgat) * [childNodes (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.childNodes) * [ChildProcessError](library/exceptions#ChildProcessError) * [children (pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.children) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.children) + [(tkinter.Tk attribute)](library/tkinter#tkinter.Tk.children) * [chmod() (in module os)](library/os#os.chmod) + [(pathlib.Path method)](library/pathlib#pathlib.Path.chmod) * [choice() (in module random)](library/random#random.choice) + [(in module secrets)](library/secrets#secrets.choice) * [choices (optparse.Option attribute)](library/optparse#optparse.Option.choices) * [choices() (in module random)](library/random#random.choices) * [Chooser (class in tkinter.colorchooser)](library/tkinter.colorchooser#tkinter.colorchooser.Chooser) * [chown() (in module os)](library/os#os.chown) + [(in module shutil)](library/shutil#shutil.chown) * chr + [built-in function](reference/datamodel#index-19) * [chr() (built-in function)](library/functions#chr) * [chroot() (in module os)](library/os#os.chroot) * [Chunk (class in chunk)](library/chunk#chunk.Chunk) * [chunk (module)](library/chunk#module-chunk) * cipher + [DES](library/crypt#index-0) * [cipher() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.cipher) * [circle() (in module turtle)](library/turtle#turtle.circle) * [CIRCUMFLEX (in module token)](library/token#token.CIRCUMFLEX) * [CIRCUMFLEXEQUAL (in module token)](library/token#token.CIRCUMFLEXEQUAL) * [Clamped (class in decimal)](library/decimal#decimal.Clamped) * [**class**](glossary#term-class) + [attribute](reference/datamodel#index-45) + [attribute assignment](reference/datamodel#index-46) + [body](reference/datamodel#index-87) + [constructor](reference/datamodel#index-69) + [definition](reference/compound_stmts#index-31), [[1]](reference/simple_stmts#index-24) + [instance](reference/datamodel#index-49) + [name](reference/compound_stmts#index-31) + [object](reference/compound_stmts#index-31), [[1]](reference/datamodel#index-45), [[2]](reference/expressions#index-54) + [statement](reference/compound_stmts#index-31) * [Class (class in symtable)](library/symtable#symtable.Class) * [Class browser](library/idle#index-1) * class instance + [attribute](reference/datamodel#index-49) + [attribute assignment](reference/datamodel#index-50) + [call](reference/expressions#index-55) + [object](reference/datamodel#index-45), [[1]](reference/datamodel#index-49), [[2]](reference/expressions#index-55) * class object + [call](reference/datamodel#index-45), [[1]](reference/datamodel#index-47), [[2]](reference/expressions#index-54) * [**class variable**](glossary#term-class-variable) * [ClassDef (class in ast)](library/ast#ast.ClassDef) * classmethod + [built-in function](c-api/structures#index-0) * [classmethod() (built-in function)](library/functions#classmethod) * [ClassMethodDescriptorType (in module types)](library/types#types.ClassMethodDescriptorType) * [ClassVar (in module typing)](library/typing#typing.ClassVar) * [clause](reference/compound_stmts#index-1) * [CLD\_CONTINUED (in module os)](library/os#os.CLD_CONTINUED) * [CLD\_DUMPED (in module os)](library/os#os.CLD_DUMPED) * [CLD\_EXITED (in module os)](library/os#os.CLD_EXITED) * [CLD\_KILLED (in module os)](library/os#os.CLD_KILLED) * [CLD\_STOPPED (in module os)](library/os#os.CLD_STOPPED) * [CLD\_TRAPPED (in module os)](library/os#os.CLD_TRAPPED) * [clean() (mailbox.Maildir method)](library/mailbox#mailbox.Maildir.clean) * [cleandoc() (in module inspect)](library/inspect#inspect.cleandoc) * [CleanImport (class in test.support)](library/test#test.support.CleanImport) * [cleanup functions](c-api/sys#index-3) * [clear (pdb command)](library/pdb#pdbcommand-clear) * [Clear Breakpoint](library/idle#index-4) * [clear() (asyncio.Event method)](library/asyncio-sync#asyncio.Event.clear) + [(collections.deque method)](library/collections#collections.deque.clear) + [(curses.window method)](library/curses#curses.window.clear) + [(dict method)](library/stdtypes#dict.clear) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.clear) + [(frame method)](reference/datamodel#frame.clear) + [(frozenset method)](library/stdtypes#frozenset.clear) + [(http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.clear) + [(in module turtle)](library/turtle#turtle.clear) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.clear) + [(sequence method)](library/stdtypes#index-22) + [(threading.Event method)](library/threading#threading.Event.clear) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.clear) * [clear\_all\_breaks() (bdb.Bdb method)](library/bdb#bdb.Bdb.clear_all_breaks) * [clear\_all\_file\_breaks() (bdb.Bdb method)](library/bdb#bdb.Bdb.clear_all_file_breaks) * [clear\_bpbynumber() (bdb.Bdb method)](library/bdb#bdb.Bdb.clear_bpbynumber) * [clear\_break() (bdb.Bdb method)](library/bdb#bdb.Bdb.clear_break) * [clear\_cache() (in module filecmp)](library/filecmp#filecmp.clear_cache) + [(zoneinfo.ZoneInfo class method)](library/zoneinfo#zoneinfo.ZoneInfo.clear_cache) * [clear\_content() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.clear_content) * [clear\_flags() (decimal.Context method)](library/decimal#decimal.Context.clear_flags) * [clear\_frames() (in module traceback)](library/traceback#traceback.clear_frames) * [clear\_history() (in module readline)](library/readline#readline.clear_history) * [clear\_session\_cookies() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.clear_session_cookies) * [clear\_traces() (in module tracemalloc)](library/tracemalloc#tracemalloc.clear_traces) * [clear\_traps() (decimal.Context method)](library/decimal#decimal.Context.clear_traps) * [clearcache() (in module linecache)](library/linecache#linecache.clearcache) * [ClearData() (msilib.Record method)](library/msilib#msilib.Record.ClearData) * [clearok() (curses.window method)](library/curses#curses.window.clearok) * [clearscreen() (in module turtle)](library/turtle#turtle.clearscreen) * [clearstamp() (in module turtle)](library/turtle#turtle.clearstamp) * [clearstamps() (in module turtle)](library/turtle#turtle.clearstamps) * [Client() (in module multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.Client) * [client\_address (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.client_address) * [CLOCK\_BOOTTIME (in module time)](library/time#time.CLOCK_BOOTTIME) * [clock\_getres() (in module time)](library/time#time.clock_getres) * [clock\_gettime() (in module time)](library/time#time.clock_gettime) * [clock\_gettime\_ns() (in module time)](library/time#time.clock_gettime_ns) * [CLOCK\_HIGHRES (in module time)](library/time#time.CLOCK_HIGHRES) * [CLOCK\_MONOTONIC (in module time)](library/time#time.CLOCK_MONOTONIC) * [CLOCK\_MONOTONIC\_RAW (in module time)](library/time#time.CLOCK_MONOTONIC_RAW) * [CLOCK\_PROCESS\_CPUTIME\_ID (in module time)](library/time#time.CLOCK_PROCESS_CPUTIME_ID) * [CLOCK\_PROF (in module time)](library/time#time.CLOCK_PROF) * [CLOCK\_REALTIME (in module time)](library/time#time.CLOCK_REALTIME) * [clock\_settime() (in module time)](library/time#time.clock_settime) * [clock\_settime\_ns() (in module time)](library/time#time.clock_settime_ns) * [CLOCK\_TAI (in module time)](library/time#time.CLOCK_TAI) * [CLOCK\_THREAD\_CPUTIME\_ID (in module time)](library/time#time.CLOCK_THREAD_CPUTIME_ID) * [CLOCK\_UPTIME (in module time)](library/time#time.CLOCK_UPTIME) * [CLOCK\_UPTIME\_RAW (in module time)](library/time#time.CLOCK_UPTIME_RAW) * [clone() (email.generator.BytesGenerator method)](library/email.generator#email.generator.BytesGenerator.clone) + [(email.generator.Generator method)](library/email.generator#email.generator.Generator.clone) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.clone) + [(in module turtle)](library/turtle#turtle.clone) + [(pipes.Template method)](library/pipes#pipes.Template.clone) * [cloneNode() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.cloneNode) * [close() (aifc.aifc method)](library/aifc#aifc.aifc.close) + [(asyncio.AbstractChildWatcher method)](library/asyncio-policy#asyncio.AbstractChildWatcher.close) + [(asyncio.BaseTransport method)](library/asyncio-protocol#asyncio.BaseTransport.close) + [(asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.close) + [(asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.close) + [(asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.close) + [(asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.close) + [(asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.close) + [(chunk.Chunk method)](library/chunk#chunk.Chunk.close) + [(contextlib.ExitStack method)](library/contextlib#contextlib.ExitStack.close) + [(coroutine method)](reference/datamodel#coroutine.close) + [(dbm.dumb.dumbdbm method)](library/dbm#dbm.dumb.dumbdbm.close) + [(dbm.gnu.gdbm method)](library/dbm#dbm.gnu.gdbm.close) + [(dbm.ndbm.ndbm method)](library/dbm#dbm.ndbm.ndbm.close) + [(distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.close) + [(email.parser.BytesFeedParser method)](library/email.parser#email.parser.BytesFeedParser.close) + [(ftplib.FTP method)](library/ftplib#ftplib.FTP.close) + [(generator method)](reference/expressions#generator.close) + [(html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.close) + [(http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.close) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.close) + [(in module fileinput)](library/fileinput#fileinput.close) + [(in module os)](c-api/init#index-44), [[1]](library/os#os.close) + [(in module socket)](library/socket#socket.close) + [(io.IOBase method)](library/io#io.IOBase.close) + [(logging.FileHandler method)](library/logging.handlers#logging.FileHandler.close) + [(logging.Handler method)](library/logging#logging.Handler.close) + [(logging.handlers.MemoryHandler method)](library/logging.handlers#logging.handlers.MemoryHandler.close) + [(logging.handlers.NTEventLogHandler method)](library/logging.handlers#logging.handlers.NTEventLogHandler.close) + [(logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.close) + [(logging.handlers.SysLogHandler method)](library/logging.handlers#logging.handlers.SysLogHandler.close) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.close) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.close) + [(mailbox.MH method)](library/mailbox#mailbox.MH.close) + [(mmap.mmap method)](library/mmap#mmap.mmap.close) * [Close() (msilib.Database method)](library/msilib#msilib.Database.Close) + [(msilib.View method)](library/msilib#msilib.View.Close) * [close() (multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.close) + [(multiprocessing.connection.Listener method)](library/multiprocessing#multiprocessing.connection.Listener.close) + [(multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.close) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.close) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.close) + [(multiprocessing.shared\_memory.SharedMemory method)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory.close) + [(multiprocessing.SimpleQueue method)](library/multiprocessing#multiprocessing.SimpleQueue.close) + [(os.scandir method)](library/os#os.scandir.close) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.close) + [(ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.close) + [(select.devpoll method)](library/select#select.devpoll.close) + [(select.epoll method)](library/select#select.epoll.close) + [(select.kqueue method)](library/select#select.kqueue.close) + [(selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.close) + [(shelve.Shelf method)](library/shelve#shelve.Shelf.close) + [(socket.socket method)](library/socket#socket.socket.close) + [(sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.close) + [(sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.close) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.close) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.close) + [(tarfile.TarFile method)](library/tarfile#tarfile.TarFile.close) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.close) + [(urllib.request.BaseHandler method)](library/urllib.request#urllib.request.BaseHandler.close) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.close) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.close) * [Close() (winreg.PyHKEY method)](library/winreg#winreg.PyHKEY.Close) * [close() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.close) + [(xml.etree.ElementTree.XMLParser method)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLParser.close) + [(xml.etree.ElementTree.XMLPullParser method)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLPullParser.close) + [(xml.sax.xmlreader.IncrementalParser method)](library/xml.sax.reader#xml.sax.xmlreader.IncrementalParser.close) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.close) * [close\_connection (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.close_connection) * [close\_when\_done() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.close_when_done) * [closed (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.closed) + [(io.IOBase attribute)](library/io#io.IOBase.closed) + [(mmap.mmap attribute)](library/mmap#mmap.mmap.closed) + [(ossaudiodev.oss\_audio\_device attribute)](library/ossaudiodev#ossaudiodev.oss_audio_device.closed) + [(select.devpoll attribute)](library/select#select.devpoll.closed) + [(select.epoll attribute)](library/select#select.epoll.closed) + [(select.kqueue attribute)](library/select#select.kqueue.closed) * [CloseKey() (in module winreg)](library/winreg#winreg.CloseKey) * [closelog() (in module syslog)](library/syslog#syslog.closelog) * [closerange() (in module os)](library/os#os.closerange) * [closing() (in module contextlib)](library/contextlib#contextlib.closing) * [clrtobot() (curses.window method)](library/curses#curses.window.clrtobot) * [clrtoeol() (curses.window method)](library/curses#curses.window.clrtoeol) * [cmath (module)](library/cmath#module-cmath) * cmd + [module](library/pdb#index-1) * [Cmd (class in cmd)](library/cmd#cmd.Cmd) * [cmd (module)](library/cmd#module-cmd) + [(subprocess.CalledProcessError attribute)](library/subprocess#subprocess.CalledProcessError.cmd) + [(subprocess.TimeoutExpired attribute)](library/subprocess#subprocess.TimeoutExpired.cmd) * [cmdloop() (cmd.Cmd method)](library/cmd#cmd.Cmd.cmdloop) * [cmdqueue (cmd.Cmd attribute)](library/cmd#cmd.Cmd.cmdqueue) * [cmp() (in module filecmp)](library/filecmp#filecmp.cmp) * [cmp\_op (in module dis)](library/dis#dis.cmp_op) * [cmp\_to\_key() (in module functools)](library/functools#functools.cmp_to_key) * [cmpfiles() (in module filecmp)](library/filecmp#filecmp.cmpfiles) * [CMSG\_LEN() (in module socket)](library/socket#socket.CMSG_LEN) * [CMSG\_SPACE() (in module socket)](library/socket#socket.CMSG_SPACE) * [co\_argcount (code object attribute)](reference/datamodel#index-56) * [CO\_ASYNC\_GENERATOR (in module inspect)](library/inspect#inspect.CO_ASYNC_GENERATOR) * [co\_cellvars (code object attribute)](reference/datamodel#index-56) * [co\_code (code object attribute)](reference/datamodel#index-56) * [co\_consts (code object attribute)](reference/datamodel#index-56) * [CO\_COROUTINE (in module inspect)](library/inspect#inspect.CO_COROUTINE) * [co\_filename (code object attribute)](reference/datamodel#index-56) * [co\_firstlineno (code object attribute)](reference/datamodel#index-56) * [co\_flags (code object attribute)](reference/datamodel#index-56) * [co\_freevars (code object attribute)](reference/datamodel#index-56) * [CO\_FUTURE\_DIVISION (C variable)](c-api/veryhigh#c.CO_FUTURE_DIVISION) * [CO\_GENERATOR (in module inspect)](library/inspect#inspect.CO_GENERATOR) * [CO\_ITERABLE\_COROUTINE (in module inspect)](library/inspect#inspect.CO_ITERABLE_COROUTINE) * [co\_kwonlyargcount (code object attribute)](reference/datamodel#index-56) * [co\_lnotab (code object attribute)](reference/datamodel#index-56) * [co\_name (code object attribute)](reference/datamodel#index-56) * [co\_names (code object attribute)](reference/datamodel#index-56) * [CO\_NESTED (in module inspect)](library/inspect#inspect.CO_NESTED) * [CO\_NEWLOCALS (in module inspect)](library/inspect#inspect.CO_NEWLOCALS) * [co\_nlocals (code object attribute)](reference/datamodel#index-56) * [CO\_NOFREE (in module inspect)](library/inspect#inspect.CO_NOFREE) * [CO\_OPTIMIZED (in module inspect)](library/inspect#inspect.CO_OPTIMIZED) * [co\_posonlyargcount (code object attribute)](reference/datamodel#index-56) * [co\_stacksize (code object attribute)](reference/datamodel#index-56) * [CO\_VARARGS (in module inspect)](library/inspect#inspect.CO_VARARGS) * [CO\_VARKEYWORDS (in module inspect)](library/inspect#inspect.CO_VARKEYWORDS) * [co\_varnames (code object attribute)](reference/datamodel#index-56) * code + [block](reference/executionmodel#index-0) * [code (module)](library/code#module-code) + [(SystemExit attribute)](library/exceptions#SystemExit.code) + [(urllib.error.HTTPError attribute)](library/urllib.error#urllib.error.HTTPError.code) + [(urllib.response.addinfourl attribute)](library/urllib.request#urllib.response.addinfourl.code) + [(xml.etree.ElementTree.ParseError attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.ParseError.code) + [(xml.parsers.expat.ExpatError attribute)](library/pyexpat#xml.parsers.expat.ExpatError.code) * [code object](c-api/code#index-0), [[1]](library/marshal#index-1), [[2]](library/stdtypes#index-57), [[3]](reference/datamodel#index-55) * [code\_info() (in module dis)](library/dis#dis.code_info) * [CodecInfo (class in codecs)](library/codecs#codecs.CodecInfo) * [Codecs](library/codecs#index-0) + [decode](library/codecs#index-0) + [encode](library/codecs#index-0) * [codecs (module)](library/codecs#module-codecs) * [coded\_value (http.cookies.Morsel attribute)](library/http.cookies#http.cookies.Morsel.coded_value) * [codeop (module)](library/codeop#module-codeop) * [codepoint2name (in module html.entities)](library/html.entities#html.entities.codepoint2name) * [codes (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.codes) * [CODESET (in module locale)](library/locale#locale.CODESET) * [CodeType (class in types)](library/types#types.CodeType) * coding + [style](tutorial/controlflow#index-8) * [**coercion**](glossary#term-coercion) * [col\_offset (ast.AST attribute)](library/ast#ast.AST.col_offset) * [collapse\_addresses() (in module ipaddress)](library/ipaddress#ipaddress.collapse_addresses) * [collapse\_rfc2231\_value() (in module email.utils)](library/email.utils#email.utils.collapse_rfc2231_value) * [collect() (in module gc)](library/gc#gc.collect) * [collect\_incoming\_data() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.collect_incoming_data) | * [Collection (class in collections.abc)](library/collections.abc#collections.abc.Collection) + [(class in typing)](library/typing#typing.Collection) * [collections (module)](library/collections#module-collections) * [collections.abc (module)](library/collections.abc#module-collections.abc) * [colno (json.JSONDecodeError attribute)](library/json#json.JSONDecodeError.colno) + [(re.error attribute)](library/re#re.error.colno) * [COLON (in module token)](library/token#token.COLON) * [COLONEQUAL (in module token)](library/token#token.COLONEQUAL) * [color() (in module turtle)](library/turtle#turtle.color) * [color\_content() (in module curses)](library/curses#curses.color_content) * [color\_pair() (in module curses)](library/curses#curses.color_pair) * [colormode() (in module turtle)](library/turtle#turtle.colormode) * [colorsys (module)](library/colorsys#module-colorsys) * [COLS](library/curses#index-4), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-32) * [column() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.column) * [COLUMNS](library/curses#index-6), [[1]](library/curses#index-8) * [columns (os.terminal\_size attribute)](library/os#os.terminal_size.columns) * [comb() (in module math)](library/math#math.comb) * [combinations() (in module itertools)](library/itertools#itertools.combinations) * [combinations\_with\_replacement() (in module itertools)](library/itertools#itertools.combinations_with_replacement) * [combine() (datetime.datetime class method)](library/datetime#datetime.datetime.combine) * [combining() (in module unicodedata)](library/unicodedata#unicodedata.combining) * [ComboBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.ComboBox) * [Combobox (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Combobox) * [comma](reference/expressions#index-10) + [trailing](reference/expressions#index-94) * [COMMA (in module token)](library/token#token.COMMA) * [Command (class in distutils.cmd)](distutils/apiref#distutils.cmd.Command) + [(class in distutils.core)](distutils/apiref#distutils.core.Command) * [command (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.command) * [command line](reference/toplevel_components#index-4) * command line option + [--check-hash-based-pycs default|always|never](using/cmdline#cmdoption-check-hash-based-pycs) + [--help](using/cmdline#cmdoption-help) + [--version](using/cmdline#cmdoption-version) + [-?](using/cmdline#cmdoption) + [-b](using/cmdline#cmdoption-b) + [-B](using/cmdline#id1) + [-c <command>](using/cmdline#cmdoption-c) + [-d](using/cmdline#cmdoption-d) + [-E](using/cmdline#cmdoption-e) + [-h](using/cmdline#cmdoption-h) + [-i](using/cmdline#cmdoption-i) + [-I](using/cmdline#id2) + [-J](using/cmdline#cmdoption-j) + [-m <module-name>](using/cmdline#cmdoption-m) + [-O](using/cmdline#cmdoption-o) + [-OO](using/cmdline#cmdoption-oo) + [-q](using/cmdline#cmdoption-q) + [-R](using/cmdline#cmdoption-r) + [-s](using/cmdline#cmdoption-s) + [-S](using/cmdline#id3) + [-u](using/cmdline#cmdoption-u) + [-V](using/cmdline#cmdoption-v) + [-v](using/cmdline#id4) + [-W arg](using/cmdline#cmdoption-w) + [-x](using/cmdline#cmdoption-x) + [-X](using/cmdline#id5) * [CommandCompiler (class in codeop)](library/codeop#codeop.CommandCompiler) * [commands (pdb command)](library/pdb#pdbcommand-commands) * [comment](reference/lexical_analysis#index-4) + [(http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.comment) * [COMMENT (in module token)](library/token#token.COMMENT) * [comment (zipfile.ZipFile attribute)](library/zipfile#zipfile.ZipFile.comment) + [(zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.comment) * [Comment() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.Comment) * [comment() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.comment) * [comment\_url (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.comment_url) * [commenters (shlex.shlex attribute)](library/shlex#shlex.shlex.commenters) * [CommentHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.CommentHandler) * [commit() (msilib.CAB method)](library/msilib#msilib.CAB.commit) * [Commit() (msilib.Database method)](library/msilib#msilib.Database.Commit) * [commit() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.commit) * [common (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.common) * [Common Gateway Interface](library/cgi#index-0) * [common\_dirs (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.common_dirs) * [common\_files (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.common_files) * [common\_funny (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.common_funny) * [common\_types (in module mimetypes)](library/mimetypes#mimetypes.common_types) * [commonpath() (in module os.path)](library/os.path#os.path.commonpath) * [commonprefix() (in module os.path)](library/os.path#os.path.commonprefix) * [communicate() (asyncio.subprocess.Process method)](library/asyncio-subprocess#asyncio.subprocess.Process.communicate) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.communicate) * [Compare (class in ast)](library/ast#ast.Compare) * [compare() (decimal.Context method)](library/decimal#decimal.Context.compare) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.compare) + [(difflib.Differ method)](library/difflib#difflib.Differ.compare) * [compare\_digest() (in module hmac)](library/hmac#hmac.compare_digest) + [(in module secrets)](library/secrets#secrets.compare_digest) * [compare\_networks() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.compare_networks) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.compare_networks) * [COMPARE\_OP (opcode)](library/dis#opcode-COMPARE_OP) * [compare\_signal() (decimal.Context method)](library/decimal#decimal.Context.compare_signal) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.compare_signal) * [compare\_to() (tracemalloc.Snapshot method)](library/tracemalloc#tracemalloc.Snapshot.compare_to) * [compare\_total() (decimal.Context method)](library/decimal#decimal.Context.compare_total) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.compare_total) * [compare\_total\_mag() (decimal.Context method)](library/decimal#decimal.Context.compare_total_mag) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.compare_total_mag) * comparing + [objects](library/stdtypes#index-8) * [comparison](reference/expressions#index-77) + [operator](library/stdtypes#index-7) * [COMPARISON\_FLAGS (in module doctest)](library/doctest#doctest.COMPARISON_FLAGS) * [comparisons](reference/datamodel#index-75) + [chaining](library/stdtypes#index-7), [[1]](reference/expressions#index-78) * [Compat32 (class in email.policy)](library/email.policy#email.policy.Compat32) * [compat32 (in module email.policy)](library/email.policy#email.policy.compat32) * compile + [built-in function](c-api/import#index-2), [[1]](library/parser#index-2), [[2]](library/stdtypes#index-58), [[3]](library/types#index-3), [[4]](reference/simple_stmts#index-44) * [Compile (class in codeop)](library/codeop#codeop.Compile) * [compile() (built-in function)](library/functions#compile) + [(distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.compile) + [(in module py\_compile)](library/py_compile#py_compile.compile) + [(in module re)](library/re#re.compile) + [(parser.ST method)](library/parser#parser.ST.compile) * [compile\_command() (in module code)](library/code#code.compile_command) + [(in module codeop)](library/codeop#codeop.compile_command) * [compile\_dir() (in module compileall)](library/compileall#compileall.compile_dir) * [compile\_file() (in module compileall)](library/compileall#compileall.compile_file) * [compile\_path() (in module compileall)](library/compileall#compileall.compile_path) * [compileall (module)](library/compileall#module-compileall) * compileall command line option + [--hardlink-dupes](library/compileall#cmdoption-compileall-hardlink-dupes) + [--invalidation-mode [timestamp|checked-hash|unchecked-hash]](library/compileall#cmdoption-compileall-invalidation-mode) + [-b](library/compileall#cmdoption-compileall-b) + [-d destdir](library/compileall#cmdoption-compileall-d) + [-e dir](library/compileall#cmdoption-compileall-e) + [-f](library/compileall#cmdoption-compileall-f) + [-i list](library/compileall#cmdoption-compileall-i) + [-j N](library/compileall#cmdoption-compileall-j) + [-l](library/compileall#cmdoption-compileall-l) + [-o level](library/compileall#cmdoption-compileall-o) + [-p prepend\_prefix](library/compileall#cmdoption-compileall-p) + [-q](library/compileall#cmdoption-compileall-q) + [-r](library/compileall#cmdoption-compileall-r) + [-s strip\_prefix](library/compileall#cmdoption-compileall-s) + [-x regex](library/compileall#cmdoption-compileall-x) + [directory ...](library/compileall#cmdoption-compileall-arg-directory) + [file ...](library/compileall#cmdoption-compileall-arg-file) * [compilest() (in module parser)](library/parser#parser.compilest) * [complete() (rlcompleter.Completer method)](library/rlcompleter#rlcompleter.Completer.complete) * [complete\_statement() (in module sqlite3)](library/sqlite3#sqlite3.complete_statement) * [completedefault() (cmd.Cmd method)](library/cmd#cmd.Cmd.completedefault) * [CompletedProcess (class in subprocess)](library/subprocess#subprocess.CompletedProcess) * complex + [built-in function](library/stdtypes#index-13), [[1]](reference/datamodel#index-100) + [number](reference/datamodel#index-14) + [object](reference/datamodel#index-14) * [complex (built-in class)](library/functions#complex) * [Complex (class in numbers)](library/numbers#numbers.Complex) * [complex literal](reference/lexical_analysis#index-26) * [**complex number**](glossary#term-complex-number) + [literals](library/stdtypes#index-12) + [object](c-api/complex#index-0), [[1]](library/stdtypes#index-11) * compound + [statement](reference/compound_stmts#index-0) * [comprehension (class in ast)](library/ast#ast.comprehension) * [comprehensions](reference/expressions#index-11) + [dictionary](reference/expressions#index-17) + [list](reference/expressions#index-15) + [set](reference/expressions#index-16) * [compress() (bz2.BZ2Compressor method)](library/bz2#bz2.BZ2Compressor.compress) + [(in module bz2)](library/bz2#bz2.compress) + [(in module gzip)](library/gzip#gzip.compress) + [(in module itertools)](library/itertools#itertools.compress) + [(in module lzma)](library/lzma#lzma.compress) + [(in module zlib)](library/zlib#zlib.compress) + [(lzma.LZMACompressor method)](library/lzma#lzma.LZMACompressor.compress) + [(zlib.Compress method)](library/zlib#zlib.Compress.compress) * [compress\_size (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.compress_size) * [compress\_type (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.compress_type) * [compressed (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.compressed) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.compressed) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.compressed) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.compressed) * [compression() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.compression) * [CompressionError](library/tarfile#tarfile.CompressionError) * [compressobj() (in module zlib)](library/zlib#zlib.compressobj) * [COMSPEC](library/os#index-37), [[1]](library/subprocess#index-2) * [concat() (in module operator)](library/operator#operator.concat) * concatenation + [operation](library/stdtypes#index-19) * [concurrent.futures (module)](library/concurrent.futures#module-concurrent.futures) * [Condition (class in asyncio)](library/asyncio-sync#asyncio.Condition) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.Condition) + [(class in threading)](library/threading#threading.Condition) * [condition (pdb command)](library/pdb#pdbcommand-condition) * [condition() (msilib.Control method)](library/msilib#msilib.Control.condition) * [Condition() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Condition) * Conditional + [expression](reference/expressions#index-82) * conditional + [expression](reference/expressions#index-87) * [config() (tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.config) * [ConfigParser (class in configparser)](library/configparser#configparser.ConfigParser) * [configparser (module)](library/configparser#module-configparser) * configuration + [file](library/configparser#index-0) + [file, debugger](library/pdb#index-2) + [file, path](library/site#index-4) * [configuration information](library/sysconfig#index-0) * [configure() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.configure) * [configure\_mock() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.configure_mock) * [confstr() (in module os)](library/os#os.confstr) * [confstr\_names (in module os)](library/os#os.confstr_names) * [conjugate() (complex number method)](library/stdtypes#index-14) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.conjugate) + [(numbers.Complex method)](library/numbers#numbers.Complex.conjugate) * [conn (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.conn) * [connect() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.connect) + [(ftplib.FTP method)](library/ftplib#ftplib.FTP.connect) + [(http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.connect) + [(in module sqlite3)](library/sqlite3#sqlite3.connect) + [(multiprocessing.managers.BaseManager method)](library/multiprocessing#multiprocessing.managers.BaseManager.connect) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.connect) + [(socket.socket method)](library/socket#socket.socket.connect) * [connect\_accepted\_socket() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.connect_accepted_socket) * [connect\_ex() (socket.socket method)](library/socket#socket.socket.connect_ex) * [connect\_read\_pipe() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.connect_read_pipe) * [connect\_write\_pipe() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.connect_write_pipe) * [Connection (class in multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.Connection) + [(class in sqlite3)](library/sqlite3#sqlite3.Connection) * [connection (sqlite3.Cursor attribute)](library/sqlite3#sqlite3.Cursor.connection) * [connection\_lost() (asyncio.BaseProtocol method)](library/asyncio-protocol#asyncio.BaseProtocol.connection_lost) * [connection\_made() (asyncio.BaseProtocol method)](library/asyncio-protocol#asyncio.BaseProtocol.connection_made) * [ConnectionAbortedError](library/exceptions#ConnectionAbortedError) * [ConnectionError](library/exceptions#ConnectionError) * [ConnectionRefusedError](library/exceptions#ConnectionRefusedError) * [ConnectionResetError](library/exceptions#ConnectionResetError) * [ConnectRegistry() (in module winreg)](library/winreg#winreg.ConnectRegistry) * [const (optparse.Option attribute)](library/optparse#optparse.Option.const) * [constant](reference/lexical_analysis#index-15) * [Constant (class in ast)](library/ast#ast.Constant) * constructor + [class](reference/datamodel#index-69) * [constructor() (in module copyreg)](library/copyreg#copyreg.constructor) * [consumed (asyncio.LimitOverrunError attribute)](library/asyncio-exceptions#asyncio.LimitOverrunError.consumed) * [container](reference/datamodel#index-3), [[1]](reference/datamodel#index-45) + [iteration over](library/stdtypes#index-17) * [Container (class in collections.abc)](library/collections.abc#collections.abc.Container) + [(class in typing)](library/typing#typing.Container) * [contains() (in module operator)](library/operator#operator.contains) * [CONTAINS\_OP (opcode)](library/dis#opcode-CONTAINS_OP) * content type + [MIME](library/mimetypes#index-0) * [content\_disposition (email.headerregistry.ContentDispositionHeader attribute)](library/email.headerregistry#email.headerregistry.ContentDispositionHeader.content_disposition) * [content\_manager (email.policy.EmailPolicy attribute)](library/email.policy#email.policy.EmailPolicy.content_manager) * [content\_type (email.headerregistry.ContentTypeHeader attribute)](library/email.headerregistry#email.headerregistry.ContentTypeHeader.content_type) * [ContentDispositionHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.ContentDispositionHeader) * [ContentHandler (class in xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.ContentHandler) * [ContentManager (class in email.contentmanager)](library/email.contentmanager#email.contentmanager.ContentManager) * [contents (ctypes.\_Pointer attribute)](library/ctypes#ctypes._Pointer.contents) * [contents() (importlib.abc.ResourceReader method)](library/importlib#importlib.abc.ResourceReader.contents) + [(in module importlib.resources)](library/importlib#importlib.resources.contents) * [ContentTooShortError](library/urllib.error#urllib.error.ContentTooShortError) * [ContentTransferEncoding (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.ContentTransferEncoding) * [ContentTypeHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.ContentTypeHeader) * [Context (class in contextvars)](library/contextvars#contextvars.Context) + [(class in decimal)](library/decimal#decimal.Context) * [context (ssl.SSLSocket attribute)](library/ssl#ssl.SSLSocket.context) * [context management protocol](library/stdtypes#index-52) * [context manager](library/stdtypes#index-52), [[1]](reference/datamodel#index-102), [**[2]**](glossary#term-context-manager) * [**context variable**](glossary#term-context-variable) * [context\_diff() (in module difflib)](library/difflib#difflib.context_diff) * [ContextDecorator (class in contextlib)](library/contextlib#contextlib.ContextDecorator) * [contextlib (module)](library/contextlib#module-contextlib) * [ContextManager (class in typing)](library/typing#typing.ContextManager) * [contextmanager() (in module contextlib)](library/contextlib#contextlib.contextmanager) * [ContextVar (class in contextvars)](library/contextvars#contextvars.ContextVar) * [contextvars (module)](library/contextvars#module-contextvars) * [contiguous](c-api/buffer#index-2), [**[1]**](glossary#term-contiguous) + [(memoryview attribute)](library/stdtypes#memoryview.contiguous) * continue + [statement](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [[2]](reference/compound_stmts#index-5), [[3]](reference/compound_stmts#index-7), [**[4]**](reference/simple_stmts#index-33) * [Continue (class in ast)](library/ast#ast.Continue) * [continue (pdb command)](library/pdb#pdbcommand-continue) * [Control (class in msilib)](library/msilib#msilib.Control) + [(class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Control) * [control() (msilib.Dialog method)](library/msilib#msilib.Dialog.control) + [(select.kqueue method)](library/select#select.kqueue.control) * [controlnames (in module curses.ascii)](library/curses.ascii#curses.ascii.controlnames) * [controls() (ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.controls) * conversion + [arithmetic](reference/expressions#index-1) + [string](reference/datamodel#index-74), [[1]](reference/simple_stmts#index-3) * [ConversionError](library/xdrlib#xdrlib.ConversionError) * conversions + [numeric](library/stdtypes#index-15) * [convert\_arg\_line\_to\_args() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.convert_arg_line_to_args) * [convert\_field() (string.Formatter method)](library/string#string.Formatter.convert_field) * [convert\_path() (in module distutils.util)](distutils/apiref#distutils.util.convert_path) * [Cookie (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.Cookie) * [CookieError](library/http.cookies#http.cookies.CookieError) * [CookieJar (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.CookieJar) * [cookiejar (urllib.request.HTTPCookieProcessor attribute)](library/urllib.request#urllib.request.HTTPCookieProcessor.cookiejar) * [CookiePolicy (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.CookiePolicy) * [Coordinated Universal Time](library/time#index-4) * [Copy](library/idle#index-4) * copy + [module](library/copyreg#index-0) + [protocol](library/pickle#index-5) * [copy (module)](library/copy#module-copy) * [copy() (collections.deque method)](library/collections#collections.deque.copy) + [(contextvars.Context method)](library/contextvars#contextvars.Context.copy) + [(decimal.Context method)](library/decimal#decimal.Context.copy) + [(dict method)](library/stdtypes#dict.copy) + [(frozenset method)](library/stdtypes#frozenset.copy) + [(hashlib.hash method)](library/hashlib#hashlib.hash.copy) + [(hmac.HMAC method)](library/hmac#hmac.HMAC.copy) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.copy) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.copy) + [(in module copy)](library/copy#copy.copy) + [(in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.copy) + [(in module shutil)](library/shutil#shutil.copy) + [(pipes.Template method)](library/pipes#pipes.Template.copy) + [(sequence method)](library/stdtypes#index-22) + [(tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.copy) + [(types.MappingProxyType method)](library/types#types.MappingProxyType.copy) + [(zlib.Compress method)](library/zlib#zlib.Compress.copy) + [(zlib.Decompress method)](library/zlib#zlib.Decompress.copy) * [copy2() (in module shutil)](library/shutil#shutil.copy2) * [copy\_abs() (decimal.Context method)](library/decimal#decimal.Context.copy_abs) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.copy_abs) * [copy\_context() (in module contextvars)](library/contextvars#contextvars.copy_context) * [copy\_decimal() (decimal.Context method)](library/decimal#decimal.Context.copy_decimal) * [copy\_file() (in module distutils.file\_util)](distutils/apiref#distutils.file_util.copy_file) * [copy\_file\_range() (in module os)](library/os#os.copy_file_range) * [copy\_location() (in module ast)](library/ast#ast.copy_location) * [copy\_negate() (decimal.Context method)](library/decimal#decimal.Context.copy_negate) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.copy_negate) * [copy\_sign() (decimal.Context method)](library/decimal#decimal.Context.copy_sign) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.copy_sign) * [copy\_tree() (in module distutils.dir\_util)](distutils/apiref#distutils.dir_util.copy_tree) * [copyfile() (in module shutil)](library/shutil#shutil.copyfile) * [copyfileobj() (in module shutil)](library/shutil#shutil.copyfileobj) * [copying files](library/shutil#index-0) * [copymode() (in module shutil)](library/shutil#shutil.copymode) * [copyreg (module)](library/copyreg#module-copyreg) * [copyright (built-in variable)](library/constants#copyright) + [(in module sys)](c-api/init#index-27), [[1]](library/sys#sys.copyright) * [copysign() (in module math)](library/math#math.copysign) * [copystat() (in module shutil)](library/shutil#shutil.copystat) * [copytree() (in module shutil)](library/shutil#shutil.copytree) * [coroutine](reference/datamodel#index-104), [[1]](reference/expressions#index-24), [**[2]**](glossary#term-coroutine) + [function](reference/datamodel#index-38) * [Coroutine (class in collections.abc)](library/collections.abc#collections.abc.Coroutine) + [(class in typing)](library/typing#typing.Coroutine) * [**coroutine function**](glossary#term-coroutine-function) * [coroutine() (in module asyncio)](library/asyncio-task#asyncio.coroutine) + [(in module types)](library/types#types.coroutine) * [CoroutineType (in module types)](library/types#types.CoroutineType) * [cos() (in module cmath)](library/cmath#cmath.cos) + [(in module math)](library/math#math.cos) * [cosh() (in module cmath)](library/cmath#cmath.cosh) + [(in module math)](library/math#math.cosh) * [count (tracemalloc.Statistic attribute)](library/tracemalloc#tracemalloc.Statistic.count) + [(tracemalloc.StatisticDiff attribute)](library/tracemalloc#tracemalloc.StatisticDiff.count) * [count() (array.array method)](library/array#array.array.count) + [(bytearray method)](library/stdtypes#bytearray.count) + [(bytes method)](library/stdtypes#bytes.count) + [(collections.deque method)](library/collections#collections.deque.count) + [(in module itertools)](library/itertools#itertools.count) + [(multiprocessing.shared\_memory.ShareableList method)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.ShareableList.count) + [(sequence method)](library/stdtypes#index-19) + [(str method)](library/stdtypes#str.count) * [count\_diff (tracemalloc.StatisticDiff attribute)](library/tracemalloc#tracemalloc.StatisticDiff.count_diff) * [Counter (class in collections)](library/collections#collections.Counter) + [(class in typing)](library/typing#typing.Counter) * [countOf() (in module operator)](library/operator#operator.countOf) * [countTestCases() (unittest.TestCase method)](library/unittest#unittest.TestCase.countTestCases) + [(unittest.TestSuite method)](library/unittest#unittest.TestSuite.countTestCases) * [CoverageResults (class in trace)](library/trace#trace.CoverageResults) * [CPP](https://docs.python.org/3.9/whatsnew/2.3.html#index-26) * [CPPFLAGS](https://docs.python.org/3.9/whatsnew/2.3.html#index-28) * [cProfile (module)](library/profile#module-cProfile) * [CPU time](library/time#index-12), [[1]](library/time#index-7) * [cpu\_count() (in module multiprocessing)](library/multiprocessing#multiprocessing.cpu_count) + [(in module os)](library/os#os.cpu_count) * [**CPython**](glossary#term-cpython) * [cpython\_only() (in module test.support)](library/test#test.support.cpython_only) * [crawl\_delay() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.crawl_delay) * [CRC (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.CRC) * [crc32() (in module binascii)](library/binascii#binascii.crc32) + [(in module zlib)](library/zlib#zlib.crc32) * [crc\_hqx() (in module binascii)](library/binascii#binascii.crc_hqx) * [create() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.create) + [(in module venv)](library/venv#venv.create) + [(venv.EnvBuilder method)](library/venv#venv.EnvBuilder.create) * [create\_aggregate() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.create_aggregate) * [create\_archive() (in module zipapp)](library/zipapp#zipapp.create_archive) * [create\_autospec() (in module unittest.mock)](library/unittest.mock#unittest.mock.create_autospec) * [CREATE\_BREAKAWAY\_FROM\_JOB (in module subprocess)](library/subprocess#subprocess.CREATE_BREAKAWAY_FROM_JOB) * [create\_collation() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.create_collation) * [create\_configuration() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.create_configuration) * [create\_connection() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_connection) + [(in module socket)](library/socket#socket.create_connection) * [create\_datagram\_endpoint() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_datagram_endpoint) * [create\_decimal() (decimal.Context method)](library/decimal#decimal.Context.create_decimal) * [create\_decimal\_from\_float() (decimal.Context method)](library/decimal#decimal.Context.create_decimal_from_float) * [create\_default\_context() (in module ssl)](library/ssl#ssl.create_default_context) * [CREATE\_DEFAULT\_ERROR\_MODE (in module subprocess)](library/subprocess#subprocess.CREATE_DEFAULT_ERROR_MODE) * [create\_empty\_file() (in module test.support)](library/test#test.support.create_empty_file) * [create\_function() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.create_function) * [create\_future() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_future) * [create\_module (C function)](c-api/module#c.create_module) * [create\_module() (importlib.abc.Loader method)](library/importlib#importlib.abc.Loader.create_module) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.create_module) * [CREATE\_NEW\_CONSOLE (in module subprocess)](library/subprocess#subprocess.CREATE_NEW_CONSOLE) * [CREATE\_NEW\_PROCESS\_GROUP (in module subprocess)](library/subprocess#subprocess.CREATE_NEW_PROCESS_GROUP) * [CREATE\_NO\_WINDOW (in module subprocess)](library/subprocess#subprocess.CREATE_NO_WINDOW) * [create\_server() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_server) + [(in module socket)](library/socket#socket.create_server) * [create\_shortcut() (built-in function)](distutils/builtdist#create_shortcut) * [create\_socket() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.create_socket) * [create\_static\_lib() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.create_static_lib) * [create\_stats() (profile.Profile method)](library/profile#profile.Profile.create_stats) * [create\_string\_buffer() (in module ctypes)](library/ctypes#ctypes.create_string_buffer) * [create\_subprocess\_exec() (in module asyncio)](library/asyncio-subprocess#asyncio.create_subprocess_exec) * [create\_subprocess\_shell() (in module asyncio)](library/asyncio-subprocess#asyncio.create_subprocess_shell) * [create\_system (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.create_system) * [create\_task() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_task) + [(in module asyncio)](library/asyncio-task#asyncio.create_task) * [create\_tree() (in module distutils.dir\_util)](distutils/apiref#distutils.dir_util.create_tree) * [create\_unicode\_buffer() (in module ctypes)](library/ctypes#ctypes.create_unicode_buffer) * [create\_unix\_connection() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_unix_connection) * [create\_unix\_server() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.create_unix_server) * [create\_version (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.create_version) * [createAttribute() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createAttribute) * [createAttributeNS() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createAttributeNS) * [createComment() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createComment) * [createDocument() (xml.dom.DOMImplementation method)](library/xml.dom#xml.dom.DOMImplementation.createDocument) * [createDocumentType() (xml.dom.DOMImplementation method)](library/xml.dom#xml.dom.DOMImplementation.createDocumentType) * [createElement() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createElement) * [createElementNS() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createElementNS) * [createfilehandler() (tkinter.Widget.tk method)](library/tkinter#tkinter.Widget.tk.createfilehandler) * [CreateKey() (in module winreg)](library/winreg#winreg.CreateKey) * [CreateKeyEx() (in module winreg)](library/winreg#winreg.CreateKeyEx) * [createLock() (logging.Handler method)](library/logging#logging.Handler.createLock) + [(logging.NullHandler method)](library/logging.handlers#logging.NullHandler.createLock) * [createProcessingInstruction() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createProcessingInstruction) * [CreateRecord() (in module msilib)](library/msilib#msilib.CreateRecord) * [createSocket() (logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.createSocket) * [createTextNode() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.createTextNode) * [credits (built-in variable)](library/constants#credits) * [critical() (in module logging)](library/logging#logging.critical) + [(logging.Logger method)](library/logging#logging.Logger.critical) * [CRNCYSTR (in module locale)](library/locale#locale.CRNCYSTR) * [cross() (in module audioop)](library/audioop#audioop.cross) * crypt + [module](library/pwd#index-0) * [crypt (module)](library/crypt#module-crypt) * [crypt() (in module crypt)](library/crypt#crypt.crypt) * [crypt(3)](library/crypt#index-0), [[1]](library/crypt#index-2), [[2]](library/crypt#index-3) * [cryptography](library/crypto#index-0) * [cssclass\_month (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclass_month) * [cssclass\_month\_head (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclass_month_head) * [cssclass\_noday (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclass_noday) * [cssclass\_year (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclass_year) * [cssclass\_year\_head (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclass_year_head) * [cssclasses (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclasses) * [cssclasses\_weekday\_head (calendar.HTMLCalendar attribute)](library/calendar#calendar.HTMLCalendar.cssclasses_weekday_head) * [csv](library/csv#index-0) + [(module)](library/csv#module-csv) * [cte (email.headerregistry.ContentTransferEncoding attribute)](library/email.headerregistry#email.headerregistry.ContentTransferEncoding.cte) * [cte\_type (email.policy.Policy attribute)](library/email.policy#email.policy.Policy.cte_type) * [ctermid() (in module os)](library/os#os.ctermid) * [ctime() (datetime.date method)](library/datetime#datetime.date.ctime) + [(datetime.datetime method)](library/datetime#datetime.datetime.ctime) + [(in module time)](library/time#time.ctime) * [ctrl() (in module curses.ascii)](library/curses.ascii#curses.ascii.ctrl) * [CTRL\_BREAK\_EVENT (in module signal)](library/signal#signal.CTRL_BREAK_EVENT) * [CTRL\_C\_EVENT (in module signal)](library/signal#signal.CTRL_C_EVENT) * [ctypes (module)](library/ctypes#module-ctypes) * [curdir (in module os)](library/os#os.curdir) * [currency() (in module locale)](library/locale#locale.currency) * [current() (tkinter.ttk.Combobox method)](library/tkinter.ttk#tkinter.ttk.Combobox.current) * [current\_process() (in module multiprocessing)](library/multiprocessing#multiprocessing.current_process) * [current\_task() (in module asyncio)](library/asyncio-task#asyncio.current_task) * [current\_thread() (in module threading)](library/threading#threading.current_thread) * [CurrentByteIndex (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.CurrentByteIndex) * [CurrentColumnNumber (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.CurrentColumnNumber) * [currentframe() (in module inspect)](library/inspect#inspect.currentframe) * [CurrentLineNumber (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.CurrentLineNumber) * [curs\_set() (in module curses)](library/curses#curses.curs_set) * [curses (module)](library/curses#module-curses) * [curses.ascii (module)](library/curses.ascii#module-curses.ascii) * [curses.panel (module)](library/curses.panel#module-curses.panel) * [curses.textpad (module)](library/curses#module-curses.textpad) * [Cursor (class in sqlite3)](library/sqlite3#sqlite3.Cursor) * [cursor() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.cursor) * [cursyncup() (curses.window method)](library/curses#curses.window.cursyncup) * [customize\_compiler() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.customize_compiler) * [Cut](library/idle#index-4) * [cwd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.cwd) + [(pathlib.Path class method)](library/pathlib#pathlib.Path.cwd) * [cycle() (in module itertools)](library/itertools#itertools.cycle) * [CycleError](library/graphlib#graphlib.CycleError) * [Cyclic Redundancy Check](library/zlib#index-0) | D - | | | | --- | --- | | * [D\_FMT (in module locale)](library/locale#locale.D_FMT) * [D\_T\_FMT (in module locale)](library/locale#locale.D_T_FMT) * [daemon (multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.daemon) + [(threading.Thread attribute)](library/threading#threading.Thread.daemon) * dangling + [else](reference/compound_stmts#index-2) * [data](reference/datamodel#index-0) + [packing binary](library/struct#index-0) + [tabular](library/csv#index-0) + [type](reference/datamodel#index-4) + [type, immutable](reference/expressions#index-7) * [data (collections.UserDict attribute)](library/collections#collections.UserDict.data) + [(collections.UserList attribute)](library/collections#collections.UserList.data) + [(collections.UserString attribute)](library/collections#collections.UserString.data) + [(select.kevent attribute)](library/select#select.kevent.data) + [(selectors.SelectorKey attribute)](library/selectors#selectors.SelectorKey.data) + [(urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.data) + [(xml.dom.Comment attribute)](library/xml.dom#xml.dom.Comment.data) + [(xml.dom.ProcessingInstruction attribute)](library/xml.dom#xml.dom.ProcessingInstruction.data) + [(xml.dom.Text attribute)](library/xml.dom#xml.dom.Text.data) + [(xmlrpc.client.Binary attribute)](library/xmlrpc.client#xmlrpc.client.Binary.data) * [data() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.data) * [data\_open() (urllib.request.DataHandler method)](library/urllib.request#urllib.request.DataHandler.data_open) * [data\_received() (asyncio.Protocol method)](library/asyncio-protocol#asyncio.Protocol.data_received) * database + [Unicode](library/unicodedata#index-0) * [DatabaseError](library/sqlite3#sqlite3.DatabaseError) * [databases](library/dbm#index-0) * [dataclass() (in module dataclasses)](library/dataclasses#dataclasses.dataclass) * [dataclasses (module)](library/dataclasses#module-dataclasses) * [datagram\_received() (asyncio.DatagramProtocol method)](library/asyncio-protocol#asyncio.DatagramProtocol.datagram_received) * [DatagramHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.DatagramHandler) * [DatagramProtocol (class in asyncio)](library/asyncio-protocol#asyncio.DatagramProtocol) * [DatagramRequestHandler (class in socketserver)](library/socketserver#socketserver.DatagramRequestHandler) * [DatagramTransport (class in asyncio)](library/asyncio-protocol#asyncio.DatagramTransport) * [DataHandler (class in urllib.request)](library/urllib.request#urllib.request.DataHandler) * [date (class in datetime)](library/datetime#datetime.date) * [date() (datetime.datetime method)](library/datetime#datetime.datetime.date) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.date) * [date\_time (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.date_time) * [date\_time\_string() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.date_time_string) * [DateHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.DateHeader) * [datetime (class in datetime)](library/datetime#datetime.datetime) * [DateTime (class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.DateTime) * [datetime (email.headerregistry.DateHeader attribute)](library/email.headerregistry#email.headerregistry.DateHeader.datetime) + [(module)](library/datetime#module-datetime) * [datum](reference/expressions#index-17) * [day (datetime.date attribute)](library/datetime#datetime.date.day) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.day) * [day\_abbr (in module calendar)](library/calendar#calendar.day_abbr) * [day\_name (in module calendar)](library/calendar#calendar.day_name) * [daylight (in module time)](library/time#time.daylight) * [Daylight Saving Time](library/time#index-5) * [DbfilenameShelf (class in shelve)](library/shelve#shelve.DbfilenameShelf) * [dbm (module)](library/dbm#module-dbm) * [dbm.dumb (module)](library/dbm#module-dbm.dumb) * dbm.gnu + [module](library/shelve#index-1), [[1]](reference/datamodel#index-31) * [dbm.gnu (module)](library/dbm#module-dbm.gnu) * dbm.ndbm + [module](library/shelve#index-1), [[1]](reference/datamodel#index-31) * [dbm.ndbm (module)](library/dbm#module-dbm.ndbm) * [dcgettext() (in module locale)](library/locale#locale.dcgettext) * [deallocation, object](extending/newtypes#index-0) * [debug (imaplib.IMAP4 attribute)](library/imaplib#imaplib.IMAP4.debug) * [DEBUG (in module re)](library/re#re.DEBUG) * [debug (pdb command)](library/pdb#pdbcommand-debug) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.debug) + [(zipfile.ZipFile attribute)](library/zipfile#zipfile.ZipFile.debug) * [debug() (in module doctest)](library/doctest#doctest.debug) + [(in module logging)](library/logging#logging.debug) + [(logging.Logger method)](library/logging#logging.Logger.debug) + [(pipes.Template method)](library/pipes#pipes.Template.debug) + [(unittest.TestCase method)](library/unittest#unittest.TestCase.debug) + [(unittest.TestSuite method)](library/unittest#unittest.TestSuite.debug) * [DEBUG\_BYTECODE\_SUFFIXES (in module importlib.machinery)](library/importlib#importlib.machinery.DEBUG_BYTECODE_SUFFIXES) * [DEBUG\_COLLECTABLE (in module gc)](library/gc#gc.DEBUG_COLLECTABLE) * [DEBUG\_LEAK (in module gc)](library/gc#gc.DEBUG_LEAK) * [debug\_print() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.debug_print) * [DEBUG\_SAVEALL (in module gc)](library/gc#gc.DEBUG_SAVEALL) * [debug\_src() (in module doctest)](library/doctest#doctest.debug_src) * [DEBUG\_STATS (in module gc)](library/gc#gc.DEBUG_STATS) * [DEBUG\_UNCOLLECTABLE (in module gc)](library/gc#gc.DEBUG_UNCOLLECTABLE) * [debugger](library/idle#index-3), [[1]](library/sys#index-11), [[2]](library/sys#index-28) + [configuration file](library/pdb#index-2) * [debugging](library/pdb#index-0) + [assertions](reference/simple_stmts#index-18) + [CGI](library/cgi#index-5) * [DebuggingServer (class in smtpd)](library/smtpd#smtpd.DebuggingServer) * [debuglevel (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.debuglevel) * [DebugRunner (class in doctest)](library/doctest#doctest.DebugRunner) * [Decimal (class in decimal)](library/decimal#decimal.Decimal) * [decimal (module)](library/decimal#module-decimal) * [decimal literal](reference/lexical_analysis#index-26) * [decimal() (in module unicodedata)](library/unicodedata#unicodedata.decimal) * [DecimalException (class in decimal)](library/decimal#decimal.DecimalException) * decode + [Codecs](library/codecs#index-0) * [decode (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.decode) * [decode() (bytearray method)](library/stdtypes#bytearray.decode) + [(bytes method)](library/stdtypes#bytes.decode) + [(codecs.Codec method)](library/codecs#codecs.Codec.decode) + [(codecs.IncrementalDecoder method)](library/codecs#codecs.IncrementalDecoder.decode) + [(in module base64)](library/base64#base64.decode) + [(in module codecs)](library/codecs#codecs.decode) + [(in module quopri)](library/quopri#quopri.decode) + [(in module uu)](library/uu#uu.decode) + [(json.JSONDecoder method)](library/json#json.JSONDecoder.decode) + [(xmlrpc.client.Binary method)](library/xmlrpc.client#xmlrpc.client.Binary.decode) + [(xmlrpc.client.DateTime method)](library/xmlrpc.client#xmlrpc.client.DateTime.decode) * [decode\_header() (in module email.header)](library/email.header#email.header.decode_header) + [(in module nntplib)](library/nntplib#nntplib.decode_header) * [decode\_params() (in module email.utils)](library/email.utils#email.utils.decode_params) * [decode\_rfc2231() (in module email.utils)](library/email.utils#email.utils.decode_rfc2231) * [decode\_source() (in module importlib.util)](library/importlib#importlib.util.decode_source) * [decodebytes() (in module base64)](library/base64#base64.decodebytes) * [DecodedGenerator (class in email.generator)](library/email.generator#email.generator.DecodedGenerator) * [decodestring() (in module quopri)](library/quopri#quopri.decodestring) * [decomposition() (in module unicodedata)](library/unicodedata#unicodedata.decomposition) * [decompress() (bz2.BZ2Decompressor method)](library/bz2#bz2.BZ2Decompressor.decompress) + [(in module bz2)](library/bz2#bz2.decompress) + [(in module gzip)](library/gzip#gzip.decompress) + [(in module lzma)](library/lzma#lzma.decompress) + [(in module zlib)](library/zlib#zlib.decompress) + [(lzma.LZMADecompressor method)](library/lzma#lzma.LZMADecompressor.decompress) + [(zlib.Decompress method)](library/zlib#zlib.Decompress.decompress) * [decompressobj() (in module zlib)](library/zlib#zlib.decompressobj) * [**decorator**](glossary#term-decorator) * [DEDENT (in module token)](library/token#token.DEDENT) * [DEDENT token](reference/compound_stmts#index-2), [[1]](reference/lexical_analysis#index-9) * [dedent() (in module textwrap)](library/textwrap#textwrap.dedent) * [deepcopy() (in module copy)](library/copy#copy.deepcopy) * def + [statement](reference/compound_stmts#index-19) * [def\_prog\_mode() (in module curses)](library/curses#curses.def_prog_mode) * [def\_shell\_mode() (in module curses)](library/curses#curses.def_shell_mode) * default + [parameter value](reference/compound_stmts#index-22) * [default (in module email.policy)](library/email.policy#email.policy.default) * [DEFAULT (in module unittest.mock)](library/unittest.mock#unittest.mock.DEFAULT) * [default (inspect.Parameter attribute)](library/inspect#inspect.Parameter.default) + [(optparse.Option attribute)](library/optparse#optparse.Option.default) * [default() (cmd.Cmd method)](library/cmd#cmd.Cmd.default) + [(json.JSONEncoder method)](library/json#json.JSONEncoder.default) * [DEFAULT\_BUFFER\_SIZE (in module io)](library/io#io.DEFAULT_BUFFER_SIZE) * [default\_bufsize (in module xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.default_bufsize) * [default\_exception\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.default_exception_handler) * [default\_factory (collections.defaultdict attribute)](library/collections#collections.defaultdict.default_factory) * [DEFAULT\_FORMAT (in module tarfile)](library/tarfile#tarfile.DEFAULT_FORMAT) * [DEFAULT\_IGNORES (in module filecmp)](library/filecmp#filecmp.DEFAULT_IGNORES) * [default\_open() (urllib.request.BaseHandler method)](library/urllib.request#urllib.request.BaseHandler.default_open) * [DEFAULT\_PROTOCOL (in module pickle)](library/pickle#pickle.DEFAULT_PROTOCOL) * [default\_timer() (in module timeit)](library/timeit#timeit.default_timer) * [DefaultContext (class in decimal)](library/decimal#decimal.DefaultContext) * [DefaultCookiePolicy (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy) * [defaultdict (class in collections)](library/collections#collections.defaultdict) * [DefaultDict (class in typing)](library/typing#typing.DefaultDict) * [DefaultEventLoopPolicy (class in asyncio)](library/asyncio-policy#asyncio.DefaultEventLoopPolicy) * [DefaultHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.DefaultHandler) * [DefaultHandlerExpand() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.DefaultHandlerExpand) * [defaults() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.defaults) * [DefaultSelector (class in selectors)](library/selectors#selectors.DefaultSelector) * [defaultTestLoader (in module unittest)](library/unittest#unittest.defaultTestLoader) * [defaultTestResult() (unittest.TestCase method)](library/unittest#unittest.TestCase.defaultTestResult) * [defects (email.headerregistry.BaseHeader attribute)](library/email.headerregistry#email.headerregistry.BaseHeader.defects) + [(email.message.EmailMessage attribute)](library/email.message#email.message.EmailMessage.defects) + [(email.message.Message attribute)](library/email.compat32-message#email.message.Message.defects) * [define\_macro() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.define_macro) * definition + [class](reference/compound_stmts#index-31), [[1]](reference/simple_stmts#index-24) + [function](reference/compound_stmts#index-19), [[1]](reference/simple_stmts#index-24) * [defpath (in module os)](library/os#os.defpath) * [DefragResult (class in urllib.parse)](library/urllib.parse#urllib.parse.DefragResult) * [DefragResultBytes (class in urllib.parse)](library/urllib.parse#urllib.parse.DefragResultBytes) * [degrees() (in module math)](library/math#math.degrees) + [(in module turtle)](library/turtle#turtle.degrees) * del + [statement](library/stdtypes#index-22), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-70), [**[3]**](reference/simple_stmts#index-21) * [Del (class in ast)](library/ast#ast.Del) * [del\_param() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.del_param) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.del_param) * [delattr() (built-in function)](library/functions#delattr) * [delay() (in module turtle)](library/turtle#turtle.delay) * [delay\_output() (in module curses)](library/curses#curses.delay_output) * [delayload (http.cookiejar.FileCookieJar attribute)](library/http.cookiejar#http.cookiejar.FileCookieJar.delayload) * [delch() (curses.window method)](library/curses#curses.window.delch) * [dele() (poplib.POP3 method)](library/poplib#poplib.POP3.dele) * [Delete (class in ast)](library/ast#ast.Delete) * [delete() (ftplib.FTP method)](library/ftplib#ftplib.FTP.delete) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.delete) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.delete) * [DELETE\_ATTR (opcode)](library/dis#opcode-DELETE_ATTR) * [DELETE\_DEREF (opcode)](library/dis#opcode-DELETE_DEREF) * [DELETE\_FAST (opcode)](library/dis#opcode-DELETE_FAST) * [DELETE\_GLOBAL (opcode)](library/dis#opcode-DELETE_GLOBAL) * [DELETE\_NAME (opcode)](library/dis#opcode-DELETE_NAME) * [DELETE\_SUBSCR (opcode)](library/dis#opcode-DELETE_SUBSCR) * [deleteacl() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.deleteacl) * [deletefilehandler() (tkinter.Widget.tk method)](library/tkinter#tkinter.Widget.tk.deletefilehandler) * [DeleteKey() (in module winreg)](library/winreg#winreg.DeleteKey) * [DeleteKeyEx() (in module winreg)](library/winreg#winreg.DeleteKeyEx) * [deleteln() (curses.window method)](library/curses#curses.window.deleteln) * [deleteMe() (bdb.Breakpoint method)](library/bdb#bdb.Breakpoint.deleteMe) * [DeleteValue() (in module winreg)](library/winreg#winreg.DeleteValue) * deletion + [attribute](reference/simple_stmts#index-23) + [target](reference/simple_stmts#index-21) + [target list](reference/simple_stmts#index-21) * [delimiter (csv.Dialect attribute)](library/csv#csv.Dialect.delimiter) * [delimiters](reference/lexical_analysis#index-31) * [delitem() (in module operator)](library/operator#operator.delitem) * [deliver\_challenge() (in module multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.deliver_challenge) * [delocalize() (in module locale)](library/locale#locale.delocalize) * [demo\_app() (in module wsgiref.simple\_server)](library/wsgiref#wsgiref.simple_server.demo_app) * [denominator (fractions.Fraction attribute)](library/fractions#fractions.Fraction.denominator) + [(numbers.Rational attribute)](library/numbers#numbers.Rational.denominator) * [DeprecationWarning](library/exceptions#DeprecationWarning) * [deque (class in collections)](library/collections#collections.deque) * [Deque (class in typing)](library/typing#typing.Deque) * [dequeue() (logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.dequeue) * [DER\_cert\_to\_PEM\_cert() (in module ssl)](library/ssl#ssl.DER_cert_to_PEM_cert) * [derwin() (curses.window method)](library/curses#curses.window.derwin) * DES + [cipher](library/crypt#index-0) * [descrgetfunc (C type)](c-api/typeobj#c.descrgetfunc) * [description (inspect.Parameter.kind attribute)](library/inspect#inspect.Parameter.kind.description) + [(sqlite3.Cursor attribute)](library/sqlite3#sqlite3.Cursor.description) * [description() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.description) * [descriptions() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.descriptions) * [**descriptor**](glossary#term-descriptor) * [descrsetfunc (C type)](c-api/typeobj#c.descrsetfunc) * [dest (optparse.Option attribute)](library/optparse#optparse.Option.dest) * [destructor](reference/datamodel#index-70), [[1]](reference/simple_stmts#index-7) + [(C type)](c-api/typeobj#c.destructor) * [detach() (io.BufferedIOBase method)](library/io#io.BufferedIOBase.detach) + [(io.TextIOBase method)](library/io#io.TextIOBase.detach) + [(socket.socket method)](library/socket#socket.socket.detach) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.detach) + [(weakref.finalize method)](library/weakref#weakref.finalize.detach) * [Detach() (winreg.PyHKEY method)](library/winreg#winreg.PyHKEY.Detach) * [DETACHED\_PROCESS (in module subprocess)](library/subprocess#subprocess.DETACHED_PROCESS) * [detect\_api\_mismatch() (in module test.support)](library/test#test.support.detect_api_mismatch) * [detect\_encoding() (in module tokenize)](library/tokenize#tokenize.detect_encoding) * [detect\_language() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.detect_language) * [deterministic profiling](library/profile#index-0) * [device\_encoding() (in module os)](library/os#os.device_encoding) * [devnull (in module os)](library/os#os.devnull) * [DEVNULL (in module subprocess)](library/subprocess#subprocess.DEVNULL) * [devpoll() (in module select)](library/select#select.devpoll) * [DevpollSelector (class in selectors)](library/selectors#selectors.DevpollSelector) * [dgettext() (in module gettext)](library/gettext#gettext.dgettext) + [(in module locale)](library/locale#locale.dgettext) * [Dialect (class in csv)](library/csv#csv.Dialect) * [dialect (csv.csvreader attribute)](library/csv#csv.csvreader.dialect) + [(csv.csvwriter attribute)](library/csv#csv.csvwriter.dialect) * [Dialog (class in msilib)](library/msilib#msilib.Dialog) + [(class in tkinter.commondialog)](library/dialog#tkinter.commondialog.Dialog) + [(class in tkinter.simpledialog)](library/dialog#tkinter.simpledialog.Dialog) * [dict (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-dict) + [(built-in class)](library/stdtypes#dict) * [Dict (class in ast)](library/ast#ast.Dict) + [(class in typing)](library/typing#typing.Dict) * [dict() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.dict) | * [DICT\_MERGE (opcode)](library/dis#opcode-DICT_MERGE) * [DICT\_UPDATE (opcode)](library/dis#opcode-DICT_UPDATE) * [DictComp (class in ast)](library/ast#ast.DictComp) * [dictConfig() (in module logging.config)](library/logging.config#logging.config.dictConfig) * [**dictionary**](glossary#term-dictionary) + [comprehensions](reference/expressions#index-17) + [display](reference/expressions#index-17) + [object](c-api/dict#index-0), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-30), [[3]](reference/datamodel#index-45), [[4]](reference/datamodel#index-76), [[5]](reference/expressions#index-17), [[6]](reference/expressions#index-42), [[7]](reference/simple_stmts#index-11) + [type, operations on](library/stdtypes#index-50) * [**dictionary comprehension**](glossary#term-dictionary-comprehension) * [**dictionary view**](glossary#term-dictionary-view) * [DictReader (class in csv)](library/csv#csv.DictReader) * [DictWriter (class in csv)](library/csv#csv.DictWriter) * [diff\_bytes() (in module difflib)](library/difflib#difflib.diff_bytes) * [diff\_files (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.diff_files) * [Differ (class in difflib)](library/difflib#difflib.Differ) * [difference() (frozenset method)](library/stdtypes#frozenset.difference) * [difference\_update() (frozenset method)](library/stdtypes#frozenset.difference_update) * [difflib (module)](library/difflib#module-difflib) * [digest() (hashlib.hash method)](library/hashlib#hashlib.hash.digest) + [(hashlib.shake method)](library/hashlib#hashlib.shake.digest) + [(hmac.HMAC method)](library/hmac#hmac.HMAC.digest) + [(in module hmac)](library/hmac#hmac.digest) * [digest\_size (hmac.HMAC attribute)](library/hmac#hmac.HMAC.digest_size) * [digit() (in module unicodedata)](library/unicodedata#unicodedata.digit) * [digits (in module string)](library/string#string.digits) * [dir() (built-in function)](library/functions#dir) + [(ftplib.FTP method)](library/ftplib#ftplib.FTP.dir) * [dircmp (class in filecmp)](library/filecmp#filecmp.dircmp) * directory + [changing](library/os#index-20) + [creating](library/os#index-22) + [deleting](library/os#index-23), [[1]](library/shutil#index-1) + [site-packages](library/site#index-1) + [traversal](library/os#index-25), [[1]](library/os#index-26) + [walking](library/os#index-25), [[1]](library/os#index-26) * [Directory (class in msilib)](library/msilib#msilib.Directory) + [(class in tkinter.filedialog)](library/dialog#tkinter.filedialog.Directory) * directory ... + [compileall command line option](library/compileall#cmdoption-compileall-arg-directory) * [directory\_created() (built-in function)](distutils/builtdist#directory_created) * [DirEntry (class in os)](library/os#os.DirEntry) * [DirList (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.DirList) * [dirname() (in module os.path)](library/os.path#os.path.dirname) * [dirs\_double\_event() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.dirs_double_event) * [dirs\_select\_event() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.dirs_select_event) * [DirSelectBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.DirSelectBox) * [DirSelectDialog (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.DirSelectDialog) * [DirsOnSysPath (class in test.support)](library/test#test.support.DirsOnSysPath) * [DirTree (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.DirTree) * [dis (module)](library/dis#module-dis) * [dis() (dis.Bytecode method)](library/dis#dis.Bytecode.dis) + [(in module dis)](library/dis#dis.dis) + [(in module pickletools)](library/pickletools#pickletools.dis) * [disable (pdb command)](library/pdb#pdbcommand-disable) * [disable() (bdb.Breakpoint method)](library/bdb#bdb.Breakpoint.disable) + [(in module faulthandler)](library/faulthandler#faulthandler.disable) + [(in module gc)](library/gc#gc.disable) + [(in module logging)](library/logging#logging.disable) + [(profile.Profile method)](library/profile#profile.Profile.disable) * [disable\_faulthandler() (in module test.support)](library/test#test.support.disable_faulthandler) * [disable\_gc() (in module test.support)](library/test#test.support.disable_gc) * [disable\_interspersed\_args() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.disable_interspersed_args) * [DisableReflectionKey() (in module winreg)](library/winreg#winreg.DisableReflectionKey) * [disassemble() (in module dis)](library/dis#dis.disassemble) * [discard (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.discard) * [discard() (frozenset method)](library/stdtypes#frozenset.discard) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.discard) + [(mailbox.MH method)](library/mailbox#mailbox.MH.discard) * [discard\_buffers() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.discard_buffers) * [disco() (in module dis)](library/dis#dis.disco) * [discover() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.discover) * [disk\_usage() (in module shutil)](library/shutil#shutil.disk_usage) * [dispatch\_call() (bdb.Bdb method)](library/bdb#bdb.Bdb.dispatch_call) * [dispatch\_exception() (bdb.Bdb method)](library/bdb#bdb.Bdb.dispatch_exception) * [dispatch\_line() (bdb.Bdb method)](library/bdb#bdb.Bdb.dispatch_line) * [dispatch\_return() (bdb.Bdb method)](library/bdb#bdb.Bdb.dispatch_return) * [dispatch\_table (pickle.Pickler attribute)](library/pickle#pickle.Pickler.dispatch_table) * [dispatcher (class in asyncore)](library/asyncore#asyncore.dispatcher) * [dispatcher\_with\_send (class in asyncore)](library/asyncore#asyncore.dispatcher_with_send) * [DISPLAY](library/tkinter#index-0) * display + [dictionary](reference/expressions#index-17) + [list](reference/expressions#index-15) + [set](reference/expressions#index-16) * [display (pdb command)](library/pdb#pdbcommand-display) * [display\_name (email.headerregistry.Address attribute)](library/email.headerregistry#email.headerregistry.Address.display_name) + [(email.headerregistry.Group attribute)](library/email.headerregistry#email.headerregistry.Group.display_name) * [displayhook() (in module sys)](library/sys#sys.displayhook) * [dist() (in module math)](library/math#math.dist) * [distance() (in module turtle)](library/turtle#turtle.distance) * [distb() (in module dis)](library/dis#dis.distb) * [Distribution (class in distutils.core)](distutils/apiref#distutils.core.Distribution) * [distutils (module)](library/distutils#module-distutils) * [distutils.archive\_util (module)](distutils/apiref#module-distutils.archive_util) * [distutils.bcppcompiler (module)](distutils/apiref#module-distutils.bcppcompiler) * [distutils.ccompiler (module)](distutils/apiref#module-distutils.ccompiler) * [distutils.cmd (module)](distutils/apiref#module-distutils.cmd) * [distutils.command (module)](distutils/apiref#module-distutils.command) * [distutils.command.bdist (module)](distutils/apiref#module-distutils.command.bdist) * [distutils.command.bdist\_dumb (module)](distutils/apiref#module-distutils.command.bdist_dumb) * [distutils.command.bdist\_msi (module)](distutils/apiref#module-distutils.command.bdist_msi) * [distutils.command.bdist\_packager (module)](distutils/apiref#module-distutils.command.bdist_packager) * [distutils.command.bdist\_rpm (module)](distutils/apiref#module-distutils.command.bdist_rpm) * [distutils.command.bdist\_wininst (module)](distutils/apiref#module-distutils.command.bdist_wininst) * [distutils.command.build (module)](distutils/apiref#module-distutils.command.build) * [distutils.command.build\_clib (module)](distutils/apiref#module-distutils.command.build_clib) * [distutils.command.build\_ext (module)](distutils/apiref#module-distutils.command.build_ext) * [distutils.command.build\_py (module)](distutils/apiref#module-distutils.command.build_py) * [distutils.command.build\_scripts (module)](distutils/apiref#module-distutils.command.build_scripts) * [distutils.command.check (module)](distutils/apiref#module-distutils.command.check) * [distutils.command.clean (module)](distutils/apiref#module-distutils.command.clean) * [distutils.command.config (module)](distutils/apiref#module-distutils.command.config) * [distutils.command.install (module)](distutils/apiref#module-distutils.command.install) * [distutils.command.install\_data (module)](distutils/apiref#module-distutils.command.install_data) * [distutils.command.install\_headers (module)](distutils/apiref#module-distutils.command.install_headers) * [distutils.command.install\_lib (module)](distutils/apiref#module-distutils.command.install_lib) * [distutils.command.install\_scripts (module)](distutils/apiref#module-distutils.command.install_scripts) * [distutils.command.register (module)](distutils/apiref#module-distutils.command.register) * [distutils.command.sdist (module)](distutils/apiref#module-distutils.command.sdist) * [distutils.core (module)](distutils/apiref#module-distutils.core) * [distutils.cygwinccompiler (module)](distutils/apiref#module-distutils.cygwinccompiler) * [distutils.debug (module)](distutils/apiref#module-distutils.debug) * [distutils.dep\_util (module)](distutils/apiref#module-distutils.dep_util) * [distutils.dir\_util (module)](distutils/apiref#module-distutils.dir_util) * [distutils.dist (module)](distutils/apiref#module-distutils.dist) * [distutils.errors (module)](distutils/apiref#module-distutils.errors) * [distutils.extension (module)](distutils/apiref#module-distutils.extension) * [distutils.fancy\_getopt (module)](distutils/apiref#module-distutils.fancy_getopt) * [distutils.file\_util (module)](distutils/apiref#module-distutils.file_util) * [distutils.filelist (module)](distutils/apiref#module-distutils.filelist) * [distutils.log (module)](distutils/apiref#module-distutils.log) * [distutils.msvccompiler (module)](distutils/apiref#module-distutils.msvccompiler) * [distutils.spawn (module)](distutils/apiref#module-distutils.spawn) * [distutils.sysconfig (module)](distutils/apiref#module-distutils.sysconfig) * [distutils.text\_file (module)](distutils/apiref#module-distutils.text_file) * [distutils.unixccompiler (module)](distutils/apiref#module-distutils.unixccompiler) * [distutils.util (module)](distutils/apiref#module-distutils.util) * [distutils.version (module)](distutils/apiref#module-distutils.version) * [DISTUTILS\_DEBUG](distutils/setupscript#index-0) * [Div (class in ast)](library/ast#ast.Div) * [divide() (decimal.Context method)](library/decimal#decimal.Context.divide) * [divide\_int() (decimal.Context method)](library/decimal#decimal.Context.divide_int) * [division](reference/expressions#index-67) * [DivisionByZero (class in decimal)](library/decimal#decimal.DivisionByZero) * divmod + [built-in function](c-api/number#index-0), [[1]](reference/datamodel#index-96), [[2]](reference/datamodel#index-97) * [divmod() (built-in function)](library/functions#divmod) + [(decimal.Context method)](library/decimal#decimal.Context.divmod) * [DllCanUnloadNow() (in module ctypes)](library/ctypes#ctypes.DllCanUnloadNow) * [DllGetClassObject() (in module ctypes)](library/ctypes#ctypes.DllGetClassObject) * [dllhandle (in module sys)](library/sys#sys.dllhandle) * [dnd\_start() (in module tkinter.dnd)](library/tkinter.dnd#tkinter.dnd.dnd_start) * [DndHandler (class in tkinter.dnd)](library/tkinter.dnd#tkinter.dnd.DndHandler) * [dngettext() (in module gettext)](library/gettext#gettext.dngettext) * [dnpgettext() (in module gettext)](library/gettext#gettext.dnpgettext) * [do\_clear() (bdb.Bdb method)](library/bdb#bdb.Bdb.do_clear) * [do\_command() (curses.textpad.Textbox method)](library/curses#curses.textpad.Textbox.do_command) * [do\_GET() (http.server.SimpleHTTPRequestHandler method)](library/http.server#http.server.SimpleHTTPRequestHandler.do_GET) * [do\_handshake() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.do_handshake) * [do\_HEAD() (http.server.SimpleHTTPRequestHandler method)](library/http.server#http.server.SimpleHTTPRequestHandler.do_HEAD) * [do\_POST() (http.server.CGIHTTPRequestHandler method)](library/http.server#http.server.CGIHTTPRequestHandler.do_POST) * [doc (json.JSONDecodeError attribute)](library/json#json.JSONDecodeError.doc) * [doc\_header (cmd.Cmd attribute)](library/cmd#cmd.Cmd.doc_header) * [DocCGIXMLRPCRequestHandler (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler) * [DocFileSuite() (in module doctest)](library/doctest#doctest.DocFileSuite) * [doClassCleanups() (unittest.TestCase class method)](library/unittest#unittest.TestCase.doClassCleanups) * [doCleanups() (unittest.TestCase method)](library/unittest#unittest.TestCase.doCleanups) * [docmd() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.docmd) * [docstring](reference/compound_stmts#index-31), [**[1]**](glossary#term-docstring) + [(doctest.DocTest attribute)](library/doctest#doctest.DocTest.docstring) * [docstrings](tutorial/controlflow#index-1), [[1]](tutorial/controlflow#index-4) * [DocTest (class in doctest)](library/doctest#doctest.DocTest) * [doctest (module)](library/doctest#module-doctest) * [DocTestFailure](library/doctest#doctest.DocTestFailure) * [DocTestFinder (class in doctest)](library/doctest#doctest.DocTestFinder) * [DocTestParser (class in doctest)](library/doctest#doctest.DocTestParser) * [DocTestRunner (class in doctest)](library/doctest#doctest.DocTestRunner) * [DocTestSuite() (in module doctest)](library/doctest#doctest.DocTestSuite) * [doctype() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.doctype) * documentation + [generation](library/pydoc#index-0) + [online](library/pydoc#index-0) * [documentation string](reference/datamodel#index-58) * [documentation strings](tutorial/controlflow#index-1), [[1]](tutorial/controlflow#index-4) * [documentElement (xml.dom.Document attribute)](library/xml.dom#xml.dom.Document.documentElement) * [DocXMLRPCRequestHandler (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.DocXMLRPCRequestHandler) * [DocXMLRPCServer (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.DocXMLRPCServer) * [domain (email.headerregistry.Address attribute)](library/email.headerregistry#email.headerregistry.Address.domain) + [(tracemalloc.DomainFilter attribute)](library/tracemalloc#tracemalloc.DomainFilter.domain) + [(tracemalloc.Filter attribute)](library/tracemalloc#tracemalloc.Filter.domain) + [(tracemalloc.Trace attribute)](library/tracemalloc#tracemalloc.Trace.domain) * [domain\_initial\_dot (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.domain_initial_dot) * [domain\_return\_ok() (http.cookiejar.CookiePolicy method)](library/http.cookiejar#http.cookiejar.CookiePolicy.domain_return_ok) * [domain\_specified (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.domain_specified) * [DomainFilter (class in tracemalloc)](library/tracemalloc#tracemalloc.DomainFilter) * [DomainLiberal (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainLiberal) * [DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainRFC2965Match) * [DomainStrict (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrict) * [DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrictNoDots) * [DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrictNonDomain) * [DOMEventStream (class in xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.DOMEventStream) * [DOMException](library/xml.dom#xml.dom.DOMException) * [doModuleCleanups() (in module unittest)](library/unittest#unittest.doModuleCleanups) * [DomstringSizeErr](library/xml.dom#xml.dom.DomstringSizeErr) * [done() (asyncio.Future method)](library/asyncio-future#asyncio.Future.done) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.done) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.done) + [(graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.done) + [(in module turtle)](library/turtle#turtle.done) + [(xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.done) * [DONT\_ACCEPT\_BLANKLINE (in module doctest)](library/doctest#doctest.DONT_ACCEPT_BLANKLINE) * [DONT\_ACCEPT\_TRUE\_FOR\_1 (in module doctest)](library/doctest#doctest.DONT_ACCEPT_TRUE_FOR_1) * [dont\_write\_bytecode (in module sys)](library/sys#sys.dont_write_bytecode) * [doRollover() (logging.handlers.RotatingFileHandler method)](library/logging.handlers#logging.handlers.RotatingFileHandler.doRollover) + [(logging.handlers.TimedRotatingFileHandler method)](library/logging.handlers#logging.handlers.TimedRotatingFileHandler.doRollover) * [DOT (in module token)](library/token#token.DOT) * [dot() (in module turtle)](library/turtle#turtle.dot) * [DOTALL (in module re)](library/re#re.DOTALL) * [doublequote (csv.Dialect attribute)](library/csv#csv.Dialect.doublequote) * [DOUBLESLASH (in module token)](library/token#token.DOUBLESLASH) * [DOUBLESLASHEQUAL (in module token)](library/token#token.DOUBLESLASHEQUAL) * [DOUBLESTAR (in module token)](library/token#token.DOUBLESTAR) * [DOUBLESTAREQUAL (in module token)](library/token#token.DOUBLESTAREQUAL) * [doupdate() (in module curses)](library/curses#curses.doupdate) * [down (pdb command)](library/pdb#pdbcommand-down) * [down() (in module turtle)](library/turtle#turtle.down) * [dpgettext() (in module gettext)](library/gettext#gettext.dpgettext) * [drain() (asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.drain) * [drop\_whitespace (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.drop_whitespace) * [dropwhile() (in module itertools)](library/itertools#itertools.dropwhile) * [dst() (datetime.datetime method)](library/datetime#datetime.datetime.dst) + [(datetime.time method)](library/datetime#datetime.time.dst) + [(datetime.timezone method)](library/datetime#datetime.timezone.dst) + [(datetime.tzinfo method)](library/datetime#datetime.tzinfo.dst) * [DTDHandler (class in xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.DTDHandler) * [**duck-typing**](glossary#term-duck-typing) * [DumbWriter (class in formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.DumbWriter) * [dump() (in module ast)](library/ast#ast.dump) + [(in module json)](library/json#json.dump) + [(in module marshal)](library/marshal#marshal.dump) + [(in module pickle)](library/pickle#pickle.dump) + [(in module plistlib)](library/plistlib#plistlib.dump) + [(in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.dump) + [(pickle.Pickler method)](library/pickle#pickle.Pickler.dump) + [(tracemalloc.Snapshot method)](library/tracemalloc#tracemalloc.Snapshot.dump) * [dump\_stats() (profile.Profile method)](library/profile#profile.Profile.dump_stats) + [(pstats.Stats method)](library/profile#pstats.Stats.dump_stats) * [dump\_traceback() (in module faulthandler)](library/faulthandler#faulthandler.dump_traceback) * [dump\_traceback\_later() (in module faulthandler)](library/faulthandler#faulthandler.dump_traceback_later) * [dumps() (in module json)](library/json#json.dumps) + [(in module marshal)](library/marshal#marshal.dumps) + [(in module pickle)](library/pickle#pickle.dumps) + [(in module plistlib)](library/plistlib#plistlib.dumps) + [(in module xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.dumps) * [dup() (in module os)](library/os#os.dup) + [(socket.socket method)](library/socket#socket.socket.dup) * [dup2() (in module os)](library/os#os.dup2) * [DUP\_TOP (opcode)](library/dis#opcode-DUP_TOP) * [DUP\_TOP\_TWO (opcode)](library/dis#opcode-DUP_TOP_TWO) * [DuplicateOptionError](library/configparser#configparser.DuplicateOptionError) * [DuplicateSectionError](library/configparser#configparser.DuplicateSectionError) * [dwFlags (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.dwFlags) * [DynamicClassAttribute() (in module types)](library/types#types.DynamicClassAttribute) | E - | | | | --- | --- | | * e + [in numeric literal](reference/lexical_analysis#index-28) * [e (in module cmath)](library/cmath#cmath.e) + [(in module math)](library/math#math.e) * [E2BIG (in module errno)](library/errno#errno.E2BIG) * [EACCES (in module errno)](library/errno#errno.EACCES) * [EADDRINUSE (in module errno)](library/errno#errno.EADDRINUSE) * [EADDRNOTAVAIL (in module errno)](library/errno#errno.EADDRNOTAVAIL) * [EADV (in module errno)](library/errno#errno.EADV) * [EAFNOSUPPORT (in module errno)](library/errno#errno.EAFNOSUPPORT) * [**EAFP**](glossary#term-eafp) * [EAGAIN (in module errno)](library/errno#errno.EAGAIN) * [EALREADY (in module errno)](library/errno#errno.EALREADY) * [east\_asian\_width() (in module unicodedata)](library/unicodedata#unicodedata.east_asian_width) * [EBADE (in module errno)](library/errno#errno.EBADE) * [EBADF (in module errno)](library/errno#errno.EBADF) * [EBADFD (in module errno)](library/errno#errno.EBADFD) * [EBADMSG (in module errno)](library/errno#errno.EBADMSG) * [EBADR (in module errno)](library/errno#errno.EBADR) * [EBADRQC (in module errno)](library/errno#errno.EBADRQC) * [EBADSLT (in module errno)](library/errno#errno.EBADSLT) * [EBFONT (in module errno)](library/errno#errno.EBFONT) * [EBUSY (in module errno)](library/errno#errno.EBUSY) * [ECHILD (in module errno)](library/errno#errno.ECHILD) * [echo() (in module curses)](library/curses#curses.echo) * [echochar() (curses.window method)](library/curses#curses.window.echochar) * [ECHRNG (in module errno)](library/errno#errno.ECHRNG) * [ECOMM (in module errno)](library/errno#errno.ECOMM) * [ECONNABORTED (in module errno)](library/errno#errno.ECONNABORTED) * [ECONNREFUSED (in module errno)](library/errno#errno.ECONNREFUSED) * [ECONNRESET (in module errno)](library/errno#errno.ECONNRESET) * [EDEADLK (in module errno)](library/errno#errno.EDEADLK) * [EDEADLOCK (in module errno)](library/errno#errno.EDEADLOCK) * [EDESTADDRREQ (in module errno)](library/errno#errno.EDESTADDRREQ) * [edit() (curses.textpad.Textbox method)](library/curses#curses.textpad.Textbox.edit) * [EDOM (in module errno)](library/errno#errno.EDOM) * [EDOTDOT (in module errno)](library/errno#errno.EDOTDOT) * [EDQUOT (in module errno)](library/errno#errno.EDQUOT) * [EEXIST (in module errno)](library/errno#errno.EEXIST) * [EFAULT (in module errno)](library/errno#errno.EFAULT) * [EFBIG (in module errno)](library/errno#errno.EFBIG) * [effective() (in module bdb)](library/bdb#bdb.effective) * [ehlo() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.ehlo) * [ehlo\_or\_helo\_if\_needed() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.ehlo_or_helo_if_needed) * [EHOSTDOWN (in module errno)](library/errno#errno.EHOSTDOWN) * [EHOSTUNREACH (in module errno)](library/errno#errno.EHOSTUNREACH) * [EIDRM (in module errno)](library/errno#errno.EIDRM) * [EILSEQ (in module errno)](library/errno#errno.EILSEQ) * [EINPROGRESS (in module errno)](library/errno#errno.EINPROGRESS) * [EINTR (in module errno)](library/errno#errno.EINTR) * [EINVAL (in module errno)](library/errno#errno.EINVAL) * [EIO (in module errno)](library/errno#errno.EIO) * [EISCONN (in module errno)](library/errno#errno.EISCONN) * [EISDIR (in module errno)](library/errno#errno.EISDIR) * [EISNAM (in module errno)](library/errno#errno.EISNAM) * [EL2HLT (in module errno)](library/errno#errno.EL2HLT) * [EL2NSYNC (in module errno)](library/errno#errno.EL2NSYNC) * [EL3HLT (in module errno)](library/errno#errno.EL3HLT) * [EL3RST (in module errno)](library/errno#errno.EL3RST) * [Element (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.Element) * [element\_create() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.element_create) * [element\_names() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.element_names) * [element\_options() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.element_options) * [ElementDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.ElementDeclHandler) * [elements() (collections.Counter method)](library/collections#collections.Counter.elements) * [ElementTree (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree) * [ELIBACC (in module errno)](library/errno#errno.ELIBACC) * [ELIBBAD (in module errno)](library/errno#errno.ELIBBAD) * [ELIBEXEC (in module errno)](library/errno#errno.ELIBEXEC) * [ELIBMAX (in module errno)](library/errno#errno.ELIBMAX) * [ELIBSCN (in module errno)](library/errno#errno.ELIBSCN) * elif + [keyword](reference/compound_stmts#index-3) * [Ellinghouse, Lance](library/uu#index-1) * Ellipsis + [object](reference/datamodel#index-8) * [Ellipsis (built-in variable)](library/constants#Ellipsis) * [ELLIPSIS (in module doctest)](library/doctest#doctest.ELLIPSIS) + [(in module token)](library/token#token.ELLIPSIS) * [ELNRNG (in module errno)](library/errno#errno.ELNRNG) * [ELOOP (in module errno)](library/errno#errno.ELOOP) * else + [conditional expression](reference/expressions#index-87) + [dangling](reference/compound_stmts#index-2) + [keyword](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-13), [[2]](reference/compound_stmts#index-3), [[3]](reference/compound_stmts#index-4), [[4]](reference/compound_stmts#index-6), [[5]](reference/simple_stmts#index-31) * [email (module)](library/email#module-email) * [email.charset (module)](library/email.charset#module-email.charset) * [email.contentmanager (module)](library/email.contentmanager#module-email.contentmanager) * [email.encoders (module)](library/email.encoders#module-email.encoders) * [email.errors (module)](library/email.errors#module-email.errors) * [email.generator (module)](library/email.generator#module-email.generator) * [email.header (module)](library/email.header#module-email.header) * [email.headerregistry (module)](library/email.headerregistry#module-email.headerregistry) * [email.iterators (module)](library/email.iterators#module-email.iterators) * [email.message (module)](library/email.message#module-email.message) * [email.mime (module)](library/email.mime#module-email.mime) * [email.parser (module)](library/email.parser#module-email.parser) * [email.policy (module)](library/email.policy#module-email.policy) * [email.utils (module)](library/email.utils#module-email.utils) * [EmailMessage (class in email.message)](library/email.message#email.message.EmailMessage) * [EmailPolicy (class in email.policy)](library/email.policy#email.policy.EmailPolicy) * [EMFILE (in module errno)](library/errno#errno.EMFILE) * [emit() (logging.FileHandler method)](library/logging.handlers#logging.FileHandler.emit) + [(logging.Handler method)](library/logging#logging.Handler.emit) + [(logging.handlers.BufferingHandler method)](library/logging.handlers#logging.handlers.BufferingHandler.emit) + [(logging.handlers.DatagramHandler method)](library/logging.handlers#logging.handlers.DatagramHandler.emit) + [(logging.handlers.HTTPHandler method)](library/logging.handlers#logging.handlers.HTTPHandler.emit) + [(logging.handlers.NTEventLogHandler method)](library/logging.handlers#logging.handlers.NTEventLogHandler.emit) + [(logging.handlers.QueueHandler method)](library/logging.handlers#logging.handlers.QueueHandler.emit) + [(logging.handlers.RotatingFileHandler method)](library/logging.handlers#logging.handlers.RotatingFileHandler.emit) + [(logging.handlers.SMTPHandler method)](library/logging.handlers#logging.handlers.SMTPHandler.emit) + [(logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.emit) + [(logging.handlers.SysLogHandler method)](library/logging.handlers#logging.handlers.SysLogHandler.emit) + [(logging.handlers.TimedRotatingFileHandler method)](library/logging.handlers#logging.handlers.TimedRotatingFileHandler.emit) + [(logging.handlers.WatchedFileHandler method)](library/logging.handlers#logging.handlers.WatchedFileHandler.emit) + [(logging.NullHandler method)](library/logging.handlers#logging.NullHandler.emit) + [(logging.StreamHandler method)](library/logging.handlers#logging.StreamHandler.emit) * [EMLINK (in module errno)](library/errno#errno.EMLINK) * [Empty](library/queue#queue.Empty) * empty + [list](reference/expressions#index-15) + [tuple](reference/datamodel#index-20), [[1]](reference/expressions#index-9) * [empty (inspect.Parameter attribute)](library/inspect#inspect.Parameter.empty) + [(inspect.Signature attribute)](library/inspect#inspect.Signature.empty) * [empty() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.empty) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.empty) + [(multiprocessing.SimpleQueue method)](library/multiprocessing#multiprocessing.SimpleQueue.empty) + [(queue.Queue method)](library/queue#queue.Queue.empty) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.empty) + [(sched.scheduler method)](library/sched#sched.scheduler.empty) * [EMPTY\_NAMESPACE (in module xml.dom)](library/xml.dom#xml.dom.EMPTY_NAMESPACE) * [emptyline() (cmd.Cmd method)](library/cmd#cmd.Cmd.emptyline) * [EMSGSIZE (in module errno)](library/errno#errno.EMSGSIZE) * [EMULTIHOP (in module errno)](library/errno#errno.EMULTIHOP) * [enable (pdb command)](library/pdb#pdbcommand-enable) * [enable() (bdb.Breakpoint method)](library/bdb#bdb.Breakpoint.enable) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.enable) + [(in module cgitb)](library/cgitb#cgitb.enable) + [(in module faulthandler)](library/faulthandler#faulthandler.enable) + [(in module gc)](library/gc#gc.enable) + [(profile.Profile method)](library/profile#profile.Profile.enable) * [enable\_callback\_tracebacks() (in module sqlite3)](library/sqlite3#sqlite3.enable_callback_tracebacks) * [enable\_interspersed\_args() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.enable_interspersed_args) * [enable\_load\_extension() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.enable_load_extension) * [enable\_traversal() (tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.enable_traversal) * [ENABLE\_USER\_SITE (in module site)](library/site#site.ENABLE_USER_SITE) * [EnableControlFlowGuard](https://docs.python.org/3.9/whatsnew/changelog.html#index-6) * [EnableReflectionKey() (in module winreg)](library/winreg#winreg.EnableReflectionKey) * [ENAMETOOLONG (in module errno)](library/errno#errno.ENAMETOOLONG) * [ENAVAIL (in module errno)](library/errno#errno.ENAVAIL) * [enclose() (curses.window method)](library/curses#curses.window.enclose) * encode + [Codecs](library/codecs#index-0) * [encode (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.encode) * [encode() (codecs.Codec method)](library/codecs#codecs.Codec.encode) + [(codecs.IncrementalEncoder method)](library/codecs#codecs.IncrementalEncoder.encode) + [(email.header.Header method)](library/email.header#email.header.Header.encode) + [(in module base64)](library/base64#base64.encode) + [(in module codecs)](library/codecs#codecs.encode) + [(in module quopri)](library/quopri#quopri.encode) + [(in module uu)](library/uu#uu.encode) + [(json.JSONEncoder method)](library/json#json.JSONEncoder.encode) + [(str method)](library/stdtypes#str.encode) + [(xmlrpc.client.Binary method)](library/xmlrpc.client#xmlrpc.client.Binary.encode) + [(xmlrpc.client.DateTime method)](library/xmlrpc.client#xmlrpc.client.DateTime.encode) * [encode\_7or8bit() (in module email.encoders)](library/email.encoders#email.encoders.encode_7or8bit) * [encode\_base64() (in module email.encoders)](library/email.encoders#email.encoders.encode_base64) * [encode\_noop() (in module email.encoders)](library/email.encoders#email.encoders.encode_noop) * [encode\_quopri() (in module email.encoders)](library/email.encoders#email.encoders.encode_quopri) * [encode\_rfc2231() (in module email.utils)](library/email.utils#email.utils.encode_rfc2231) * [encodebytes() (in module base64)](library/base64#base64.encodebytes) * [EncodedFile() (in module codecs)](library/codecs#codecs.EncodedFile) * [encodePriority() (logging.handlers.SysLogHandler method)](library/logging.handlers#logging.handlers.SysLogHandler.encodePriority) * [encodestring() (in module quopri)](library/quopri#quopri.encodestring) * encoding + [base64](library/base64#index-0) + [quoted-printable](library/quopri#index-0) * [encoding (curses.window attribute)](library/curses#curses.window.encoding) * [ENCODING (in module tarfile)](library/tarfile#tarfile.ENCODING) + [(in module token)](library/token#token.ENCODING) * [encoding (io.TextIOBase attribute)](library/io#io.TextIOBase.encoding) + [(UnicodeError attribute)](library/exceptions#UnicodeError.encoding) * [encoding declarations (source file)](reference/lexical_analysis#index-5) * [encodings.idna (module)](library/codecs#module-encodings.idna) * [encodings.mbcs (module)](library/codecs#module-encodings.mbcs) * [encodings.utf\_8\_sig (module)](library/codecs#module-encodings.utf_8_sig) * [encodings\_map (in module mimetypes)](library/mimetypes#mimetypes.encodings_map) + [(mimetypes.MimeTypes attribute)](library/mimetypes#mimetypes.MimeTypes.encodings_map) * [end (UnicodeError attribute)](library/exceptions#UnicodeError.end) * [end() (re.Match method)](library/re#re.Match.end) + [(xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.end) * [END\_ASYNC\_FOR (opcode)](library/dis#opcode-END_ASYNC_FOR) * [end\_col\_offset (ast.AST attribute)](library/ast#ast.AST.end_col_offset) * [end\_fill() (in module turtle)](library/turtle#turtle.end_fill) * [end\_headers() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.end_headers) * [end\_lineno (ast.AST attribute)](library/ast#ast.AST.end_lineno) * [end\_ns() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.end_ns) * [end\_paragraph() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.end_paragraph) * [end\_poly() (in module turtle)](library/turtle#turtle.end_poly) * [EndCdataSectionHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.EndCdataSectionHandler) * [EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler) * [endDocument() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.endDocument) * [endElement() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.endElement) * [EndElementHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.EndElementHandler) * [endElementNS() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.endElementNS) * [endheaders() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.endheaders) * [ENDMARKER (in module token)](library/token#token.ENDMARKER) * [EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.EndNamespaceDeclHandler) * [endpos (re.Match attribute)](library/re#re.Match.endpos) * [endPrefixMapping() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.endPrefixMapping) * [endswith() (bytearray method)](library/stdtypes#bytearray.endswith) + [(bytes method)](library/stdtypes#bytes.endswith) + [(str method)](library/stdtypes#str.endswith) * [endwin() (in module curses)](library/curses#curses.endwin) * [ENETDOWN (in module errno)](library/errno#errno.ENETDOWN) * [ENETRESET (in module errno)](library/errno#errno.ENETRESET) * [ENETUNREACH (in module errno)](library/errno#errno.ENETUNREACH) * [ENFILE (in module errno)](library/errno#errno.ENFILE) * [ENOANO (in module errno)](library/errno#errno.ENOANO) * [ENOBUFS (in module errno)](library/errno#errno.ENOBUFS) * [ENOCSI (in module errno)](library/errno#errno.ENOCSI) * [ENODATA (in module errno)](library/errno#errno.ENODATA) * [ENODEV (in module errno)](library/errno#errno.ENODEV) * [ENOENT (in module errno)](library/errno#errno.ENOENT) * [ENOEXEC (in module errno)](library/errno#errno.ENOEXEC) * [ENOLCK (in module errno)](library/errno#errno.ENOLCK) * [ENOLINK (in module errno)](library/errno#errno.ENOLINK) * [ENOMEM (in module errno)](library/errno#errno.ENOMEM) * [ENOMSG (in module errno)](library/errno#errno.ENOMSG) * [ENONET (in module errno)](library/errno#errno.ENONET) * [ENOPKG (in module errno)](library/errno#errno.ENOPKG) * [ENOPROTOOPT (in module errno)](library/errno#errno.ENOPROTOOPT) * [ENOSPC (in module errno)](library/errno#errno.ENOSPC) * [ENOSR (in module errno)](library/errno#errno.ENOSR) * [ENOSTR (in module errno)](library/errno#errno.ENOSTR) * [ENOSYS (in module errno)](library/errno#errno.ENOSYS) * [ENOTBLK (in module errno)](library/errno#errno.ENOTBLK) * [ENOTCONN (in module errno)](library/errno#errno.ENOTCONN) * [ENOTDIR (in module errno)](library/errno#errno.ENOTDIR) * [ENOTEMPTY (in module errno)](library/errno#errno.ENOTEMPTY) * [ENOTNAM (in module errno)](library/errno#errno.ENOTNAM) * [ENOTSOCK (in module errno)](library/errno#errno.ENOTSOCK) * [ENOTTY (in module errno)](library/errno#errno.ENOTTY) * [ENOTUNIQ (in module errno)](library/errno#errno.ENOTUNIQ) * [enqueue() (logging.handlers.QueueHandler method)](library/logging.handlers#logging.handlers.QueueHandler.enqueue) * [enqueue\_sentinel() (logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.enqueue_sentinel) * [ensure\_directories() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.ensure_directories) * [ensure\_future() (in module asyncio)](library/asyncio-future#asyncio.ensure_future) * [ensurepip (module)](library/ensurepip#module-ensurepip) * [enter() (sched.scheduler method)](library/sched#sched.scheduler.enter) * [enter\_async\_context() (contextlib.AsyncExitStack method)](library/contextlib#contextlib.AsyncExitStack.enter_async_context) * [enter\_context() (contextlib.ExitStack method)](library/contextlib#contextlib.ExitStack.enter_context) * [enterabs() (sched.scheduler method)](library/sched#sched.scheduler.enterabs) * [entities (xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.entities) * [EntityDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.EntityDeclHandler) * [entitydefs (in module html.entities)](library/html.entities#html.entities.entitydefs) * [EntityResolver (class in xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.EntityResolver) * [Enum (class in enum)](library/enum#enum.Enum) * [enum (module)](library/enum#module-enum) * [enum\_certificates() (in module ssl)](library/ssl#ssl.enum_certificates) * [enum\_crls() (in module ssl)](library/ssl#ssl.enum_crls) * [enumerate() (built-in function)](library/functions#enumerate) + [(in module threading)](library/threading#threading.enumerate) * [EnumKey() (in module winreg)](library/winreg#winreg.EnumKey) * [EnumValue() (in module winreg)](library/winreg#winreg.EnumValue) * [EnvBuilder (class in venv)](library/venv#venv.EnvBuilder) * [environ (in module os)](library/os#os.environ) + [(in module posix)](library/posix#posix.environ) * [environb (in module os)](library/os#os.environb) * [environment](reference/executionmodel#index-8) * environment variable + [APPDATA](https://docs.python.org/3.9/whatsnew/2.6.html#index-5) + [AUDIODEV](library/ossaudiodev#index-1) + [BROWSER](library/webbrowser#index-0), [[1]](library/webbrowser#index-1) + [CC](https://docs.python.org/3.9/whatsnew/2.3.html#index-24) + [CFLAGS](install/index#index-10), [[1]](install/index#index-9), [[2]](https://docs.python.org/3.9/whatsnew/2.3.html#index-25) + [COLS](library/curses#index-4), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-32) + [COLUMNS](library/curses#index-6), [[1]](library/curses#index-8) + [COMSPEC](library/os#index-37), [[1]](library/subprocess#index-2) + [CPP](https://docs.python.org/3.9/whatsnew/2.3.html#index-26) + [CPPFLAGS](https://docs.python.org/3.9/whatsnew/2.3.html#index-28) + [DISPLAY](library/tkinter#index-0) + [DISTUTILS\_DEBUG](distutils/setupscript#index-0) + [EnableControlFlowGuard](https://docs.python.org/3.9/whatsnew/changelog.html#index-6) + [exec\_prefix](c-api/intro#index-2), [[1]](c-api/intro#index-5), [[2]](using/unix#index-1) + [HOME](distutils/apiref#index-1), [[1]](install/index#index-4), [[2]](install/index#index-5), [[3]](library/os.path#index-3), [[4]](library/os.path#index-7), [[5]](library/tkinter#index-1), [[6]](https://docs.python.org/3.9/whatsnew/3.8.html#index-14), [[7]](https://docs.python.org/3.9/whatsnew/3.8.html#index-21), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-54), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-55) + [HOMEDRIVE](install/index#index-7), [[1]](library/os.path#index-6) + [HOMEPATH](install/index#index-8), [[1]](library/os.path#index-5) + [http\_proxy](howto/urllib2#index-3), [[1]](library/urllib.request#index-0), [[2]](library/urllib.request#index-9) + [IDLESTARTUP](library/idle#index-5), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-108), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-78), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-83) + [KDEDIR](library/webbrowser#index-2) + [LANG](library/gettext#index-3), [[1]](library/gettext#index-8), [[2]](library/locale#index-1), [[3]](library/locale#index-2), [[4]](library/locale#index-3) + [LANGUAGE](library/gettext#index-0), [[1]](library/gettext#index-5) + [LC\_ALL](library/gettext#index-1), [[1]](library/gettext#index-6) + [LC\_MESSAGES](library/gettext#index-2), [[1]](library/gettext#index-7) + [LDCXXSHARED](https://docs.python.org/3.9/whatsnew/2.7.html#index-12) + [LDFLAGS](https://docs.python.org/3.9/whatsnew/2.3.html#index-27) + [LINES](library/curses#index-0), [[1]](library/curses#index-3), [[2]](library/curses#index-5), [[3]](library/curses#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-31) + [LNAME](library/getpass#index-2) + [LOGNAME](library/getpass#index-0), [[1]](library/os#index-4) + [MIXERDEV](library/ossaudiodev#index-2) + [no\_proxy](library/urllib.request#index-4) + [PAGER](library/pydoc#index-1) + [PATH](c-api/intro#index-25), [[1]](c-api/intro#index-26), [[2]](faq/library#index-0), [[3]](faq/library#index-1), [[4]](library/cgi#index-3), [[5]](library/cgi#index-6), [[6]](library/os#index-27), [[7]](library/os#index-28), [[8]](library/os#index-29), [[9]](library/os#index-30), [[10]](library/os#index-33), [[11]](library/os#index-34), [[12]](library/os#index-35), [[13]](library/os#index-36), [[14]](library/os#index-46), [[15]](library/site#index-3), [[16]](library/webbrowser#index-3), [[17]](tutorial/appendix#index-0), [[18]](tutorial/modules#index-2), [[19]](using/cmdline#index-30), [[20]](using/unix#index-2), [[21]](using/windows#index-1), [[22]](using/windows#index-10), [[23]](using/windows#index-14), [[24]](using/windows#index-16), [[25]](using/windows#index-17), [[26]](using/windows#index-18), [[27]](using/windows#index-19), [[28]](using/windows#index-2), [[29]](using/windows#index-3), [[30]](using/windows#index-5), [[31]](using/windows#index-6), [[32]](using/windows#index-8), [[33]](using/windows#index-9), [[34]](https://docs.python.org/3.9/whatsnew/3.4.html#index-55), [[35]](https://docs.python.org/3.9/whatsnew/3.4.html#index-58), [[36]](https://docs.python.org/3.9/whatsnew/3.4.html#index-59), [[37]](https://docs.python.org/3.9/whatsnew/3.8.html#index-22), [[38]](https://docs.python.org/3.9/whatsnew/changelog.html#index-65), [[39]](https://docs.python.org/3.9/whatsnew/changelog.html#index-66) + [PATHEXT](using/windows#index-4), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-51), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-9) + [PIP\_USER](https://docs.python.org/3.9/whatsnew/changelog.html#index-61) + [PLAT](distutils/apiref#index-2) + [POSIXLY\_CORRECT](library/getopt#index-0) + [prefix](c-api/intro#index-1), [[1]](c-api/intro#index-3), [[2]](c-api/intro#index-4), [[3]](using/unix#index-0) + [PY\_PYTHON](using/windows#index-20) + [PYTHON\*](c-api/init#index-4), [[1]](using/cmdline#index-0), [[2]](using/cmdline#index-10), [[3]](using/cmdline#index-2), [[4]](using/cmdline#index-5), [[5]](https://docs.python.org/3.9/whatsnew/3.4.html#index-50) + [PYTHON\_DOM](library/xml.dom#index-0) + [PYTHONASYNCIODEBUG](library/asyncio-dev#index-0), [[1]](library/asyncio-eventloop#index-5), [[2]](library/devmode#index-5), [[3]](using/cmdline#envvar-PYTHONASYNCIODEBUG) + [PYTHONBREAKPOINT](library/sys#index-3), [[1]](library/sys#index-4), [[2]](library/sys#index-5), [[3]](using/cmdline#envvar-PYTHONBREAKPOINT), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-12) + [PYTHONCASEOK](library/functions#index-15), [[1]](using/cmdline#envvar-PYTHONCASEOK), [[2]](https://docs.python.org/3.9/whatsnew/2.1.html#index-11), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-21), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-45) + [PYTHONCOERCECLOCALE](c-api/init_config#index-9), [[1]](using/cmdline#envvar-PYTHONCOERCECLOCALE), [[2]](using/cmdline#index-46), [[3]](https://docs.python.org/3.9/whatsnew/3.7.html#index-4) + [PYTHONDEBUG](c-api/init#index-0), [[1]](using/cmdline#envvar-PYTHONDEBUG), [[2]](using/cmdline#index-4) + [PYTHONDEVMODE](library/devmode#index-0), [[1]](using/cmdline#envvar-PYTHONDEVMODE), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-26) + [PYTHONDOCS](library/pydoc#index-2) + [PYTHONDONTWRITEBYTECODE](c-api/init#index-1), [[1]](faq/programming#index-4), [[2]](library/sys#index-6), [[3]](using/cmdline#envvar-PYTHONDONTWRITEBYTECODE), [[4]](using/cmdline#index-3), [[5]](https://docs.python.org/3.9/whatsnew/2.6.html#index-20), [[6]](https://docs.python.org/3.9/whatsnew/2.6.html#index-24) + [PYTHONDUMPREFS](c-api/typeobj#index-0), [[1]](using/cmdline#envvar-PYTHONDUMPREFS), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-3), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-68) + [PYTHONEXECUTABLE](using/cmdline#envvar-PYTHONEXECUTABLE) + [PYTHONFAULTHANDLER](library/devmode#index-4), [[1]](library/faulthandler#index-0), [[2]](using/cmdline#envvar-PYTHONFAULTHANDLER), [[3]](https://docs.python.org/3.9/whatsnew/3.3.html#index-24) + [PYTHONHASHSEED](c-api/init#index-2), [[1]](c-api/init#index-3), [[2]](reference/datamodel#index-77), [[3]](using/cmdline#envvar-PYTHONHASHSEED), [[4]](using/cmdline#index-16), [[5]](using/cmdline#index-17), [[6]](using/cmdline#index-36), [[7]](https://docs.python.org/3.9/whatsnew/3.3.html#index-23), [[8]](https://docs.python.org/3.9/whatsnew/3.3.html#index-35), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-89) + [PYTHONHOME](c-api/init#index-31), [[1]](c-api/init#index-32), [[2]](c-api/init#index-6), [[3]](c-api/init_config#index-2), [[4]](c-api/intro#index-27), [[5]](c-api/intro#index-30), [[6]](install/index#index-0), [[7]](install/index#index-1), [[8]](library/test#index-2), [[9]](using/cmdline#envvar-PYTHONHOME), [[10]](using/cmdline#index-28), [[11]](using/cmdline#index-29), [[12]](using/cmdline#index-32), [[13]](using/cmdline#index-7), [[14]](using/windows#index-22), [[15]](using/windows#index-24), [[16]](using/windows#index-26), [[17]](https://docs.python.org/3.9/whatsnew/3.6.html#index-2) + [PYTHONINSPECT](c-api/init#index-7), [[1]](using/cmdline#envvar-PYTHONINSPECT), [[2]](using/cmdline#index-9), [[3]](https://docs.python.org/3.9/whatsnew/2.3.html#index-29) + [PYTHONINTMAXSTRDIGITS](library/stdtypes#index-63), [[1]](library/stdtypes#index-64), [[2]](library/sys#index-17), [[3]](using/cmdline#envvar-PYTHONINTMAXSTRDIGITS), [[4]](using/cmdline#index-24) + [PYTHONIOENCODING](c-api/init#index-18), [[1]](c-api/init#index-19), [[2]](library/sys#index-34), [[3]](using/cmdline#envvar-PYTHONIOENCODING), [[4]](using/cmdline#index-42), [[5]](using/cmdline#index-45), [[6]](https://docs.python.org/3.9/whatsnew/2.6.html#index-21), [[7]](https://docs.python.org/3.9/whatsnew/3.4.html#index-54) + [PYTHONLEGACYWINDOWSFSENCODING](c-api/init#index-8), [[1]](library/sys#index-32), [[2]](using/cmdline#envvar-PYTHONLEGACYWINDOWSFSENCODING), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-19) + [PYTHONLEGACYWINDOWSSTDIO](c-api/init#index-10), [[1]](library/sys#index-36), [[2]](using/cmdline#envvar-PYTHONLEGACYWINDOWSSTDIO), [[3]](using/cmdline#index-37), [[4]](https://docs.python.org/3.9/whatsnew/3.6.html#index-21) + [PYTHONMALLOC](c-api/memory#index-1), [[1]](c-api/memory#index-3), [[2]](c-api/memory#index-4), [[3]](library/devmode#index-2), [[4]](library/devmode#index-3), [[5]](using/cmdline#envvar-PYTHONMALLOC), [[6]](using/cmdline#index-40), [[7]](https://docs.python.org/3.9/whatsnew/3.6.html#index-27), [[8]](https://docs.python.org/3.9/whatsnew/3.6.html#index-38), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-138) + [PYTHONMALLOCSTATS](c-api/memory#index-2), [[1]](using/cmdline#envvar-PYTHONMALLOCSTATS), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-139) + [PYTHONNOUSERSITE](c-api/init#index-12), [[1]](library/site#index-8), [[2]](using/cmdline#envvar-PYTHONNOUSERSITE), [[3]](https://docs.python.org/3.9/whatsnew/2.6.html#index-6) + [PYTHONOLDPARSER](c-api/init_config#index-4), [[1]](using/cmdline#envvar-PYTHONOLDPARSER), [[2]](using/cmdline#index-22) + [PYTHONOPTIMIZE](c-api/init#index-13), [[1]](using/cmdline#envvar-PYTHONOPTIMIZE), [[2]](using/cmdline#index-12) + [PYTHONPATH](c-api/init#index-5), [[1]](c-api/init_config#index-3), [[2]](c-api/intro#index-28), [[3]](c-api/intro#index-31), [[4]](extending/building#index-0), [[5]](install/index#index-2), [[6]](install/index#index-3), [[7]](library/cgi#index-4), [[8]](library/sys#index-22), [[9]](library/sys#index-23), [[10]](library/test#index-3), [[11]](tutorial/modules#index-1), [[12]](tutorial/modules#index-5), [[13]](tutorial/modules#index-6), [[14]](using/cmdline#envvar-PYTHONPATH), [[15]](using/cmdline#index-31), [[16]](using/cmdline#index-33), [[17]](using/cmdline#index-34), [[18]](using/cmdline#index-6), [[19]](using/mac#index-0), [[20]](using/windows#index-21), [[21]](using/windows#index-23), [[22]](using/windows#index-25), [[23]](using/windows#index-7), [[24]](https://docs.python.org/3.9/whatsnew/3.4.html#index-56), [[25]](https://docs.python.org/3.9/whatsnew/3.4.html#index-57) + [PYTHONPLATLIBDIR](using/cmdline#envvar-PYTHONPLATLIBDIR), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-10) + [PYTHONPROFILEIMPORTTIME](using/cmdline#envvar-PYTHONPROFILEIMPORTTIME), [[1]](using/cmdline#index-25), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-27), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-97) + [PYTHONPYCACHEPREFIX](library/sys#index-7), [[1]](using/cmdline#envvar-PYTHONPYCACHEPREFIX), [[2]](using/cmdline#index-27), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-2), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-70) + [PYTHONSHOWALLOCCOUNT](https://docs.python.org/3.9/whatsnew/2.7.html#index-15) + [PYTHONSHOWREFCOUNT](https://docs.python.org/3.9/whatsnew/2.7.html#index-14) + [PYTHONSTARTUP](library/idle#index-6), [[1]](library/readline#index-0), [[2]](library/site#index-7), [[3]](library/sys#index-18), [[4]](tutorial/appendix#index-1), [[5]](using/cmdline#envvar-PYTHONSTARTUP), [[6]](using/cmdline#index-8), [[7]](https://docs.python.org/3.9/whatsnew/3.4.html#index-40), [[8]](https://docs.python.org/3.9/whatsnew/3.4.html#index-41), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-109), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-79), [[11]](https://docs.python.org/3.9/whatsnew/changelog.html#index-84) + [PYTHONTHREADDEBUG](using/cmdline#envvar-PYTHONTHREADDEBUG) + [PYTHONTRACEMALLOC](library/tracemalloc#index-0), [[1]](library/tracemalloc#index-1), [[2]](library/tracemalloc#index-2), [[3]](using/cmdline#envvar-PYTHONTRACEMALLOC) + [PYTHONTZPATH](library/zoneinfo#envvar-PYTHONTZPATH), [[1]](library/zoneinfo#index-2) + [PYTHONUNBUFFERED](c-api/init#index-14), [[1]](library/sys#index-37), [[2]](using/cmdline#envvar-PYTHONUNBUFFERED), [[3]](using/cmdline#index-19), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-57) + [PYTHONUSERBASE](library/site#index-10), [[1]](library/site#index-9), [[2]](using/cmdline#envvar-PYTHONUSERBASE), [[3]](https://docs.python.org/3.9/whatsnew/2.6.html#index-4) + [PYTHONUSERSITE](library/test#index-4) + [PYTHONUTF8](c-api/init_config#index-8), [[1]](library/sys#index-35), [[2]](using/cmdline#envvar-PYTHONUTF8), [[3]](using/cmdline#index-26), [[4]](using/cmdline#index-43), [[5]](using/windows#index-11), [[6]](https://docs.python.org/3.9/whatsnew/3.7.html#index-8) + [PYTHONVERBOSE](c-api/init#index-15), [[1]](using/cmdline#envvar-PYTHONVERBOSE), [[2]](using/cmdline#index-20) + [PYTHONWARNINGS](library/devmode#index-1), [[1]](library/warnings#index-1), [[2]](library/warnings#index-2), [[3]](library/warnings#index-3), [[4]](using/cmdline#envvar-PYTHONWARNINGS), [[5]](using/cmdline#index-21), [[6]](https://docs.python.org/3.9/whatsnew/2.7.html#index-1), [[7]](https://docs.python.org/3.9/whatsnew/2.7.html#index-8), [[8]](https://docs.python.org/3.9/whatsnew/3.2.html#index-10), [[9]](https://docs.python.org/3.9/whatsnew/3.7.html#index-36) + [SOURCE\_DATE\_EPOCH](library/compileall#index-1), [[1]](library/py_compile#index-3), [[2]](library/py_compile#index-6), [[3]](library/py_compile#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-31), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-72), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-88) + [SSL\_CERT\_FILE](library/ssl#index-20) + [SSL\_CERT\_PATH](library/ssl#index-21) + [SSLKEYLOGFILE](library/ssl#index-2), [[1]](library/ssl#index-3) + [SystemRoot](library/subprocess#index-3) + [TCL\_LIBRARY](faq/gui#index-0) + [TEMP](library/tempfile#index-2) + [TERM](library/curses#index-1), [[1]](library/curses#index-2) + [TK\_LIBRARY](faq/gui#index-1) + [TMP](library/tempfile#index-3) + [TMPDIR](library/tempfile#index-1) + [TZ](library/time#index-13), [[1]](library/time#index-14), [[2]](library/time#index-15), [[3]](library/time#index-16), [[4]](library/time#index-17), [[5]](library/time#index-18) + [USER](library/getpass#index-1) + [USER\_BASE](https://docs.python.org/3.9/whatsnew/2.7.html#index-9) + [USERNAME](library/getpass#index-3), [[1]](library/os#index-5) + [USERPROFILE](install/index#index-6), [[1]](library/os.path#index-4), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-13), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-20), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-53) + [VIRTUAL\_ENV](library/venv#index-2) | * environment variables + [deleting](library/os#index-15) + [setting](library/os#index-11) * [EnvironmentError](library/exceptions#EnvironmentError) * Environments + [virtual](library/venv#index-0) * [EnvironmentVarGuard (class in test.support)](library/test#test.support.EnvironmentVarGuard) * [ENXIO (in module errno)](library/errno#errno.ENXIO) * [eof (bz2.BZ2Decompressor attribute)](library/bz2#bz2.BZ2Decompressor.eof) + [(lzma.LZMADecompressor attribute)](library/lzma#lzma.LZMADecompressor.eof) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.eof) + [(ssl.MemoryBIO attribute)](library/ssl#ssl.MemoryBIO.eof) + [(zlib.Decompress attribute)](library/zlib#zlib.Decompress.eof) * [eof\_received() (asyncio.BufferedProtocol method)](library/asyncio-protocol#asyncio.BufferedProtocol.eof_received) + [(asyncio.Protocol method)](library/asyncio-protocol#asyncio.Protocol.eof_received) * [EOFError](library/exceptions#EOFError) + [(built-in exception)](c-api/file#index-1) * [EOPNOTSUPP (in module errno)](library/errno#errno.EOPNOTSUPP) * [EOVERFLOW (in module errno)](library/errno#errno.EOVERFLOW) * [EPERM (in module errno)](library/errno#errno.EPERM) * [EPFNOSUPPORT (in module errno)](library/errno#errno.EPFNOSUPPORT) * [epilogue (email.message.EmailMessage attribute)](library/email.message#email.message.EmailMessage.epilogue) + [(email.message.Message attribute)](library/email.compat32-message#email.message.Message.epilogue) * [EPIPE (in module errno)](library/errno#errno.EPIPE) * [epoch](library/time#index-0) * [epoll() (in module select)](library/select#select.epoll) * [EpollSelector (class in selectors)](library/selectors#selectors.EpollSelector) * [EPROTO (in module errno)](library/errno#errno.EPROTO) * [EPROTONOSUPPORT (in module errno)](library/errno#errno.EPROTONOSUPPORT) * [EPROTOTYPE (in module errno)](library/errno#errno.EPROTOTYPE) * [Eq (class in ast)](library/ast#ast.Eq) * [eq() (in module operator)](library/operator#operator.eq) * [EQEQUAL (in module token)](library/token#token.EQEQUAL) * [EQUAL (in module token)](library/token#token.EQUAL) * [ERA (in module locale)](library/locale#locale.ERA) * [ERA\_D\_FMT (in module locale)](library/locale#locale.ERA_D_FMT) * [ERA\_D\_T\_FMT (in module locale)](library/locale#locale.ERA_D_T_FMT) * [ERA\_T\_FMT (in module locale)](library/locale#locale.ERA_T_FMT) * [ERANGE (in module errno)](library/errno#errno.ERANGE) * [erase() (curses.window method)](library/curses#curses.window.erase) * [erasechar() (in module curses)](library/curses#curses.erasechar) * [EREMCHG (in module errno)](library/errno#errno.EREMCHG) * [EREMOTE (in module errno)](library/errno#errno.EREMOTE) * [EREMOTEIO (in module errno)](library/errno#errno.EREMOTEIO) * [ERESTART (in module errno)](library/errno#errno.ERESTART) * [erf() (in module math)](library/math#math.erf) * [erfc() (in module math)](library/math#math.erfc) * [EROFS (in module errno)](library/errno#errno.EROFS) * [ERR (in module curses)](library/curses#curses.ERR) * [errcheck (ctypes.\_FuncPtr attribute)](library/ctypes#ctypes._FuncPtr.errcheck) * [errcode (xmlrpc.client.ProtocolError attribute)](library/xmlrpc.client#xmlrpc.client.ProtocolError.errcode) * [errmsg (xmlrpc.client.ProtocolError attribute)](library/xmlrpc.client#xmlrpc.client.ProtocolError.errmsg) * errno + [module](library/exceptions#index-3) * [errno (module)](library/errno#module-errno) + [(OSError attribute)](library/exceptions#OSError.errno) * [Error](library/binascii#binascii.Error), [[1]](library/binhex#binhex.Error), [[2]](library/configparser#configparser.Error), [[3]](library/copy#copy.Error), [[4]](library/csv#csv.Error), [[5]](library/locale#locale.Error), [[6]](library/mailbox#mailbox.Error), [[7]](library/shutil#shutil.Error), [[8]](library/sqlite3#sqlite3.Error), [[9]](https://docs.python.org/3.9/library/sunau.html#sunau.Error), [[10]](library/uu#uu.Error), [[11]](library/wave#wave.Error), [[12]](library/webbrowser#webbrowser.Error), [[13]](library/xdrlib#xdrlib.Error) * [error](library/_thread#_thread.error), [[1]](library/audioop#audioop.error), [[2]](library/curses#curses.error), [[3]](library/dbm#dbm.dumb.error), [[4]](library/dbm#dbm.error), [[5]](library/dbm#dbm.gnu.error), [[6]](library/dbm#dbm.ndbm.error), [[7]](library/getopt#getopt.error), [[8]](library/nis#nis.error), [[9]](library/os#os.error), [[10]](library/pyexpat#xml.parsers.expat.error), [[11]](library/re#re.error), [[12]](library/resource#resource.error), [[13]](library/select#select.error), [[14]](library/socket#socket.error), [[15]](library/struct#struct.error), [[16]](library/zlib#zlib.error) * error handler's name + [backslashreplace](library/codecs#index-1) + [ignore](library/codecs#index-1) + [namereplace](library/codecs#index-3) + [replace](library/codecs#index-1) + [strict](library/codecs#index-1) + [surrogateescape](library/codecs#index-1) + [surrogatepass](library/codecs#index-4) + [xmlcharrefreplace](library/codecs#index-3) * [error handling](reference/executionmodel#index-13) * [error() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.error) + [(in module logging)](library/logging#logging.error) + [(logging.Logger method)](library/logging#logging.Logger.error) + [(urllib.request.OpenerDirector method)](library/urllib.request#urllib.request.OpenerDirector.error) + [(xml.sax.handler.ErrorHandler method)](library/xml.sax.handler#xml.sax.handler.ErrorHandler.error) * [error\_body (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.error_body) * [error\_content\_type (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.error_content_type) * [error\_headers (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.error_headers) * [error\_leader() (shlex.shlex method)](library/shlex#shlex.shlex.error_leader) * [error\_message\_format (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.error_message_format) * [error\_output() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.error_output) * [error\_perm](library/ftplib#ftplib.error_perm) * [error\_proto](library/ftplib#ftplib.error_proto), [[1]](library/poplib#poplib.error_proto) * [error\_received() (asyncio.DatagramProtocol method)](library/asyncio-protocol#asyncio.DatagramProtocol.error_received) * [error\_reply](library/ftplib#ftplib.error_reply) * [error\_status (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.error_status) * [error\_temp](library/ftplib#ftplib.error_temp) * [ErrorByteIndex (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.ErrorByteIndex) * [errorcode (in module errno)](library/errno#errno.errorcode) * [ErrorCode (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.ErrorCode) * [ErrorColumnNumber (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.ErrorColumnNumber) * [ErrorHandler (class in xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.ErrorHandler) * [ErrorLineNumber (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.ErrorLineNumber) * Errors + [logging](library/logging#index-0) * [errors](reference/executionmodel#index-13) + [(io.TextIOBase attribute)](library/io#io.TextIOBase.errors) + [(unittest.TestLoader attribute)](library/unittest#unittest.TestLoader.errors) + [(unittest.TestResult attribute)](library/unittest#unittest.TestResult.errors) * [ErrorString() (in module xml.parsers.expat)](library/pyexpat#xml.parsers.expat.ErrorString) * [ERRORTOKEN (in module token)](library/token#token.ERRORTOKEN) * [escape (shlex.shlex attribute)](library/shlex#shlex.shlex.escape) * [escape sequence](reference/lexical_analysis#index-22) * [escape() (in module glob)](library/glob#glob.escape) + [(in module html)](library/html#html.escape) + [(in module re)](library/re#re.escape) + [(in module xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.escape) * [escapechar (csv.Dialect attribute)](library/csv#csv.Dialect.escapechar) * [escapedquotes (shlex.shlex attribute)](library/shlex#shlex.shlex.escapedquotes) * [ESHUTDOWN (in module errno)](library/errno#errno.ESHUTDOWN) * [ESOCKTNOSUPPORT (in module errno)](library/errno#errno.ESOCKTNOSUPPORT) * [ESPIPE (in module errno)](library/errno#errno.ESPIPE) * [ESRCH (in module errno)](library/errno#errno.ESRCH) * [ESRMNT (in module errno)](library/errno#errno.ESRMNT) * [ESTALE (in module errno)](library/errno#errno.ESTALE) * [ESTRPIPE (in module errno)](library/errno#errno.ESTRPIPE) * [ETIME (in module errno)](library/errno#errno.ETIME) * [ETIMEDOUT (in module errno)](library/errno#errno.ETIMEDOUT) * [Etiny() (decimal.Context method)](library/decimal#decimal.Context.Etiny) * [ETOOMANYREFS (in module errno)](library/errno#errno.ETOOMANYREFS) * [Etop() (decimal.Context method)](library/decimal#decimal.Context.Etop) * [ETXTBSY (in module errno)](library/errno#errno.ETXTBSY) * [EUCLEAN (in module errno)](library/errno#errno.EUCLEAN) * [EUNATCH (in module errno)](library/errno#errno.EUNATCH) * [EUSERS (in module errno)](library/errno#errno.EUSERS) * eval + [built-in function](library/parser#index-1), [[1]](library/pprint#index-1), [[2]](library/pprint#index-2), [[3]](library/stdtypes#index-59), [[4]](reference/simple_stmts#index-44), [[5]](reference/toplevel_components#index-6) * [eval() (built-in function)](library/functions#eval) * evaluation + [order](reference/expressions#index-95) * [Event (class in asyncio)](library/asyncio-sync#asyncio.Event) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.Event) + [(class in threading)](library/threading#threading.Event) * [event scheduling](library/sched#index-0) * [event() (msilib.Control method)](library/msilib#msilib.Control.event) * [Event() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Event) * [events (selectors.SelectorKey attribute)](library/selectors#selectors.SelectorKey.events) + [(widgets)](library/tkinter#index-6) * [EWOULDBLOCK (in module errno)](library/errno#errno.EWOULDBLOCK) * [EX\_CANTCREAT (in module os)](library/os#os.EX_CANTCREAT) * [EX\_CONFIG (in module os)](library/os#os.EX_CONFIG) * [EX\_DATAERR (in module os)](library/os#os.EX_DATAERR) * [EX\_IOERR (in module os)](library/os#os.EX_IOERR) * [EX\_NOHOST (in module os)](library/os#os.EX_NOHOST) * [EX\_NOINPUT (in module os)](library/os#os.EX_NOINPUT) * [EX\_NOPERM (in module os)](library/os#os.EX_NOPERM) * [EX\_NOTFOUND (in module os)](library/os#os.EX_NOTFOUND) * [EX\_NOUSER (in module os)](library/os#os.EX_NOUSER) * [EX\_OK (in module os)](library/os#os.EX_OK) * [EX\_OSERR (in module os)](library/os#os.EX_OSERR) * [EX\_OSFILE (in module os)](library/os#os.EX_OSFILE) * [EX\_PROTOCOL (in module os)](library/os#os.EX_PROTOCOL) * [EX\_SOFTWARE (in module os)](library/os#os.EX_SOFTWARE) * [EX\_TEMPFAIL (in module os)](library/os#os.EX_TEMPFAIL) * [EX\_UNAVAILABLE (in module os)](library/os#os.EX_UNAVAILABLE) * [EX\_USAGE (in module os)](library/os#os.EX_USAGE) * [Example (class in doctest)](library/doctest#doctest.Example) * [example (doctest.DocTestFailure attribute)](library/doctest#doctest.DocTestFailure.example) + [(doctest.UnexpectedException attribute)](library/doctest#doctest.UnexpectedException.example) * [examples (doctest.DocTest attribute)](library/doctest#doctest.DocTest.examples) * [exc\_info (doctest.UnexpectedException attribute)](library/doctest#doctest.UnexpectedException.exc_info) + [(in module sys)](reference/datamodel#index-62) * [exc\_info() (in module sys)](c-api/intro#index-18), [[1]](library/sys#sys.exc_info) * [exc\_msg (doctest.Example attribute)](library/doctest#doctest.Example.exc_msg) * [exc\_type (traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.exc_type) * [excel (class in csv)](library/csv#csv.excel) * [excel\_tab (class in csv)](library/csv#csv.excel_tab) * except + [keyword](reference/compound_stmts#index-10) + [statement](library/exceptions#index-0) * [except (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-except) * [ExceptHandler (class in ast)](library/ast#ast.ExceptHandler) * [excepthook() (in module sys)](library/cgitb#index-2), [[1]](library/sys#sys.excepthook) + [(in module threading)](library/threading#threading.excepthook) * [Exception](library/exceptions#Exception) * [exception](reference/executionmodel#index-12), [[1]](reference/simple_stmts#index-27) + [AssertionError](reference/simple_stmts#index-19) + [AttributeError](reference/expressions#index-40) + [chaining](reference/simple_stmts#index-29) + [GeneratorExit](reference/expressions#index-33), [[1]](reference/expressions#index-37) + [handler](reference/datamodel#index-62) + [ImportError](reference/simple_stmts#index-34) + [NameError](reference/expressions#index-4) + [raising](reference/simple_stmts#index-27) + [StopAsyncIteration](reference/expressions#index-36) + [StopIteration](reference/expressions#index-32), [[1]](reference/simple_stmts#index-26) + [TypeError](reference/expressions#index-63) + [ValueError](reference/expressions#index-72) + [ZeroDivisionError](reference/expressions#index-67) * [EXCEPTION (in module tkinter)](library/tkinter#tkinter.EXCEPTION) * [exception handler](reference/executionmodel#index-13) * [exception() (asyncio.Future method)](library/asyncio-future#asyncio.Future.exception) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.exception) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.exception) + [(in module logging)](library/logging#logging.exception) + [(logging.Logger method)](library/logging#logging.Logger.exception) * exceptions + [in CGI scripts](library/cgitb#index-0) * exclusive + [or](reference/expressions#index-75) * [EXDEV (in module errno)](library/errno#errno.EXDEV) * exec + [built-in function](library/functions#index-1), [[1]](library/parser#index-1), [[2]](library/stdtypes#index-59), [[3]](reference/simple_stmts#index-44) * [exec (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-exec) * [exec() (built-in function)](library/functions#exec) * [exec\_module (C function)](c-api/module#c.exec_module) * [exec\_module() (importlib.abc.InspectLoader method)](library/importlib#importlib.abc.InspectLoader.exec_module) + [(importlib.abc.Loader method)](library/importlib#importlib.abc.Loader.exec_module) + [(importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.exec_module) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.exec_module) * [exec\_prefix](c-api/intro#index-2), [[1]](c-api/intro#index-5), [[2]](using/unix#index-1) * [EXEC\_PREFIX (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.EXEC_PREFIX) * [exec\_prefix (in module sys)](library/sys#sys.exec_prefix) * [execfile (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-execfile) * [execl() (in module os)](library/os#os.execl) * [execle() (in module os)](library/os#os.execle) * [execlp() (in module os)](library/os#os.execlp) * [execlpe() (in module os)](library/os#os.execlpe) * [executable (in module sys)](c-api/init#index-22), [[1]](library/sys#sys.executable) * [Executable Zip Files](library/zipapp#index-0) * [executable\_filename() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.executable_filename) * [execute() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.execute) + [(in module distutils.util)](distutils/apiref#distutils.util.execute) * [Execute() (msilib.View method)](library/msilib#msilib.View.Execute) * [execute() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.execute) + [(sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.execute) * [executemany() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.executemany) + [(sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.executemany) * [executescript() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.executescript) + [(sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.executescript) * execution + [frame](reference/compound_stmts#index-31), [[1]](reference/executionmodel#index-2) + [restricted](reference/executionmodel#index-11) + [stack](reference/datamodel#index-62) * [execution model](reference/executionmodel#index-0) * [ExecutionLoader (class in importlib.abc)](library/importlib#importlib.abc.ExecutionLoader) * [Executor (class in concurrent.futures)](library/concurrent.futures#concurrent.futures.Executor) * [execv() (in module os)](library/os#os.execv) * [execve() (in module os)](library/os#os.execve) * [execvp() (in module os)](library/os#os.execvp) * [execvpe() (in module os)](library/os#os.execvpe) * [ExFileSelectBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.ExFileSelectBox) * [EXFULL (in module errno)](library/errno#errno.EXFULL) * [exists() (in module os.path)](library/os.path#os.path.exists) + [(pathlib.Path method)](library/pathlib#pathlib.Path.exists) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.exists) + [(zipfile.Path method)](library/zipfile#zipfile.Path.exists) * [exit (built-in variable)](library/constants#exit) * [exit()](c-api/sys#index-2) + [(argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.exit) + [(in module \_thread)](library/_thread#_thread.exit) + [(in module sys)](library/sys#sys.exit) * [exitcode (multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.exitcode) * [exitfunc (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-exitfunc) * [exitonclick() (in module turtle)](library/turtle#turtle.exitonclick) * [ExitStack (class in contextlib)](library/contextlib#contextlib.ExitStack) * [exp() (decimal.Context method)](library/decimal#decimal.Context.exp) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.exp) + [(in module cmath)](library/cmath#cmath.exp) + [(in module math)](library/math#math.exp) * [expand() (re.Match method)](library/re#re.Match.expand) * [expand\_tabs (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.expand_tabs) * [ExpandEnvironmentStrings() (in module winreg)](library/winreg#winreg.ExpandEnvironmentStrings) * [expandNode() (xml.dom.pulldom.DOMEventStream method)](library/xml.dom.pulldom#xml.dom.pulldom.DOMEventStream.expandNode) * [expandtabs() (bytearray method)](library/stdtypes#bytearray.expandtabs) + [(bytes method)](library/stdtypes#bytes.expandtabs) + [(str method)](library/stdtypes#str.expandtabs) * [expanduser() (in module os.path)](library/os.path#os.path.expanduser) + [(pathlib.Path method)](library/pathlib#pathlib.Path.expanduser) * [expandvars() (in module os.path)](library/os.path#os.path.expandvars) * [Expat](library/pyexpat#index-0) * [ExpatError](library/pyexpat#xml.parsers.expat.ExpatError) * [expect() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.expect) * [expected (asyncio.IncompleteReadError attribute)](library/asyncio-exceptions#asyncio.IncompleteReadError.expected) * [expectedFailure() (in module unittest)](library/unittest#unittest.expectedFailure) * [expectedFailures (unittest.TestResult attribute)](library/unittest#unittest.TestResult.expectedFailures) * [expires (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.expires) * [exploded (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.exploded) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.exploded) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.exploded) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.exploded) * [expm1() (in module math)](library/math#math.expm1) * [expovariate() (in module random)](library/random#random.expovariate) * [Expr (class in ast)](library/ast#ast.Expr) * [expr() (in module parser)](library/parser#parser.expr) * [expression](reference/expressions#index-0), [**[1]**](glossary#term-expression) + [Conditional](reference/expressions#index-82) + [conditional](reference/expressions#index-87) + [generator](reference/expressions#index-22) + [lambda](reference/compound_stmts#index-26), [[1]](reference/expressions#index-89) + [list](reference/expressions#index-90), [[1]](reference/simple_stmts#index-1), [[2]](reference/simple_stmts#index-2) + [statement](reference/simple_stmts#index-1) + [yield](reference/expressions#index-23) * [expunge() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.expunge) * [extend() (array.array method)](library/array#array.array.extend) + [(collections.deque method)](library/collections#collections.deque.extend) + [(sequence method)](library/stdtypes#index-22) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.extend) * [extend\_path() (in module pkgutil)](library/pkgutil#pkgutil.extend_path) * [EXTENDED\_ARG (opcode)](library/dis#opcode-EXTENDED_ARG) * [ExtendedContext (class in decimal)](library/decimal#decimal.ExtendedContext) * [ExtendedInterpolation (class in configparser)](library/configparser#configparser.ExtendedInterpolation) * [extendleft() (collections.deque method)](library/collections#collections.deque.extendleft) * extension + [module](reference/datamodel#index-4) * [Extension (class in distutils.core)](distutils/apiref#distutils.core.Extension) * [**extension module**](glossary#term-extension-module) * [EXTENSION\_SUFFIXES (in module importlib.machinery)](library/importlib#importlib.machinery.EXTENSION_SUFFIXES) * [ExtensionFileLoader (class in importlib.machinery)](library/importlib#importlib.machinery.ExtensionFileLoader) * [extensions\_map (http.server.SimpleHTTPRequestHandler attribute)](library/http.server#http.server.SimpleHTTPRequestHandler.extensions_map) * [External Data Representation](library/pickle#index-1), [[1]](library/xdrlib#index-0) * [external\_attr (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.external_attr) * [ExternalClashError](library/mailbox#mailbox.ExternalClashError) * [ExternalEntityParserCreate() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.ExternalEntityParserCreate) * [ExternalEntityRefHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.ExternalEntityRefHandler) * [extra (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.extra) * [extract() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.extract) + [(traceback.StackSummary class method)](library/traceback#traceback.StackSummary.extract) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.extract) * [extract\_cookies() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.extract_cookies) * [extract\_stack() (in module traceback)](library/traceback#traceback.extract_stack) * [extract\_tb() (in module traceback)](library/traceback#traceback.extract_tb) * [extract\_version (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.extract_version) * [extractall() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.extractall) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.extractall) * [ExtractError](library/tarfile#tarfile.ExtractError) * [extractfile() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.extractfile) * [extsep (in module os)](library/os#os.extsep) | F - | | | | --- | --- | | * f" + [formatted string literal](reference/lexical_analysis#index-21) * f' + [formatted string literal](reference/lexical_analysis#index-21) * [f-string](reference/lexical_analysis#index-24), [**[1]**](glossary#term-f-string) * [f\_back (frame attribute)](reference/datamodel#index-60) * [f\_builtins (frame attribute)](reference/datamodel#index-60) * [f\_code (frame attribute)](reference/datamodel#index-60) * [f\_contiguous (memoryview attribute)](library/stdtypes#memoryview.f_contiguous) * [f\_globals (frame attribute)](reference/datamodel#index-60) * [f\_lasti (frame attribute)](reference/datamodel#index-60) * [f\_lineno (frame attribute)](reference/datamodel#index-61) * [f\_locals (frame attribute)](reference/datamodel#index-60) * [F\_LOCK (in module os)](library/os#os.F_LOCK) * [F\_OK (in module os)](library/os#os.F_OK) * [F\_TEST (in module os)](library/os#os.F_TEST) * [F\_TLOCK (in module os)](library/os#os.F_TLOCK) * [f\_trace (frame attribute)](reference/datamodel#index-61) * [f\_trace\_lines (frame attribute)](reference/datamodel#index-61) * [f\_trace\_opcodes (frame attribute)](reference/datamodel#index-61) * [F\_ULOCK (in module os)](library/os#os.F_ULOCK) * [fabs() (in module math)](library/math#math.fabs) * [factorial() (in module math)](library/math#math.factorial) * [factory() (importlib.util.LazyLoader class method)](library/importlib#importlib.util.LazyLoader.factory) * [fail() (unittest.TestCase method)](library/unittest#unittest.TestCase.fail) * [FAIL\_FAST (in module doctest)](library/doctest#doctest.FAIL_FAST) * [failfast (unittest.TestResult attribute)](library/unittest#unittest.TestResult.failfast) * [failureException (unittest.TestCase attribute)](library/unittest#unittest.TestCase.failureException) * [failures (unittest.TestResult attribute)](library/unittest#unittest.TestResult.failures) * [FakePath (class in test.support)](library/test#test.support.FakePath) * [False](library/stdtypes#index-4), [[1]](library/stdtypes#index-62), [[2]](reference/datamodel#index-11) * [false](library/stdtypes#index-1) * [False (Built-in object)](library/stdtypes#index-3) + [(built-in variable)](library/constants#False) * [families() (in module tkinter.font)](library/tkinter.font#tkinter.font.families) * [family (socket.socket attribute)](library/socket#socket.socket.family) * [fancy\_getopt() (in module distutils.fancy\_getopt)](distutils/apiref#distutils.fancy_getopt.fancy_getopt) * [FancyGetopt (class in distutils.fancy\_getopt)](distutils/apiref#distutils.fancy_getopt.FancyGetopt) * [FancyURLopener (class in urllib.request)](library/urllib.request#urllib.request.FancyURLopener) * [fast (pickle.Pickler attribute)](library/pickle#pickle.Pickler.fast) * [FastChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.FastChildWatcher) * [fatalError() (xml.sax.handler.ErrorHandler method)](library/xml.sax.handler#xml.sax.handler.ErrorHandler.fatalError) * [Fault (class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.Fault) * [faultCode (xmlrpc.client.Fault attribute)](library/xmlrpc.client#xmlrpc.client.Fault.faultCode) * [faulthandler (module)](library/faulthandler#module-faulthandler) * [faultString (xmlrpc.client.Fault attribute)](library/xmlrpc.client#xmlrpc.client.Fault.faultString) * [fchdir() (in module os)](library/os#os.fchdir) * [fchmod() (in module os)](library/os#os.fchmod) * [fchown() (in module os)](library/os#os.fchown) * [FCICreate() (in module msilib)](library/msilib#msilib.FCICreate) * [fcntl (module)](library/fcntl#module-fcntl) * [fcntl() (in module fcntl)](library/fcntl#fcntl.fcntl) * [fd (selectors.SelectorKey attribute)](library/selectors#selectors.SelectorKey.fd) * [fd() (in module turtle)](library/turtle#turtle.fd) * [fd\_count() (in module test.support)](library/test#test.support.fd_count) * [fdatasync() (in module os)](library/os#os.fdatasync) * [fdopen() (in module os)](library/os#os.fdopen) * [Feature (class in msilib)](library/msilib#msilib.Feature) * [feature\_external\_ges (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_external_ges) * [feature\_external\_pes (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_external_pes) * [feature\_namespace\_prefixes (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_namespace_prefixes) * [feature\_namespaces (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_namespaces) * [feature\_string\_interning (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_string_interning) * [feature\_validation (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.feature_validation) * [feed() (email.parser.BytesFeedParser method)](library/email.parser#email.parser.BytesFeedParser.feed) + [(html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.feed) + [(xml.etree.ElementTree.XMLParser method)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLParser.feed) + [(xml.etree.ElementTree.XMLPullParser method)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLPullParser.feed) + [(xml.sax.xmlreader.IncrementalParser method)](library/xml.sax.reader#xml.sax.xmlreader.IncrementalParser.feed) * [FeedParser (class in email.parser)](library/email.parser#email.parser.FeedParser) * [fetch() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.fetch) * [Fetch() (msilib.View method)](library/msilib#msilib.View.Fetch) * [fetchall() (sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.fetchall) * [fetchmany() (sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.fetchmany) * [fetchone() (sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.fetchone) * [fflags (select.kevent attribute)](library/select#select.kevent.fflags) * [Field (class in dataclasses)](library/dataclasses#dataclasses.Field) * [field() (in module dataclasses)](library/dataclasses#dataclasses.field) * [field\_size\_limit() (in module csv)](library/csv#csv.field_size_limit) * [fieldnames (csv.csvreader attribute)](library/csv#csv.csvreader.fieldnames) * [fields (uuid.UUID attribute)](library/uuid#uuid.UUID.fields) * [fields() (in module dataclasses)](library/dataclasses#dataclasses.fields) * file + [.ini](library/configparser#index-0) + [.pdbrc](library/pdb#index-2) + [byte-code](library/imp#index-1), [[1]](library/py_compile#index-0) + [configuration](library/configparser#index-0) + [copying](library/shutil#index-0) + [debugger configuration](library/pdb#index-2) + [gzip command line option](library/gzip#cmdoption-gzip-arg-file) + [large files](library/posix#index-1) + [mime.types](library/mimetypes#index-2) + [modes](library/functions#index-5) + [object](c-api/file#index-0), [[1]](tutorial/inputoutput#index-0) + [path configuration](library/site#index-4) + [plist](library/plistlib#index-0) + [temporary](library/tempfile#index-0) * [file (pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.file) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.file) * file ... + [compileall command line option](library/compileall#cmdoption-compileall-arg-file) * file control + [UNIX](library/fcntl#index-0) * file name + [temporary](library/tempfile#index-0) * [**file object**](glossary#term-file-object) + [io module](library/io#index-0) + [open() built-in function](library/functions#index-4) * [**file-like object**](glossary#term-file-like-object) * [FILE\_ATTRIBUTE\_ARCHIVE (in module stat)](library/stat#stat.FILE_ATTRIBUTE_ARCHIVE) * [FILE\_ATTRIBUTE\_COMPRESSED (in module stat)](library/stat#stat.FILE_ATTRIBUTE_COMPRESSED) * [FILE\_ATTRIBUTE\_DEVICE (in module stat)](library/stat#stat.FILE_ATTRIBUTE_DEVICE) * [FILE\_ATTRIBUTE\_DIRECTORY (in module stat)](library/stat#stat.FILE_ATTRIBUTE_DIRECTORY) * [FILE\_ATTRIBUTE\_ENCRYPTED (in module stat)](library/stat#stat.FILE_ATTRIBUTE_ENCRYPTED) * [FILE\_ATTRIBUTE\_HIDDEN (in module stat)](library/stat#stat.FILE_ATTRIBUTE_HIDDEN) * [FILE\_ATTRIBUTE\_INTEGRITY\_STREAM (in module stat)](library/stat#stat.FILE_ATTRIBUTE_INTEGRITY_STREAM) * [FILE\_ATTRIBUTE\_NO\_SCRUB\_DATA (in module stat)](library/stat#stat.FILE_ATTRIBUTE_NO_SCRUB_DATA) * [FILE\_ATTRIBUTE\_NORMAL (in module stat)](library/stat#stat.FILE_ATTRIBUTE_NORMAL) * [FILE\_ATTRIBUTE\_NOT\_CONTENT\_INDEXED (in module stat)](library/stat#stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) * [FILE\_ATTRIBUTE\_OFFLINE (in module stat)](library/stat#stat.FILE_ATTRIBUTE_OFFLINE) * [FILE\_ATTRIBUTE\_READONLY (in module stat)](library/stat#stat.FILE_ATTRIBUTE_READONLY) * [FILE\_ATTRIBUTE\_REPARSE\_POINT (in module stat)](library/stat#stat.FILE_ATTRIBUTE_REPARSE_POINT) * [FILE\_ATTRIBUTE\_SPARSE\_FILE (in module stat)](library/stat#stat.FILE_ATTRIBUTE_SPARSE_FILE) * [FILE\_ATTRIBUTE\_SYSTEM (in module stat)](library/stat#stat.FILE_ATTRIBUTE_SYSTEM) * [FILE\_ATTRIBUTE\_TEMPORARY (in module stat)](library/stat#stat.FILE_ATTRIBUTE_TEMPORARY) * [FILE\_ATTRIBUTE\_VIRTUAL (in module stat)](library/stat#stat.FILE_ATTRIBUTE_VIRTUAL) * [file\_created() (built-in function)](distutils/builtdist#file_created) * [file\_dispatcher (class in asyncore)](library/asyncore#asyncore.file_dispatcher) * [file\_open() (urllib.request.FileHandler method)](library/urllib.request#urllib.request.FileHandler.file_open) * [file\_size (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.file_size) * [file\_wrapper (class in asyncore)](library/asyncore#asyncore.file_wrapper) * [filecmp (module)](library/filecmp#module-filecmp) * [fileConfig() (in module logging.config)](library/logging.config#logging.config.fileConfig) * [FileCookieJar (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.FileCookieJar) * [FileDialog (class in tkinter.filedialog)](library/dialog#tkinter.filedialog.FileDialog) * [FileEntry (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.FileEntry) * [FileExistsError](library/exceptions#FileExistsError) * [FileFinder (class in importlib.machinery)](library/importlib#importlib.machinery.FileFinder) * [FileHandler (class in logging)](library/logging.handlers#logging.FileHandler) + [(class in urllib.request)](library/urllib.request#urllib.request.FileHandler) * [FileInput (class in fileinput)](library/fileinput#fileinput.FileInput) * [fileinput (module)](library/fileinput#module-fileinput) * [FileIO (class in io)](library/io#io.FileIO) * [filelineno() (in module fileinput)](library/fileinput#fileinput.filelineno) * [FileLoader (class in importlib.abc)](library/importlib#importlib.abc.FileLoader) * [filemode() (in module stat)](library/stat#stat.filemode) * [filename (doctest.DocTest attribute)](library/doctest#doctest.DocTest.filename) + [(http.cookiejar.FileCookieJar attribute)](library/http.cookiejar#http.cookiejar.FileCookieJar.filename) + [(OSError attribute)](library/exceptions#OSError.filename) + [(SyntaxError attribute)](library/exceptions#SyntaxError.filename) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.filename) + [(tracemalloc.Frame attribute)](library/tracemalloc#tracemalloc.Frame.filename) + [(zipfile.ZipFile attribute)](library/zipfile#zipfile.ZipFile.filename) + [(zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.filename) * [filename() (in module fileinput)](library/fileinput#fileinput.filename) * [filename2 (OSError attribute)](library/exceptions#OSError.filename2) * [filename\_only (in module tabnanny)](library/tabnanny#tabnanny.filename_only) * [filename\_pattern (tracemalloc.Filter attribute)](library/tracemalloc#tracemalloc.Filter.filename_pattern) * filenames + [pathname expansion](library/glob#index-0) + [wildcard expansion](library/fnmatch#index-0) * [fileno() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.fileno) + [(in module fileinput)](library/fileinput#fileinput.fileno) + [(io.IOBase method)](library/io#io.IOBase.fileno) + [(multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.fileno) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.fileno) + [(ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.fileno) + [(select.devpoll method)](library/select#select.devpoll.fileno) + [(select.epoll method)](library/select#select.epoll.fileno) + [(select.kqueue method)](library/select#select.kqueue.fileno) + [(selectors.DevpollSelector method)](library/selectors#selectors.DevpollSelector.fileno) + [(selectors.EpollSelector method)](library/selectors#selectors.EpollSelector.fileno) + [(selectors.KqueueSelector method)](library/selectors#selectors.KqueueSelector.fileno) + [(socket.socket method)](library/socket#socket.socket.fileno) + [(socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.fileno) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.fileno) * [FileNotFoundError](library/exceptions#FileNotFoundError) * [fileobj (selectors.SelectorKey attribute)](library/selectors#selectors.SelectorKey.fileobj) * [files() (in module importlib.resources)](library/importlib#importlib.resources.files) * [files\_double\_event() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.files_double_event) * [files\_select\_event() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.files_select_event) * [FileSelectBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.FileSelectBox) * [FileType (class in argparse)](library/argparse#argparse.FileType) * [FileWrapper (class in wsgiref.util)](library/wsgiref#wsgiref.util.FileWrapper) * [fill() (in module textwrap)](library/textwrap#textwrap.fill) + [(textwrap.TextWrapper method)](library/textwrap#textwrap.TextWrapper.fill) * [fillcolor() (in module turtle)](library/turtle#turtle.fillcolor) * [filling() (in module turtle)](library/turtle#turtle.filling) * [filter (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-filter) * [Filter (class in logging)](library/logging#logging.Filter) + [(class in tracemalloc)](library/tracemalloc#tracemalloc.Filter) * [filter (select.kevent attribute)](library/select#select.kevent.filter) * [filter() (built-in function)](library/functions#filter) + [(in module curses)](library/curses#curses.filter) + [(in module fnmatch)](library/fnmatch#fnmatch.filter) + [(logging.Filter method)](library/logging#logging.Filter.filter) + [(logging.Handler method)](library/logging#logging.Handler.filter) + [(logging.Logger method)](library/logging#logging.Logger.filter) * [filter\_command() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.filter_command) * [FILTER\_DIR (in module unittest.mock)](library/unittest.mock#unittest.mock.FILTER_DIR) * [filter\_traces() (tracemalloc.Snapshot method)](library/tracemalloc#tracemalloc.Snapshot.filter_traces) * [filterfalse() (in module itertools)](library/itertools#itertools.filterfalse) * [filterwarnings() (in module warnings)](library/warnings#warnings.filterwarnings) * [Final (in module typing)](library/typing#typing.Final) * [final() (in module typing)](library/typing#typing.final) * [finalization, of objects](extending/newtypes#index-0) * [finalize (class in weakref)](library/weakref#weakref.finalize) * [finalize\_options() (distutils.cmd.Command method)](distutils/apiref#distutils.cmd.Command.finalize_options) * [finalizer](reference/datamodel#index-70) * finally + [keyword](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-14), [[2]](reference/simple_stmts#index-25), [[3]](reference/simple_stmts#index-32), [[4]](reference/simple_stmts#index-33) * [find() (bytearray method)](library/stdtypes#bytearray.find) + [(bytes method)](library/stdtypes#bytes.find) + [(doctest.DocTestFinder method)](library/doctest#doctest.DocTestFinder.find) + [(in module gettext)](library/gettext#gettext.find) + [(mmap.mmap method)](library/mmap#mmap.mmap.find) + [(str method)](library/stdtypes#str.find) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.find) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.find) * [find\_class() (pickle protocol)](library/pickle#index-9) + [(pickle.Unpickler method)](library/pickle#pickle.Unpickler.find_class) * [find\_library() (in module ctypes.util)](library/ctypes#ctypes.util.find_library) * [find\_library\_file() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.find_library_file) * [find\_loader() (importlib.abc.PathEntryFinder method)](library/importlib#importlib.abc.PathEntryFinder.find_loader) + [(importlib.machinery.FileFinder method)](library/importlib#importlib.machinery.FileFinder.find_loader) + [(in module importlib)](library/importlib#importlib.find_loader) + [(in module pkgutil)](library/pkgutil#pkgutil.find_loader) * [find\_longest\_match() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.find_longest_match) * [find\_module() (imp.NullImporter method)](library/imp#imp.NullImporter.find_module) + [(importlib.abc.Finder method)](library/importlib#importlib.abc.Finder.find_module) + [(importlib.abc.MetaPathFinder method)](library/importlib#importlib.abc.MetaPathFinder.find_module) + [(importlib.abc.PathEntryFinder method)](library/importlib#importlib.abc.PathEntryFinder.find_module) + [(importlib.machinery.PathFinder class method)](library/importlib#importlib.machinery.PathFinder.find_module) + [(in module imp)](library/imp#imp.find_module) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.find_module) * [find\_msvcrt() (in module ctypes.util)](library/ctypes#ctypes.util.find_msvcrt) * find\_spec + [finder](reference/import#index-10) * [find\_spec() (importlib.abc.MetaPathFinder method)](library/importlib#importlib.abc.MetaPathFinder.find_spec) + [(importlib.abc.PathEntryFinder method)](library/importlib#importlib.abc.PathEntryFinder.find_spec) + [(importlib.machinery.FileFinder method)](library/importlib#importlib.machinery.FileFinder.find_spec) + [(importlib.machinery.PathFinder class method)](library/importlib#importlib.machinery.PathFinder.find_spec) + [(in module importlib.util)](library/importlib#importlib.util.find_spec) * [find\_unused\_port() (in module test.support.socket\_helper)](library/test#test.support.socket_helper.find_unused_port) * [find\_user\_password() (urllib.request.HTTPPasswordMgr method)](library/urllib.request#urllib.request.HTTPPasswordMgr.find_user_password) + [(urllib.request.HTTPPasswordMgrWithPriorAuth method)](library/urllib.request#urllib.request.HTTPPasswordMgrWithPriorAuth.find_user_password) * [findall() (in module re)](library/re#re.findall) + [(re.Pattern method)](library/re#re.Pattern.findall) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.findall) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.findall) * [findCaller() (logging.Logger method)](library/logging#logging.Logger.findCaller) * [finder](reference/import#index-8), [**[1]**](glossary#term-finder) + [find\_spec](reference/import#index-10) * [Finder (class in importlib.abc)](library/importlib#importlib.abc.Finder) * [findfactor() (in module audioop)](library/audioop#audioop.findfactor) * [findfile() (in module test.support)](library/test#test.support.findfile) * [findfit() (in module audioop)](library/audioop#audioop.findfit) * [finditer() (in module re)](library/re#re.finditer) + [(re.Pattern method)](library/re#re.Pattern.finditer) * [findlabels() (in module dis)](library/dis#dis.findlabels) * [findlinestarts() (in module dis)](library/dis#dis.findlinestarts) * [findmatch() (in module mailcap)](library/mailcap#mailcap.findmatch) * [findmax() (in module audioop)](library/audioop#audioop.findmax) * [findtext() (xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.findtext) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.findtext) * [finish() (socketserver.BaseRequestHandler method)](library/socketserver#socketserver.BaseRequestHandler.finish) + [(tkinter.dnd.DndHandler method)](library/tkinter.dnd#tkinter.dnd.DndHandler.finish) * [finish\_request() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.finish_request) * [firstChild (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.firstChild) | * [firstkey() (dbm.gnu.gdbm method)](library/dbm#dbm.gnu.gdbm.firstkey) * [firstweekday() (in module calendar)](library/calendar#calendar.firstweekday) * [fix\_missing\_locations() (in module ast)](library/ast#ast.fix_missing_locations) * [fix\_sentence\_endings (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.fix_sentence_endings) * [Flag (class in enum)](library/enum#enum.Flag) * [flag\_bits (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.flag_bits) * [flags (in module sys)](library/sys#sys.flags) + [(re.Pattern attribute)](library/re#re.Pattern.flags) + [(select.kevent attribute)](library/select#select.kevent.flags) * [flash() (in module curses)](library/curses#curses.flash) * [flatten() (email.generator.BytesGenerator method)](library/email.generator#email.generator.BytesGenerator.flatten) + [(email.generator.Generator method)](library/email.generator#email.generator.Generator.flatten) * flattening + [objects](library/pickle#index-0) * float + [built-in function](c-api/number#index-5), [[1]](library/stdtypes#index-13), [[2]](reference/datamodel#index-100) * [float (built-in class)](library/functions#float) * [float\_info (in module sys)](library/sys#sys.float_info) * [float\_repr\_style (in module sys)](library/sys#sys.float_repr_style) * floating point + [literals](library/stdtypes#index-12) + [number](reference/datamodel#index-13) + [object](c-api/float#index-0), [[1]](library/stdtypes#index-11), [[2]](reference/datamodel#index-13) * [floating point literal](reference/lexical_analysis#index-26) * [FloatingPointError](library/exceptions#FloatingPointError) * [FloatOperation (class in decimal)](library/decimal#decimal.FloatOperation) * [flock() (in module fcntl)](library/fcntl#fcntl.flock) * [**floor division**](glossary#term-floor-division) * [floor() (in module math)](library/math#math.floor), [[1]](library/stdtypes#index-15) * [FloorDiv (class in ast)](library/ast#ast.FloorDiv) * [floordiv() (in module operator)](library/operator#operator.floordiv) * [flush() (bz2.BZ2Compressor method)](library/bz2#bz2.BZ2Compressor.flush) + [(formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.flush) + [(io.BufferedWriter method)](library/io#io.BufferedWriter.flush) + [(io.IOBase method)](library/io#io.IOBase.flush) + [(logging.Handler method)](library/logging#logging.Handler.flush) + [(logging.handlers.BufferingHandler method)](library/logging.handlers#logging.handlers.BufferingHandler.flush) + [(logging.handlers.MemoryHandler method)](library/logging.handlers#logging.handlers.MemoryHandler.flush) + [(logging.StreamHandler method)](library/logging.handlers#logging.StreamHandler.flush) + [(lzma.LZMACompressor method)](library/lzma#lzma.LZMACompressor.flush) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.flush) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.flush) + [(mailbox.MH method)](library/mailbox#mailbox.MH.flush) + [(mmap.mmap method)](library/mmap#mmap.mmap.flush) + [(zlib.Compress method)](library/zlib#zlib.Compress.flush) + [(zlib.Decompress method)](library/zlib#zlib.Decompress.flush) * [flush\_headers() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.flush_headers) * [flush\_softspace() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.flush_softspace) * [flushinp() (in module curses)](library/curses#curses.flushinp) * [FlushKey() (in module winreg)](library/winreg#winreg.FlushKey) * [fma() (decimal.Context method)](library/decimal#decimal.Context.fma) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.fma) * [fmean() (in module statistics)](library/statistics#statistics.fmean) * [fmod() (in module math)](library/math#math.fmod) * [FMT\_BINARY (in module plistlib)](library/plistlib#plistlib.FMT_BINARY) * [FMT\_XML (in module plistlib)](library/plistlib#plistlib.FMT_XML) * [fnmatch (module)](library/fnmatch#module-fnmatch) * [fnmatch() (in module fnmatch)](library/fnmatch#fnmatch.fnmatch) * [fnmatchcase() (in module fnmatch)](library/fnmatch#fnmatch.fnmatchcase) * [focus() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.focus) * [fold (datetime.datetime attribute)](library/datetime#datetime.datetime.fold) + [(datetime.time attribute)](library/datetime#datetime.time.fold) * [fold() (email.headerregistry.BaseHeader method)](library/email.headerregistry#email.headerregistry.BaseHeader.fold) + [(email.policy.Compat32 method)](library/email.policy#email.policy.Compat32.fold) + [(email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.fold) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.fold) * [fold\_binary() (email.policy.Compat32 method)](library/email.policy#email.policy.Compat32.fold_binary) + [(email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.fold_binary) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.fold_binary) * [Font (class in tkinter.font)](library/tkinter.font#tkinter.font.Font) * for + [in comprehensions](reference/expressions#index-12) + [statement](reference/simple_stmts#index-30), [[1]](reference/simple_stmts#index-33), [[2]](tutorial/controlflow#index-0), [**[3]**](reference/compound_stmts#index-6) * [For (class in ast)](library/ast#ast.For) * [FOR\_ITER (opcode)](library/dis#opcode-FOR_ITER) * [forget() (in module test.support)](library/test#test.support.forget) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.forget) * [fork() (in module os)](library/os#os.fork) + [(in module pty)](library/pty#pty.fork) * [ForkingMixIn (class in socketserver)](library/socketserver#socketserver.ForkingMixIn) * [ForkingTCPServer (class in socketserver)](library/socketserver#socketserver.ForkingTCPServer) * [ForkingUDPServer (class in socketserver)](library/socketserver#socketserver.ForkingUDPServer) * [forkpty() (in module os)](library/os#os.forkpty) * form + [lambda](reference/expressions#index-89) * [Form (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Form) * [format (memoryview attribute)](library/stdtypes#memoryview.format) + [(multiprocessing.shared\_memory.ShareableList attribute)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.ShareableList.format) + [(struct.Struct attribute)](library/struct#struct.Struct.format) * [format() (built-in function)](library/functions#format) + [\_\_str\_\_() (object method)](reference/datamodel#index-72) * [format() (in module locale)](library/locale#locale.format) + [(logging.Formatter method)](library/logging#logging.Formatter.format) + [(logging.Handler method)](library/logging#logging.Handler.format) + [(pprint.PrettyPrinter method)](library/pprint#pprint.PrettyPrinter.format) + [(str method)](library/stdtypes#str.format) + [(string.Formatter method)](library/string#string.Formatter.format) + [(traceback.StackSummary method)](library/traceback#traceback.StackSummary.format) + [(traceback.TracebackException method)](library/traceback#traceback.TracebackException.format) + [(tracemalloc.Traceback method)](library/tracemalloc#tracemalloc.Traceback.format) * [format\_datetime() (in module email.utils)](library/email.utils#email.utils.format_datetime) * [format\_exc() (in module traceback)](library/traceback#traceback.format_exc) * [format\_exception() (in module traceback)](library/traceback#traceback.format_exception) * [format\_exception\_only() (in module traceback)](library/traceback#traceback.format_exception_only) + [(traceback.TracebackException method)](library/traceback#traceback.TracebackException.format_exception_only) * [format\_field() (string.Formatter method)](library/string#string.Formatter.format_field) * [format\_help() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.format_help) * [format\_list() (in module traceback)](library/traceback#traceback.format_list) * [format\_map() (str method)](library/stdtypes#str.format_map) * [format\_stack() (in module traceback)](library/traceback#traceback.format_stack) * [format\_stack\_entry() (bdb.Bdb method)](library/bdb#bdb.Bdb.format_stack_entry) * [format\_string() (in module locale)](library/locale#locale.format_string) * [format\_tb() (in module traceback)](library/traceback#traceback.format_tb) * [format\_usage() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.format_usage) * [FORMAT\_VALUE (opcode)](library/dis#opcode-FORMAT_VALUE) * [formataddr() (in module email.utils)](library/email.utils#email.utils.formataddr) * [formatargspec() (in module inspect)](library/inspect#inspect.formatargspec) * [formatargvalues() (in module inspect)](library/inspect#inspect.formatargvalues) * [formatdate() (in module email.utils)](library/email.utils#email.utils.formatdate) * [FormatError](library/mailbox#mailbox.FormatError) * [FormatError() (in module ctypes)](library/ctypes#ctypes.FormatError) * [formatException() (logging.Formatter method)](library/logging#logging.Formatter.formatException) * [formatmonth() (calendar.HTMLCalendar method)](library/calendar#calendar.HTMLCalendar.formatmonth) + [(calendar.TextCalendar method)](library/calendar#calendar.TextCalendar.formatmonth) * [formatStack() (logging.Formatter method)](library/logging#logging.Formatter.formatStack) * [formatted string literal](reference/lexical_analysis#index-24) * [FormattedValue (class in ast)](library/ast#ast.FormattedValue) * [Formatter (class in logging)](library/logging#logging.Formatter) + [(class in string)](library/string#string.Formatter) * [formatter (module)](https://docs.python.org/3.9/library/formatter.html#module-formatter) * [formatTime() (logging.Formatter method)](library/logging#logging.Formatter.formatTime) * formatting + [bytearray (%)](library/stdtypes#index-43) + [bytes (%)](library/stdtypes#index-43) * [formatting, string (%)](library/stdtypes#index-33) * [formatwarning() (in module warnings)](library/warnings#warnings.formatwarning) * [formatyear() (calendar.HTMLCalendar method)](library/calendar#calendar.HTMLCalendar.formatyear) + [(calendar.TextCalendar method)](library/calendar#calendar.TextCalendar.formatyear) * [formatyearpage() (calendar.HTMLCalendar method)](library/calendar#calendar.HTMLCalendar.formatyearpage) * [Fortran contiguous](c-api/buffer#index-2), [[1]](glossary#index-10) * [forward() (in module turtle)](library/turtle#turtle.forward) * [ForwardRef (class in typing)](library/typing#typing.ForwardRef) * [found\_terminator() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.found_terminator) * [fpathconf() (in module os)](library/os#os.fpathconf) * [fqdn (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.fqdn) * [Fraction (class in fractions)](library/fractions#fractions.Fraction) * [fractions (module)](library/fractions#module-fractions) * frame + [execution](reference/compound_stmts#index-31), [[1]](reference/executionmodel#index-2) + [object](reference/datamodel#index-59) * [Frame (class in tracemalloc)](library/tracemalloc#tracemalloc.Frame) * [frame (tkinter.scrolledtext.ScrolledText attribute)](library/tkinter.scrolledtext#tkinter.scrolledtext.ScrolledText.frame) * [FrameSummary (class in traceback)](library/traceback#traceback.FrameSummary) * [FrameType (in module types)](library/types#types.FrameType) * free + [variable](reference/executionmodel#index-6) * [free()](c-api/memory#index-0) * [freefunc (C type)](c-api/typeobj#c.freefunc) * [freeze utility](c-api/import#index-4) * [freeze() (in module gc)](library/gc#gc.freeze) * [freeze\_support() (in module multiprocessing)](library/multiprocessing#multiprocessing.freeze_support) * [frexp() (in module math)](library/math#math.frexp) * from + [import statement](reference/executionmodel#index-5), [[1]](reference/simple_stmts#index-36) + [keyword](reference/expressions#index-23), [[1]](reference/simple_stmts#index-34) + [yield from expression](reference/expressions#index-25) * [from\_address() (ctypes.\_CData method)](library/ctypes#ctypes._CData.from_address) * [from\_buffer() (ctypes.\_CData method)](library/ctypes#ctypes._CData.from_buffer) * [from\_buffer\_copy() (ctypes.\_CData method)](library/ctypes#ctypes._CData.from_buffer_copy) * [from\_bytes() (int class method)](library/stdtypes#int.from_bytes) * [from\_callable() (inspect.Signature class method)](library/inspect#inspect.Signature.from_callable) * [from\_decimal() (fractions.Fraction method)](library/fractions#fractions.Fraction.from_decimal) * [from\_exception() (traceback.TracebackException class method)](library/traceback#traceback.TracebackException.from_exception) * [from\_file() (zipfile.ZipInfo class method)](library/zipfile#zipfile.ZipInfo.from_file) + [(zoneinfo.ZoneInfo class method)](library/zoneinfo#zoneinfo.ZoneInfo.from_file) * [from\_float() (decimal.Decimal method)](library/decimal#decimal.Decimal.from_float) + [(fractions.Fraction method)](library/fractions#fractions.Fraction.from_float) * [from\_iterable() (itertools.chain class method)](library/itertools#itertools.chain.from_iterable) * [from\_list() (traceback.StackSummary class method)](library/traceback#traceback.StackSummary.from_list) * [from\_param() (ctypes.\_CData method)](library/ctypes#ctypes._CData.from_param) * [from\_samples() (statistics.NormalDist class method)](library/statistics#statistics.NormalDist.from_samples) * [from\_traceback() (dis.Bytecode class method)](library/dis#dis.Bytecode.from_traceback) * [frombuf() (tarfile.TarInfo class method)](library/tarfile#tarfile.TarInfo.frombuf) * [frombytes() (array.array method)](library/array#array.array.frombytes) * [fromfd() (in module socket)](library/socket#socket.fromfd) + [(select.epoll method)](library/select#select.epoll.fromfd) + [(select.kqueue method)](library/select#select.kqueue.fromfd) * [fromfile() (array.array method)](library/array#array.array.fromfile) * [fromhex() (bytearray class method)](library/stdtypes#bytearray.fromhex) + [(bytes class method)](library/stdtypes#bytes.fromhex) + [(float class method)](library/stdtypes#float.fromhex) * [fromisocalendar() (datetime.date class method)](library/datetime#datetime.date.fromisocalendar) + [(datetime.datetime class method)](library/datetime#datetime.datetime.fromisocalendar) * [fromisoformat() (datetime.date class method)](library/datetime#datetime.date.fromisoformat) + [(datetime.datetime class method)](library/datetime#datetime.datetime.fromisoformat) + [(datetime.time class method)](library/datetime#datetime.time.fromisoformat) * [fromkeys() (collections.Counter method)](library/collections#collections.Counter.fromkeys) + [(dict class method)](library/stdtypes#dict.fromkeys) * [fromlist() (array.array method)](library/array#array.array.fromlist) * [fromordinal() (datetime.date class method)](library/datetime#datetime.date.fromordinal) + [(datetime.datetime class method)](library/datetime#datetime.datetime.fromordinal) * [fromshare() (in module socket)](library/socket#socket.fromshare) * [fromstring() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.fromstring) * [fromstringlist() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.fromstringlist) * [fromtarfile() (tarfile.TarInfo class method)](library/tarfile#tarfile.TarInfo.fromtarfile) * [fromtimestamp() (datetime.date class method)](library/datetime#datetime.date.fromtimestamp) + [(datetime.datetime class method)](library/datetime#datetime.datetime.fromtimestamp) * [fromunicode() (array.array method)](library/array#array.array.fromunicode) * [fromutc() (datetime.timezone method)](library/datetime#datetime.timezone.fromutc) + [(datetime.tzinfo method)](library/datetime#datetime.tzinfo.fromutc) * [FrozenImporter (class in importlib.machinery)](library/importlib#importlib.machinery.FrozenImporter) * [FrozenInstanceError](library/dataclasses#dataclasses.FrozenInstanceError) * frozenset + [object](c-api/set#index-0), [[1]](reference/datamodel#index-28) * [frozenset (built-in class)](library/stdtypes#frozenset) * [FrozenSet (class in typing)](library/typing#typing.FrozenSet) * [fs\_is\_case\_insensitive() (in module test.support)](library/test#test.support.fs_is_case_insensitive) * [FS\_NONASCII (in module test.support)](library/test#test.support.FS_NONASCII) * [fsdecode() (in module os)](library/os#os.fsdecode) * [fsencode() (in module os)](library/os#os.fsencode) * [fspath() (in module os)](library/os#os.fspath) * [fstat() (in module os)](library/os#os.fstat) * [fstatvfs() (in module os)](library/os#os.fstatvfs) * [fstring](reference/lexical_analysis#index-24) * [fsum() (in module math)](library/math#math.fsum) * [fsync() (in module os)](library/os#os.fsync) * [FTP](library/urllib.request#index-13) + [ftplib (standard module)](library/ftplib#index-0) + [protocol](library/ftplib#index-0), [[1]](library/urllib.request#index-11) * [FTP (class in ftplib)](library/ftplib#ftplib.FTP) * [ftp\_open() (urllib.request.FTPHandler method)](library/urllib.request#urllib.request.FTPHandler.ftp_open) * [FTP\_TLS (class in ftplib)](library/ftplib#ftplib.FTP_TLS) * [FTPHandler (class in urllib.request)](library/urllib.request#urllib.request.FTPHandler) * [ftplib (module)](library/ftplib#module-ftplib) * [ftruncate() (in module os)](library/os#os.ftruncate) * [Full](library/queue#queue.Full) * [full() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.full) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.full) + [(queue.Queue method)](library/queue#queue.Queue.full) * [full\_url (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.full_url) * [fullmatch() (in module re)](library/re#re.fullmatch) + [(re.Pattern method)](library/re#re.Pattern.fullmatch) * [func (functools.partial attribute)](library/functools#functools.partial.func) * [funcattrs (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-funcattrs) * [**function**](glossary#term-function) + [annotations](reference/compound_stmts#index-25), [[1]](tutorial/controlflow#index-5) + [anonymous](reference/expressions#index-89) + [argument](reference/datamodel#index-32) + [call](reference/datamodel#index-32), [[1]](reference/expressions#index-52), [[2]](reference/expressions#index-53) + [call, user-defined](reference/expressions#index-52) + [definition](reference/compound_stmts#index-19), [[1]](reference/simple_stmts#index-24) + [generator](reference/expressions#index-23), [[1]](reference/simple_stmts#index-26) + [name](reference/compound_stmts#index-19), [[1]](reference/compound_stmts#index-19) + [object](c-api/function#index-0), [[1]](reference/compound_stmts#index-19), [[2]](reference/datamodel#index-33), [[3]](reference/datamodel#index-40), [[4]](reference/expressions#index-52), [[5]](reference/expressions#index-53) + [user-defined](reference/datamodel#index-33) * [Function (class in symtable)](library/symtable#symtable.Function) * [**function annotation**](glossary#term-function-annotation) * [FunctionDef (class in ast)](library/ast#ast.FunctionDef) * [FunctionTestCase (class in unittest)](library/unittest#unittest.FunctionTestCase) * [FunctionType (in module types)](library/types#types.FunctionType) * [functools (module)](library/functools#module-functools) * [funny\_files (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.funny_files) * future + [statement](reference/simple_stmts#index-40) * [future (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-future) * [Future (class in asyncio)](library/asyncio-future#asyncio.Future) + [(class in concurrent.futures)](library/concurrent.futures#concurrent.futures.Future) * [FutureWarning](library/exceptions#FutureWarning) * [fwalk() (in module os)](library/os#os.fwalk) | G - | | | | --- | --- | | * [G.722](library/aifc#index-2) * [gaierror](library/socket#socket.gaierror) * [gamma() (in module math)](library/math#math.gamma) * [gammavariate() (in module random)](library/random#random.gammavariate) * [garbage (in module gc)](library/gc#gc.garbage) * [garbage collection](reference/datamodel#index-2), [**[1]**](glossary#term-garbage-collection) * [gather() (curses.textpad.Textbox method)](library/curses#curses.textpad.Textbox.gather) + [(in module asyncio)](library/asyncio-task#asyncio.gather) * [gauss() (in module random)](library/random#random.gauss) * [gc (module)](library/gc#module-gc) * [gc\_collect() (in module test.support)](library/test#test.support.gc_collect) * [gcd() (in module math)](library/math#math.gcd) * [ge() (in module operator)](library/operator#operator.ge) * [gen\_lib\_options() (in module distutils.ccompiler)](distutils/apiref#distutils.ccompiler.gen_lib_options) * [gen\_preprocess\_options() (in module distutils.ccompiler)](distutils/apiref#distutils.ccompiler.gen_preprocess_options) * [gen\_uuid() (in module msilib)](library/msilib#msilib.gen_uuid) * [generate\_help() (distutils.fancy\_getopt.FancyGetopt method)](distutils/apiref#distutils.fancy_getopt.FancyGetopt.generate_help) * [generate\_tokens() (in module tokenize)](library/tokenize#tokenize.generate_tokens) * [generator](glossary#index-19), [**[1]**](glossary#term-generator) + [expression](reference/expressions#index-22) + [function](reference/datamodel#index-37), [[1]](reference/expressions#index-23), [[2]](reference/simple_stmts#index-26) + [iterator](reference/datamodel#index-37), [[1]](reference/simple_stmts#index-26) + [object](reference/datamodel#index-57), [[1]](reference/expressions#index-22), [[2]](reference/expressions#index-31) * [Generator (class in collections.abc)](library/collections.abc#collections.abc.Generator) + [(class in email.generator)](library/email.generator#email.generator.Generator) + [(class in typing)](library/typing#typing.Generator) * [generator expression](glossary#index-20), [**[1]**](glossary#term-generator-expression) * [**generator iterator**](glossary#term-generator-iterator) * [GeneratorExit](library/exceptions#GeneratorExit) + [exception](reference/expressions#index-33), [[1]](reference/expressions#index-37) * [GeneratorExp (class in ast)](library/ast#ast.GeneratorExp) * [GeneratorType (in module types)](library/types#types.GeneratorType) * Generic + [Alias](library/stdtypes#index-53) * generic + [special attribute](reference/datamodel#index-5) * [Generic (class in typing)](library/typing#typing.Generic) * [**generic function**](glossary#term-generic-function) * [**generic type**](glossary#term-generic-type) * [generic\_visit() (ast.NodeVisitor method)](library/ast#ast.NodeVisitor.generic_visit) * GenericAlias + [object](library/stdtypes#index-53) * [GenericAlias (class in types)](library/types#types.GenericAlias) * [genops() (in module pickletools)](library/pickletools#pickletools.genops) * [geometric\_mean() (in module statistics)](library/statistics#statistics.geometric_mean) * [get() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.get) + [(configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.get) + [(contextvars.Context method)](library/contextvars#contextvars.Context.get) + [(contextvars.ContextVar method)](library/contextvars#contextvars.ContextVar.get) + [(dict method)](library/stdtypes#dict.get) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get) + [(in module webbrowser)](library/webbrowser#webbrowser.get) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.get) + [(multiprocessing.pool.AsyncResult method)](library/multiprocessing#multiprocessing.pool.AsyncResult.get) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.get) + [(multiprocessing.SimpleQueue method)](library/multiprocessing#multiprocessing.SimpleQueue.get) + [(ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.get) + [(queue.Queue method)](library/queue#queue.Queue.get) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.get) + [(tkinter.ttk.Combobox method)](library/tkinter.ttk#tkinter.ttk.Combobox.get) + [(tkinter.ttk.Spinbox method)](library/tkinter.ttk#tkinter.ttk.Spinbox.get) + [(types.MappingProxyType method)](library/types#types.MappingProxyType.get) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.get) * [GET\_AITER (opcode)](library/dis#opcode-GET_AITER) * [get\_all() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_all) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_all) + [(wsgiref.headers.Headers method)](library/wsgiref#wsgiref.headers.Headers.get_all) * [get\_all\_breaks() (bdb.Bdb method)](library/bdb#bdb.Bdb.get_all_breaks) * [get\_all\_start\_methods() (in module multiprocessing)](library/multiprocessing#multiprocessing.get_all_start_methods) * [GET\_ANEXT (opcode)](library/dis#opcode-GET_ANEXT) * [get\_app() (wsgiref.simple\_server.WSGIServer method)](library/wsgiref#wsgiref.simple_server.WSGIServer.get_app) * [get\_archive\_formats() (in module shutil)](library/shutil#shutil.get_archive_formats) * [get\_args() (in module typing)](library/typing#typing.get_args) * [get\_asyncgen\_hooks() (in module sys)](library/sys#sys.get_asyncgen_hooks) * [get\_attribute() (in module test.support)](library/test#test.support.get_attribute) * [GET\_AWAITABLE (opcode)](library/dis#opcode-GET_AWAITABLE) * [get\_begidx() (in module readline)](library/readline#readline.get_begidx) * [get\_blocking() (in module os)](library/os#os.get_blocking) * [get\_body() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_body) * [get\_body\_encoding() (email.charset.Charset method)](library/email.charset#email.charset.Charset.get_body_encoding) * [get\_boundary() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_boundary) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_boundary) * [get\_bpbynumber() (bdb.Bdb method)](library/bdb#bdb.Bdb.get_bpbynumber) * [get\_break() (bdb.Bdb method)](library/bdb#bdb.Bdb.get_break) * [get\_breaks() (bdb.Bdb method)](library/bdb#bdb.Bdb.get_breaks) * [get\_buffer() (asyncio.BufferedProtocol method)](library/asyncio-protocol#asyncio.BufferedProtocol.get_buffer) + [(xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.get_buffer) + [(xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.get_buffer) * [get\_bytes() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.get_bytes) * [get\_ca\_certs() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.get_ca_certs) * [get\_cache\_token() (in module abc)](library/abc#abc.get_cache_token) * [get\_channel\_binding() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.get_channel_binding) * [get\_charset() (email.message.Message method)](library/email.compat32-message#email.message.Message.get_charset) * [get\_charsets() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_charsets) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_charsets) * [get\_child\_watcher() (asyncio.AbstractEventLoopPolicy method)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy.get_child_watcher) + [(in module asyncio)](library/asyncio-policy#asyncio.get_child_watcher) * [get\_children() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_children) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.get_children) * [get\_ciphers() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.get_ciphers) * [get\_clock\_info() (in module time)](library/time#time.get_clock_info) * [get\_close\_matches() (in module difflib)](library/difflib#difflib.get_close_matches) * [get\_code() (importlib.abc.InspectLoader method)](library/importlib#importlib.abc.InspectLoader.get_code) + [(importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.get_code) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.get_code) + [(importlib.machinery.SourcelessFileLoader method)](library/importlib#importlib.machinery.SourcelessFileLoader.get_code) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.get_code) * [get\_completer() (in module readline)](library/readline#readline.get_completer) * [get\_completer\_delims() (in module readline)](library/readline#readline.get_completer_delims) * [get\_completion\_type() (in module readline)](library/readline#readline.get_completion_type) * [get\_config\_h\_filename() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_config_h_filename) + [(in module sysconfig)](library/sysconfig#sysconfig.get_config_h_filename) * [get\_config\_var() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_config_var) + [(in module sysconfig)](library/sysconfig#sysconfig.get_config_var) * [get\_config\_vars() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_config_vars) + [(in module sysconfig)](library/sysconfig#sysconfig.get_config_vars) * [get\_content() (email.contentmanager.ContentManager method)](library/email.contentmanager#email.contentmanager.ContentManager.get_content) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content) + [(in module email.contentmanager)](library/email.contentmanager#email.contentmanager.get_content) * [get\_content\_charset() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content_charset) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_content_charset) * [get\_content\_disposition() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content_disposition) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_content_disposition) * [get\_content\_maintype() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content_maintype) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_content_maintype) * [get\_content\_subtype() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content_subtype) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_content_subtype) * [get\_content\_type() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_content_type) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_content_type) * [get\_context() (in module multiprocessing)](library/multiprocessing#multiprocessing.get_context) * [get\_coro() (asyncio.Task method)](library/asyncio-task#asyncio.Task.get_coro) * [get\_coroutine\_origin\_tracking\_depth() (in module sys)](library/sys#sys.get_coroutine_origin_tracking_depth) * [get\_count() (in module gc)](library/gc#gc.get_count) * [get\_current\_history\_length() (in module readline)](library/readline#readline.get_current_history_length) * [get\_data() (importlib.abc.FileLoader method)](library/importlib#importlib.abc.FileLoader.get_data) + [(importlib.abc.ResourceLoader method)](library/importlib#importlib.abc.ResourceLoader.get_data) + [(in module pkgutil)](library/pkgutil#pkgutil.get_data) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.get_data) * [get\_date() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.get_date) * [get\_debug() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.get_debug) + [(in module gc)](library/gc#gc.get_debug) * [get\_default() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.get_default) * [get\_default\_compiler() (in module distutils.ccompiler)](distutils/apiref#distutils.ccompiler.get_default_compiler) * [get\_default\_domain() (in module nis)](library/nis#nis.get_default_domain) * [get\_default\_type() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_default_type) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_default_type) * [get\_default\_verify\_paths() (in module ssl)](library/ssl#ssl.get_default_verify_paths) * [get\_dialect() (in module csv)](library/csv#csv.get_dialect) * [get\_disassembly\_as\_string() (test.support.bytecode\_helper.BytecodeTestCase method)](library/test#test.support.bytecode_helper.BytecodeTestCase.get_disassembly_as_string) * [get\_docstring() (in module ast)](library/ast#ast.get_docstring) * [get\_doctest() (doctest.DocTestParser method)](library/doctest#doctest.DocTestParser.get_doctest) * [get\_endidx() (in module readline)](library/readline#readline.get_endidx) * [get\_environ() (wsgiref.simple\_server.WSGIRequestHandler method)](library/wsgiref#wsgiref.simple_server.WSGIRequestHandler.get_environ) * [get\_errno() (in module ctypes)](library/ctypes#ctypes.get_errno) * [get\_escdelay() (in module curses)](library/curses#curses.get_escdelay) * [get\_event\_loop() (asyncio.AbstractEventLoopPolicy method)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy.get_event_loop) + [(in module asyncio)](library/asyncio-eventloop#asyncio.get_event_loop) * [get\_event\_loop\_policy() (in module asyncio)](library/asyncio-policy#asyncio.get_event_loop_policy) * [get\_examples() (doctest.DocTestParser method)](library/doctest#doctest.DocTestParser.get_examples) * [get\_exception\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.get_exception_handler) * [get\_exec\_path() (in module os)](library/os#os.get_exec_path) * [get\_extra\_info() (asyncio.BaseTransport method)](library/asyncio-protocol#asyncio.BaseTransport.get_extra_info) + [(asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.get_extra_info) * [get\_field() (string.Formatter method)](library/string#string.Formatter.get_field) * [get\_file() (mailbox.Babyl method)](library/mailbox#mailbox.Babyl.get_file) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.get_file) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.get_file) + [(mailbox.mbox method)](library/mailbox#mailbox.mbox.get_file) + [(mailbox.MH method)](library/mailbox#mailbox.MH.get_file) + [(mailbox.MMDF method)](library/mailbox#mailbox.MMDF.get_file) * [get\_file\_breaks() (bdb.Bdb method)](library/bdb#bdb.Bdb.get_file_breaks) * [get\_filename() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_filename) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_filename) + [(importlib.abc.ExecutionLoader method)](library/importlib#importlib.abc.ExecutionLoader.get_filename) + [(importlib.abc.FileLoader method)](library/importlib#importlib.abc.FileLoader.get_filename) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.get_filename) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.get_filename) * [get\_filter() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.get_filter) * [get\_flags() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.get_flags) + [(mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.get_flags) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.get_flags) * [get\_folder() (mailbox.Maildir method)](library/mailbox#mailbox.Maildir.get_folder) + [(mailbox.MH method)](library/mailbox#mailbox.MH.get_folder) * [get\_frees() (symtable.Function method)](library/symtable#symtable.Function.get_frees) * [get\_freeze\_count() (in module gc)](library/gc#gc.get_freeze_count) * [get\_from() (mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.get_from) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.get_from) * [get\_full\_url() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.get_full_url) * [get\_globals() (symtable.Function method)](library/symtable#symtable.Function.get_globals) * [get\_grouped\_opcodes() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.get_grouped_opcodes) * [get\_handle\_inheritable() (in module os)](library/os#os.get_handle_inheritable) * [get\_header() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.get_header) * [get\_history\_item() (in module readline)](library/readline#readline.get_history_item) * [get\_history\_length() (in module readline)](library/readline#readline.get_history_length) * [get\_id() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_id) * [get\_ident() (in module \_thread)](library/_thread#_thread.get_ident) + [(in module threading)](library/threading#threading.get_ident) * [get\_identifiers() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_identifiers) * [get\_importer() (in module pkgutil)](library/pkgutil#pkgutil.get_importer) * [get\_info() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.get_info) * [get\_inheritable() (in module os)](library/os#os.get_inheritable) + [(socket.socket method)](library/socket#socket.socket.get_inheritable) * [get\_instructions() (in module dis)](library/dis#dis.get_instructions) * [get\_int\_max\_str\_digits() (in module sys)](library/sys#sys.get_int_max_str_digits) * [get\_interpreter() (in module zipapp)](library/zipapp#zipapp.get_interpreter) * [GET\_ITER (opcode)](library/dis#opcode-GET_ITER) * [get\_key() (selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.get_key) * [get\_labels() (mailbox.Babyl method)](library/mailbox#mailbox.Babyl.get_labels) + [(mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.get_labels) * [get\_last\_error() (in module ctypes)](library/ctypes#ctypes.get_last_error) * [get\_line\_buffer() (in module readline)](library/readline#readline.get_line_buffer) * [get\_lineno() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_lineno) * [get\_loader() (in module pkgutil)](library/pkgutil#pkgutil.get_loader) * [get\_locals() (symtable.Function method)](library/symtable#symtable.Function.get_locals) * [get\_logger() (in module multiprocessing)](library/multiprocessing#multiprocessing.get_logger) * [get\_loop() (asyncio.Future method)](library/asyncio-future#asyncio.Future.get_loop) + [(asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.get_loop) * [get\_magic() (in module imp)](library/imp#imp.get_magic) * [get\_makefile\_filename() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_makefile_filename) + [(in module sysconfig)](library/sysconfig#sysconfig.get_makefile_filename) * [get\_map() (selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.get_map) * [get\_matching\_blocks() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.get_matching_blocks) * [get\_message() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.get_message) * [get\_method() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.get_method) * [get\_methods() (symtable.Class method)](library/symtable#symtable.Class.get_methods) * [get\_mixed\_type\_key() (in module ipaddress)](library/ipaddress#ipaddress.get_mixed_type_key) * [get\_name() (asyncio.Task method)](library/asyncio-task#asyncio.Task.get_name) + [(symtable.Symbol method)](library/symtable#symtable.Symbol.get_name) + [(symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_name) * [get\_namespace() (symtable.Symbol method)](library/symtable#symtable.Symbol.get_namespace) * [get\_namespaces() (symtable.Symbol method)](library/symtable#symtable.Symbol.get_namespaces) * [get\_native\_id() (in module \_thread)](library/_thread#_thread.get_native_id) + [(in module threading)](library/threading#threading.get_native_id) * [get\_nonlocals() (symtable.Function method)](library/symtable#symtable.Function.get_nonlocals) * [get\_nonstandard\_attr() (http.cookiejar.Cookie method)](library/http.cookiejar#http.cookiejar.Cookie.get_nonstandard_attr) * [get\_nowait() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.get_nowait) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.get_nowait) + [(queue.Queue method)](library/queue#queue.Queue.get_nowait) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.get_nowait) * [get\_object\_traceback() (in module tracemalloc)](library/tracemalloc#tracemalloc.get_object_traceback) * [get\_objects() (in module gc)](library/gc#gc.get_objects) * [get\_opcodes() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.get_opcodes) * [get\_option() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.get_option) * [get\_option\_group() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.get_option_group) * [get\_option\_order() (distutils.fancy\_getopt.FancyGetopt method)](distutils/apiref#distutils.fancy_getopt.FancyGetopt.get_option_order) * [get\_origin() (in module typing)](library/typing#typing.get_origin) * [get\_original\_stdout() (in module test.support)](library/test#test.support.get_original_stdout) * [get\_osfhandle() (in module msvcrt)](library/msvcrt#msvcrt.get_osfhandle) * [get\_output\_charset() (email.charset.Charset method)](library/email.charset#email.charset.Charset.get_output_charset) * [get\_param() (email.message.Message method)](library/email.compat32-message#email.message.Message.get_param) * [get\_parameters() (symtable.Function method)](library/symtable#symtable.Function.get_parameters) * [get\_params() (email.message.Message method)](library/email.compat32-message#email.message.Message.get_params) * [get\_path() (in module sysconfig)](library/sysconfig#sysconfig.get_path) * [get\_path\_names() (in module sysconfig)](library/sysconfig#sysconfig.get_path_names) * [get\_paths() (in module sysconfig)](library/sysconfig#sysconfig.get_paths) * [get\_payload() (email.message.Message method)](library/email.compat32-message#email.message.Message.get_payload) * [get\_pid() (asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.get_pid) * [get\_pipe\_transport() (asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.get_pipe_transport) * [get\_platform() (in module distutils.util)](distutils/apiref#distutils.util.get_platform) + [(in module sysconfig)](library/sysconfig#sysconfig.get_platform) * [get\_poly() (in module turtle)](library/turtle#turtle.get_poly) * [get\_position() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.get_position) * [get\_protocol() (asyncio.BaseTransport method)](library/asyncio-protocol#asyncio.BaseTransport.get_protocol) * [get\_python\_inc() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_python_inc) * [get\_python\_lib() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.get_python_lib) * [get\_python\_version() (in module sysconfig)](library/sysconfig#sysconfig.get_python_version) * [get\_ready() (graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.get_ready) * [get\_recsrc() (ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.get_recsrc) * [get\_referents() (in module gc)](library/gc#gc.get_referents) * [get\_referrers() (in module gc)](library/gc#gc.get_referrers) * [get\_request() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.get_request) * [get\_returncode() (asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.get_returncode) * [get\_running\_loop() (in module asyncio)](library/asyncio-eventloop#asyncio.get_running_loop) * [get\_scheme() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.get_scheme) * [get\_scheme\_names() (in module sysconfig)](library/sysconfig#sysconfig.get_scheme_names) * [get\_selection() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.get_selection) * [get\_sequences() (mailbox.MH method)](library/mailbox#mailbox.MH.get_sequences) + [(mailbox.MHMessage method)](library/mailbox#mailbox.MHMessage.get_sequences) * [get\_server() (multiprocessing.managers.BaseManager method)](library/multiprocessing#multiprocessing.managers.BaseManager.get_server) * [get\_server\_certificate() (in module ssl)](library/ssl#ssl.get_server_certificate) * [get\_shapepoly() (in module turtle)](library/turtle#turtle.get_shapepoly) * [get\_socket() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.get_socket) * [get\_source() (importlib.abc.InspectLoader method)](library/importlib#importlib.abc.InspectLoader.get_source) + [(importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.get_source) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.get_source) + [(importlib.machinery.SourcelessFileLoader method)](library/importlib#importlib.machinery.SourcelessFileLoader.get_source) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.get_source) * [get\_source\_segment() (in module ast)](library/ast#ast.get_source_segment) * [get\_special\_folder\_path() (built-in function)](distutils/builtdist#get_special_folder_path) * [get\_stack() (asyncio.Task method)](library/asyncio-task#asyncio.Task.get_stack) + [(bdb.Bdb method)](library/bdb#bdb.Bdb.get_stack) * [get\_start\_method() (in module multiprocessing)](library/multiprocessing#multiprocessing.get_start_method) * [get\_starttag\_text() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.get_starttag_text) * [get\_stats() (in module gc)](library/gc#gc.get_stats) * [get\_stats\_profile() (pstats.Stats method)](library/profile#pstats.Stats.get_stats_profile) * [get\_stderr() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.get_stderr) + [(wsgiref.simple\_server.WSGIRequestHandler method)](library/wsgiref#wsgiref.simple_server.WSGIRequestHandler.get_stderr) * [get\_stdin() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.get_stdin) * [get\_string() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.get_string) * [get\_subdir() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.get_subdir) * [get\_suffixes() (in module imp)](library/imp#imp.get_suffixes) * [get\_symbols() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_symbols) * [get\_tabsize() (in module curses)](library/curses#curses.get_tabsize) * [get\_tag() (in module imp)](library/imp#imp.get_tag) * [get\_task\_factory() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.get_task_factory) * [get\_terminal\_size() (in module os)](library/os#os.get_terminal_size) + [(in module shutil)](library/shutil#shutil.get_terminal_size) * [get\_terminator() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.get_terminator) * [get\_threshold() (in module gc)](library/gc#gc.get_threshold) * [get\_token() (shlex.shlex method)](library/shlex#shlex.shlex.get_token) * [get\_traceback\_limit() (in module tracemalloc)](library/tracemalloc#tracemalloc.get_traceback_limit) * [get\_traced\_memory() (in module tracemalloc)](library/tracemalloc#tracemalloc.get_traced_memory) * [get\_tracemalloc\_memory() (in module tracemalloc)](library/tracemalloc#tracemalloc.get_tracemalloc_memory) * [get\_type() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.get_type) * [get\_type\_hints() (in module typing)](library/typing#typing.get_type_hints) * [get\_unixfrom() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.get_unixfrom) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.get_unixfrom) * [get\_unpack\_formats() (in module shutil)](library/shutil#shutil.get_unpack_formats) * [get\_usage() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.get_usage) * [get\_value() (string.Formatter method)](library/string#string.Formatter.get_value) * [get\_version() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.get_version) * [get\_visible() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.get_visible) * [get\_wch() (curses.window method)](library/curses#curses.window.get_wch) * [get\_write\_buffer\_limits() (asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.get_write_buffer_limits) * [get\_write\_buffer\_size() (asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.get_write_buffer_size) * [GET\_YIELD\_FROM\_ITER (opcode)](library/dis#opcode-GET_YIELD_FROM_ITER) * [getacl() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.getacl) * [getaddresses() (in module email.utils)](library/email.utils#email.utils.getaddresses) * [getaddrinfo() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.getaddrinfo) + [(in module socket)](library/socket#socket.getaddrinfo) * [getallocatedblocks() (in module sys)](library/sys#sys.getallocatedblocks) * [getandroidapilevel() (in module sys)](library/sys#sys.getandroidapilevel) * [getannotation() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.getannotation) * [getargspec() (in module inspect)](library/inspect#inspect.getargspec) * [getargvalues() (in module inspect)](library/inspect#inspect.getargvalues) * [getatime() (in module os.path)](library/os.path#os.path.getatime) * [getattr() (built-in function)](library/functions#getattr) * [getattr\_static() (in module inspect)](library/inspect#inspect.getattr_static) * [getattrfunc (C type)](c-api/typeobj#c.getattrfunc) | * [getAttribute() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.getAttribute) * [getAttributeNode() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.getAttributeNode) * [getAttributeNodeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.getAttributeNodeNS) * [getAttributeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.getAttributeNS) * [getattrofunc (C type)](c-api/typeobj#c.getattrofunc) * [GetBase() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.GetBase) * [getbegyx() (curses.window method)](library/curses#curses.window.getbegyx) * [getbkgd() (curses.window method)](library/curses#curses.window.getbkgd) * [getblocking() (socket.socket method)](library/socket#socket.socket.getblocking) * [getboolean() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.getboolean) * [getbuffer() (io.BytesIO method)](library/io#io.BytesIO.getbuffer) * [getbufferproc (C type)](c-api/typeobj#c.getbufferproc) * [getByteStream() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.getByteStream) * [getcallargs() (in module inspect)](library/inspect#inspect.getcallargs) * [getcanvas() (in module turtle)](library/turtle#turtle.getcanvas) * [getcapabilities() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.getcapabilities) * [getcaps() (in module mailcap)](library/mailcap#mailcap.getcaps) * [getch() (curses.window method)](library/curses#curses.window.getch) + [(in module msvcrt)](library/msvcrt#msvcrt.getch) * [getCharacterStream() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.getCharacterStream) * [getche() (in module msvcrt)](library/msvcrt#msvcrt.getche) * [getChild() (logging.Logger method)](library/logging#logging.Logger.getChild) * [getclasstree() (in module inspect)](library/inspect#inspect.getclasstree) * [getclosurevars() (in module inspect)](library/inspect#inspect.getclosurevars) * [GetColumnInfo() (msilib.View method)](library/msilib#msilib.View.GetColumnInfo) * [getColumnNumber() (xml.sax.xmlreader.Locator method)](library/xml.sax.reader#xml.sax.xmlreader.Locator.getColumnNumber) * [getcomments() (in module inspect)](library/inspect#inspect.getcomments) * [getcompname() (aifc.aifc method)](library/aifc#aifc.aifc.getcompname) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getcompname) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getcompname) * [getcomptype() (aifc.aifc method)](library/aifc#aifc.aifc.getcomptype) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getcomptype) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getcomptype) * [getContentHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getContentHandler) * [getcontext() (in module decimal)](library/decimal#decimal.getcontext) * [getcoroutinelocals() (in module inspect)](library/inspect#inspect.getcoroutinelocals) * [getcoroutinestate() (in module inspect)](library/inspect#inspect.getcoroutinestate) * [getctime() (in module os.path)](library/os.path#os.path.getctime) * [getcwd() (in module os)](library/os#os.getcwd) * [getcwdb() (in module os)](library/os#os.getcwdb) * [getcwdu (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-getcwdu) * [getdecoder() (in module codecs)](library/codecs#codecs.getdecoder) * [getdefaultencoding() (in module sys)](library/sys#sys.getdefaultencoding) * [getdefaultlocale() (in module locale)](library/locale#locale.getdefaultlocale) * [getdefaulttimeout() (in module socket)](library/socket#socket.getdefaulttimeout) * [getdlopenflags() (in module sys)](library/sys#sys.getdlopenflags) * [getdoc() (in module inspect)](library/inspect#inspect.getdoc) * [getDOMImplementation() (in module xml.dom)](library/xml.dom#xml.dom.getDOMImplementation) * [getDTDHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getDTDHandler) * [getEffectiveLevel() (logging.Logger method)](library/logging#logging.Logger.getEffectiveLevel) * [getegid() (in module os)](library/os#os.getegid) * [getElementsByTagName() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.getElementsByTagName) + [(xml.dom.Element method)](library/xml.dom#xml.dom.Element.getElementsByTagName) * [getElementsByTagNameNS() (xml.dom.Document method)](library/xml.dom#xml.dom.Document.getElementsByTagNameNS) + [(xml.dom.Element method)](library/xml.dom#xml.dom.Element.getElementsByTagNameNS) * [getencoder() (in module codecs)](library/codecs#codecs.getencoder) * [getEncoding() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.getEncoding) * [getEntityResolver() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getEntityResolver) * [getenv() (in module os)](library/os#os.getenv) * [getenvb() (in module os)](library/os#os.getenvb) * [getErrorHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getErrorHandler) * [geteuid() (in module os)](library/os#os.geteuid) * [getEvent() (xml.dom.pulldom.DOMEventStream method)](library/xml.dom.pulldom#xml.dom.pulldom.DOMEventStream.getEvent) * [getEventCategory() (logging.handlers.NTEventLogHandler method)](library/logging.handlers#logging.handlers.NTEventLogHandler.getEventCategory) * [getEventType() (logging.handlers.NTEventLogHandler method)](library/logging.handlers#logging.handlers.NTEventLogHandler.getEventType) * [getException() (xml.sax.SAXException method)](library/xml.sax#xml.sax.SAXException.getException) * [getFeature() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getFeature) * [GetFieldCount() (msilib.Record method)](library/msilib#msilib.Record.GetFieldCount) * [getfile() (in module inspect)](library/inspect#inspect.getfile) * [getFilesToDelete() (logging.handlers.TimedRotatingFileHandler method)](library/logging.handlers#logging.handlers.TimedRotatingFileHandler.getFilesToDelete) * [getfilesystemencodeerrors() (in module sys)](library/sys#sys.getfilesystemencodeerrors) * [getfilesystemencoding() (in module sys)](library/sys#sys.getfilesystemencoding) * [getfirst() (cgi.FieldStorage method)](library/cgi#cgi.FieldStorage.getfirst) * [getfloat() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.getfloat) * [getfmts() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.getfmts) * [getfqdn() (in module socket)](library/socket#socket.getfqdn) * [getframeinfo() (in module inspect)](library/inspect#inspect.getframeinfo) * [getframerate() (aifc.aifc method)](library/aifc#aifc.aifc.getframerate) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getframerate) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getframerate) * [getfullargspec() (in module inspect)](library/inspect#inspect.getfullargspec) * [getgeneratorlocals() (in module inspect)](library/inspect#inspect.getgeneratorlocals) * [getgeneratorstate() (in module inspect)](library/inspect#inspect.getgeneratorstate) * [getgid() (in module os)](library/os#os.getgid) * [getgrall() (in module grp)](library/grp#grp.getgrall) * [getgrgid() (in module grp)](library/grp#grp.getgrgid) * [getgrnam() (in module grp)](library/grp#grp.getgrnam) * [getgrouplist() (in module os)](library/os#os.getgrouplist) * [getgroups() (in module os)](library/os#os.getgroups) * [getheader() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.getheader) * [getheaders() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.getheaders) * [gethostbyaddr() (in module socket)](library/os#index-14), [[1]](library/socket#socket.gethostbyaddr) * [gethostbyname() (in module socket)](library/socket#socket.gethostbyname) * [gethostbyname\_ex() (in module socket)](library/socket#socket.gethostbyname_ex) * [gethostname() (in module socket)](library/os#index-14), [[1]](library/socket#socket.gethostname) * [getincrementaldecoder() (in module codecs)](library/codecs#codecs.getincrementaldecoder) * [getincrementalencoder() (in module codecs)](library/codecs#codecs.getincrementalencoder) * [getinfo() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.getinfo) * [getinnerframes() (in module inspect)](library/inspect#inspect.getinnerframes) * [GetInputContext() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.GetInputContext) * [getint() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.getint) * [GetInteger() (msilib.Record method)](library/msilib#msilib.Record.GetInteger) * [getitem() (in module operator)](library/operator#operator.getitem) * [getiterfunc (C type)](c-api/typeobj#c.getiterfunc) * [getitimer() (in module signal)](library/signal#signal.getitimer) * [getkey() (curses.window method)](library/curses#curses.window.getkey) * [GetLastError() (in module ctypes)](library/ctypes#ctypes.GetLastError) * [getLength() (xml.sax.xmlreader.Attributes method)](library/xml.sax.reader#xml.sax.xmlreader.Attributes.getLength) * [getLevelName() (in module logging)](library/logging#logging.getLevelName) * [getline() (in module linecache)](library/linecache#linecache.getline) * [getLineNumber() (xml.sax.xmlreader.Locator method)](library/xml.sax.reader#xml.sax.xmlreader.Locator.getLineNumber) * [getlist() (cgi.FieldStorage method)](library/cgi#cgi.FieldStorage.getlist) * [getloadavg() (in module os)](library/os#os.getloadavg) * [getlocale() (in module locale)](library/locale#locale.getlocale) * [getLogger() (in module logging)](library/logging#logging.getLogger) * [getLoggerClass() (in module logging)](library/logging#logging.getLoggerClass) * [getlogin() (in module os)](library/os#os.getlogin) * [getLogRecordFactory() (in module logging)](library/logging#logging.getLogRecordFactory) * [getmark() (aifc.aifc method)](library/aifc#aifc.aifc.getmark) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getmark) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getmark) * [getmarkers() (aifc.aifc method)](library/aifc#aifc.aifc.getmarkers) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getmarkers) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getmarkers) * [getmaxyx() (curses.window method)](library/curses#curses.window.getmaxyx) * [getmember() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.getmember) * [getmembers() (in module inspect)](library/inspect#inspect.getmembers) + [(tarfile.TarFile method)](library/tarfile#tarfile.TarFile.getmembers) * [getMessage() (logging.LogRecord method)](library/logging#logging.LogRecord.getMessage) + [(xml.sax.SAXException method)](library/xml.sax#xml.sax.SAXException.getMessage) * [getMessageID() (logging.handlers.NTEventLogHandler method)](library/logging.handlers#logging.handlers.NTEventLogHandler.getMessageID) * [getmodule() (in module inspect)](library/inspect#inspect.getmodule) * [getmodulename() (in module inspect)](library/inspect#inspect.getmodulename) * [getmouse() (in module curses)](library/curses#curses.getmouse) * [getmro() (in module inspect)](library/inspect#inspect.getmro) * [getmtime() (in module os.path)](library/os.path#os.path.getmtime) * [getname() (chunk.Chunk method)](library/chunk#chunk.Chunk.getname) * [getName() (threading.Thread method)](library/threading#threading.Thread.getName) * [getNameByQName() (xml.sax.xmlreader.AttributesNS method)](library/xml.sax.reader#xml.sax.xmlreader.AttributesNS.getNameByQName) * [getnameinfo() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.getnameinfo) + [(in module socket)](library/socket#socket.getnameinfo) * [getnames() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.getnames) * [getNames() (xml.sax.xmlreader.Attributes method)](library/xml.sax.reader#xml.sax.xmlreader.Attributes.getNames) * [getnchannels() (aifc.aifc method)](library/aifc#aifc.aifc.getnchannels) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getnchannels) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getnchannels) * [getnframes() (aifc.aifc method)](library/aifc#aifc.aifc.getnframes) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getnframes) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getnframes) * [getnode](library/uuid#index-5) * [getnode() (in module uuid)](library/uuid#uuid.getnode) * [getopt (module)](library/getopt#module-getopt) * [getopt() (distutils.fancy\_getopt.FancyGetopt method)](distutils/apiref#distutils.fancy_getopt.FancyGetopt.getopt) + [(in module getopt)](library/getopt#getopt.getopt) * [GetoptError](library/getopt#getopt.GetoptError) * [getouterframes() (in module inspect)](library/inspect#inspect.getouterframes) * [getoutput() (in module subprocess)](library/subprocess#subprocess.getoutput) * [getpagesize() (in module resource)](library/resource#resource.getpagesize) * [getparams() (aifc.aifc method)](library/aifc#aifc.aifc.getparams) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getparams) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getparams) * [getparyx() (curses.window method)](library/curses#curses.window.getparyx) * [getpass (module)](library/getpass#module-getpass) * [getpass() (in module getpass)](library/getpass#getpass.getpass) * [GetPassWarning](library/getpass#getpass.GetPassWarning) * [getpeercert() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.getpeercert) * [getpeername() (socket.socket method)](library/socket#socket.socket.getpeername) * [getpen() (in module turtle)](library/turtle#turtle.getpen) * [getpgid() (in module os)](library/os#os.getpgid) * [getpgrp() (in module os)](library/os#os.getpgrp) * [getpid() (in module os)](library/os#os.getpid) * [getpos() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.getpos) * [getppid() (in module os)](library/os#os.getppid) * [getpreferredencoding() (in module locale)](library/locale#locale.getpreferredencoding) * [getpriority() (in module os)](library/os#os.getpriority) * [getprofile() (in module sys)](library/sys#sys.getprofile) * [GetProperty() (msilib.SummaryInformation method)](library/msilib#msilib.SummaryInformation.GetProperty) * [getProperty() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.getProperty) * [GetPropertyCount() (msilib.SummaryInformation method)](library/msilib#msilib.SummaryInformation.GetPropertyCount) * [getprotobyname() (in module socket)](library/socket#socket.getprotobyname) * [getproxies() (in module urllib.request)](library/urllib.request#urllib.request.getproxies) * [getPublicId() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.getPublicId) + [(xml.sax.xmlreader.Locator method)](library/xml.sax.reader#xml.sax.xmlreader.Locator.getPublicId) * [getpwall() (in module pwd)](library/pwd#pwd.getpwall) * [getpwnam() (in module pwd)](library/pwd#pwd.getpwnam) * [getpwuid() (in module pwd)](library/pwd#pwd.getpwuid) * [getQNameByName() (xml.sax.xmlreader.AttributesNS method)](library/xml.sax.reader#xml.sax.xmlreader.AttributesNS.getQNameByName) * [getQNames() (xml.sax.xmlreader.AttributesNS method)](library/xml.sax.reader#xml.sax.xmlreader.AttributesNS.getQNames) * [getquota() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.getquota) * [getquotaroot() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.getquotaroot) * [getrandbits() (in module random)](library/random#random.getrandbits) * [getrandom() (in module os)](library/os#os.getrandom) * [getreader() (in module codecs)](library/codecs#codecs.getreader) * [getrecursionlimit() (in module sys)](library/sys#sys.getrecursionlimit) * [getrefcount() (in module sys)](library/sys#sys.getrefcount) * [getresgid() (in module os)](library/os#os.getresgid) * [getresponse() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.getresponse) * [getresuid() (in module os)](library/os#os.getresuid) * [getrlimit() (in module resource)](library/resource#resource.getrlimit) * [getroot() (xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.getroot) * [getrusage() (in module resource)](library/resource#resource.getrusage) * [getsample() (in module audioop)](library/audioop#audioop.getsample) * [getsampwidth() (aifc.aifc method)](library/aifc#aifc.aifc.getsampwidth) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.getsampwidth) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.getsampwidth) * [getscreen() (in module turtle)](library/turtle#turtle.getscreen) * [getservbyname() (in module socket)](library/socket#socket.getservbyname) * [getservbyport() (in module socket)](library/socket#socket.getservbyport) * [GetSetDescriptorType (in module types)](library/types#types.GetSetDescriptorType) * [getshapes() (in module turtle)](library/turtle#turtle.getshapes) * [getsid() (in module os)](library/os#os.getsid) * [getsignal() (in module signal)](library/signal#signal.getsignal) * [getsitepackages() (in module site)](library/site#site.getsitepackages) * [getsize() (chunk.Chunk method)](library/chunk#chunk.Chunk.getsize) + [(in module os.path)](library/os.path#os.path.getsize) * [getsizeof() (in module sys)](library/sys#sys.getsizeof) * [getsockname() (socket.socket method)](library/socket#socket.socket.getsockname) * [getsockopt() (socket.socket method)](library/socket#socket.socket.getsockopt) * [getsource() (in module inspect)](library/inspect#inspect.getsource) * [getsourcefile() (in module inspect)](library/inspect#inspect.getsourcefile) * [getsourcelines() (in module inspect)](library/inspect#inspect.getsourcelines) * [getspall() (in module spwd)](library/spwd#spwd.getspall) * [getspnam() (in module spwd)](library/spwd#spwd.getspnam) * [getstate() (codecs.IncrementalDecoder method)](library/codecs#codecs.IncrementalDecoder.getstate) + [(codecs.IncrementalEncoder method)](library/codecs#codecs.IncrementalEncoder.getstate) + [(in module random)](library/random#random.getstate) * [getstatus() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.getstatus) + [(urllib.response.addinfourl method)](library/urllib.request#urllib.response.addinfourl.getstatus) * [getstatusoutput() (in module subprocess)](library/subprocess#subprocess.getstatusoutput) * [getstr() (curses.window method)](library/curses#curses.window.getstr) * [GetString() (msilib.Record method)](library/msilib#msilib.Record.GetString) * [getSubject() (logging.handlers.SMTPHandler method)](library/logging.handlers#logging.handlers.SMTPHandler.getSubject) * [GetSummaryInformation() (msilib.Database method)](library/msilib#msilib.Database.GetSummaryInformation) * [getswitchinterval() (in module sys)](library/sys#sys.getswitchinterval) * [getSystemId() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.getSystemId) + [(xml.sax.xmlreader.Locator method)](library/xml.sax.reader#xml.sax.xmlreader.Locator.getSystemId) * [getsyx() (in module curses)](library/curses#curses.getsyx) * [gettarinfo() (tarfile.TarFile method)](library/tarfile#tarfile.TarFile.gettarinfo) * [gettempdir() (in module tempfile)](library/tempfile#tempfile.gettempdir) * [gettempdirb() (in module tempfile)](library/tempfile#tempfile.gettempdirb) * [gettempprefix() (in module tempfile)](library/tempfile#tempfile.gettempprefix) * [gettempprefixb() (in module tempfile)](library/tempfile#tempfile.gettempprefixb) * [getTestCaseNames() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.getTestCaseNames) * [gettext (module)](library/gettext#module-gettext) * [gettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.gettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.gettext) + [(in module gettext)](library/gettext#gettext.gettext) + [(in module locale)](library/locale#locale.gettext) * [gettimeout() (socket.socket method)](library/socket#socket.socket.gettimeout) * [gettrace() (in module sys)](library/sys#sys.gettrace) * [getturtle() (in module turtle)](library/turtle#turtle.getturtle) * [getType() (xml.sax.xmlreader.Attributes method)](library/xml.sax.reader#xml.sax.xmlreader.Attributes.getType) * [getuid() (in module os)](library/os#os.getuid) * [geturl() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.geturl) + [(urllib.parse.urllib.parse.SplitResult method)](library/urllib.parse#urllib.parse.urllib.parse.SplitResult.geturl) + [(urllib.response.addinfourl method)](library/urllib.request#urllib.response.addinfourl.geturl) * [getuser() (in module getpass)](library/getpass#getpass.getuser) * [getuserbase() (in module site)](library/site#site.getuserbase) * [getusersitepackages() (in module site)](library/site#site.getusersitepackages) * [getvalue() (io.BytesIO method)](library/io#io.BytesIO.getvalue) + [(io.StringIO method)](library/io#io.StringIO.getvalue) * [getValue() (xml.sax.xmlreader.Attributes method)](library/xml.sax.reader#xml.sax.xmlreader.Attributes.getValue) * [getValueByQName() (xml.sax.xmlreader.AttributesNS method)](library/xml.sax.reader#xml.sax.xmlreader.AttributesNS.getValueByQName) * [getwch() (in module msvcrt)](library/msvcrt#msvcrt.getwch) * [getwche() (in module msvcrt)](library/msvcrt#msvcrt.getwche) * [getweakrefcount() (in module weakref)](library/weakref#weakref.getweakrefcount) * [getweakrefs() (in module weakref)](library/weakref#weakref.getweakrefs) * [getwelcome() (ftplib.FTP method)](library/ftplib#ftplib.FTP.getwelcome) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.getwelcome) + [(poplib.POP3 method)](library/poplib#poplib.POP3.getwelcome) * [getwin() (in module curses)](library/curses#curses.getwin) * [getwindowsversion() (in module sys)](library/sys#sys.getwindowsversion) * [getwriter() (in module codecs)](library/codecs#codecs.getwriter) * [getxattr() (in module os)](library/os#os.getxattr) * [getyx() (curses.window method)](library/curses#curses.window.getyx) * [gid (tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.gid) * [**GIL**](glossary#term-gil) * glob + [module](library/fnmatch#index-3) * [glob (module)](library/glob#module-glob) * [glob() (in module glob)](library/glob#glob.glob) + [(msilib.Directory method)](library/msilib#msilib.Directory.glob) + [(pathlib.Path method)](library/pathlib#pathlib.Path.glob) * global + [name binding](reference/simple_stmts#index-43) + [namespace](reference/datamodel#index-34) + [statement](reference/simple_stmts#index-22), [**[1]**](reference/simple_stmts#index-43) * [Global (class in ast)](library/ast#ast.Global) * [global interpreter lock](c-api/init#index-33), [**[1]**](glossary#term-global-interpreter-lock) * [globals() (built-in function)](library/functions#globals) * [globs (doctest.DocTest attribute)](library/doctest#doctest.DocTest.globs) * [gmtime() (in module time)](library/time#time.gmtime) * [gname (tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.gname) * [GNOME](library/gettext#index-10) * [GNU\_FORMAT (in module tarfile)](library/tarfile#tarfile.GNU_FORMAT) * [gnu\_getopt() (in module getopt)](library/getopt#getopt.gnu_getopt) * [GNUTranslations (class in gettext)](library/gettext#gettext.GNUTranslations) * [go() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.go) * [got (doctest.DocTestFailure attribute)](library/doctest#doctest.DocTestFailure.got) * [goto() (in module turtle)](library/turtle#turtle.goto) * [grammar](reference/introduction#index-0) * [Graphical User Interface](library/tk#index-0) * [graphlib (module)](library/graphlib#module-graphlib) * [GREATER (in module token)](library/token#token.GREATER) * [GREATEREQUAL (in module token)](library/token#token.GREATEREQUAL) * [Greenwich Mean Time](library/time#index-4) * [GRND\_NONBLOCK (in module os)](library/os#os.GRND_NONBLOCK) * [GRND\_RANDOM (in module os)](library/os#os.GRND_RANDOM) * [Group (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.Group) * [group() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.group) + [(pathlib.Path method)](library/pathlib#pathlib.Path.group) + [(re.Match method)](library/re#re.Match.group) * [groupby() (in module itertools)](library/itertools#itertools.groupby) * [groupdict() (re.Match method)](library/re#re.Match.groupdict) * [groupindex (re.Pattern attribute)](library/re#re.Pattern.groupindex) * [grouping](reference/lexical_analysis#index-8) * [groups (email.headerregistry.AddressHeader attribute)](library/email.headerregistry#email.headerregistry.AddressHeader.groups) + [(re.Pattern attribute)](library/re#re.Pattern.groups) * [groups() (re.Match method)](library/re#re.Match.groups) * [grp (module)](library/grp#module-grp) * [Gt (class in ast)](library/ast#ast.Gt) * [gt() (in module operator)](library/operator#operator.gt) * [GtE (class in ast)](library/ast#ast.GtE) * [guess\_all\_extensions() (in module mimetypes)](library/mimetypes#mimetypes.guess_all_extensions) + [(mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.guess_all_extensions) * [guess\_extension() (in module mimetypes)](library/mimetypes#mimetypes.guess_extension) + [(mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.guess_extension) * [guess\_scheme() (in module wsgiref.util)](library/wsgiref#wsgiref.util.guess_scheme) * [guess\_type() (in module mimetypes)](library/mimetypes#mimetypes.guess_type) + [(mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.guess_type) * [GUI](library/tk#index-0) * [gzip (module)](library/gzip#module-gzip) * gzip command line option + [--best](library/gzip#cmdoption-gzip-best) + [--decompress](library/gzip#cmdoption-gzip-d) + [--fast](library/gzip#cmdoption-gzip-fast) + [--help](library/gzip#cmdoption-gzip-h) + [-d](library/gzip#cmdoption-gzip-d) + [-h](library/gzip#cmdoption-gzip-h) + [file](library/gzip#cmdoption-gzip-arg-file) * [GzipFile (class in gzip)](library/gzip#gzip.GzipFile) | H - | | | | --- | --- | | * [halfdelay() (in module curses)](library/curses#curses.halfdelay) * [Handle (class in asyncio)](library/asyncio-eventloop#asyncio.Handle) * [handle an exception](reference/executionmodel#index-13) * [handle() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.handle) + [(logging.Handler method)](library/logging#logging.Handler.handle) + [(logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.handle) + [(logging.Logger method)](library/logging#logging.Logger.handle) + [(logging.NullHandler method)](library/logging.handlers#logging.NullHandler.handle) + [(socketserver.BaseRequestHandler method)](library/socketserver#socketserver.BaseRequestHandler.handle) + [(wsgiref.simple\_server.WSGIRequestHandler method)](library/wsgiref#wsgiref.simple_server.WSGIRequestHandler.handle) * [handle\_accept() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_accept) * [handle\_accepted() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_accepted) * [handle\_charref() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_charref) * [handle\_close() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_close) * [handle\_comment() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_comment) * [handle\_connect() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_connect) * [handle\_data() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_data) * [handle\_decl() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_decl) * [handle\_defect() (email.policy.Policy method)](library/email.policy#email.policy.Policy.handle_defect) * [handle\_endtag() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_endtag) * [handle\_entityref() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_entityref) * [handle\_error() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_error) + [(socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.handle_error) * [handle\_expect\_100() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.handle_expect_100) * [handle\_expt() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_expt) * [handle\_one\_request() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.handle_one_request) * [handle\_pi() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_pi) * [handle\_read() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_read) * [handle\_request() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.handle_request) + [(xmlrpc.server.CGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.handle_request) * [handle\_startendtag() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_startendtag) * [handle\_starttag() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.handle_starttag) * [handle\_timeout() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.handle_timeout) * [handle\_write() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.handle_write) * [handleError() (logging.Handler method)](library/logging#logging.Handler.handleError) + [(logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.handleError) * handler + [exception](reference/datamodel#index-62) * [Handler (class in logging)](library/logging#logging.Handler) * [handler() (in module cgitb)](library/cgitb#cgitb.handler) * [harmonic\_mean() (in module statistics)](library/statistics#statistics.harmonic_mean) * [HAS\_ALPN (in module ssl)](library/ssl#ssl.HAS_ALPN) * [has\_children() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.has_children) * [has\_colors() (in module curses)](library/curses#curses.has_colors) * [has\_dualstack\_ipv6() (in module socket)](library/socket#socket.has_dualstack_ipv6) * [HAS\_ECDH (in module ssl)](library/ssl#ssl.HAS_ECDH) * [has\_extn() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.has_extn) * [has\_function() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.has_function) * [has\_header() (csv.Sniffer method)](library/csv#csv.Sniffer.has_header) + [(urllib.request.Request method)](library/urllib.request#urllib.request.Request.has_header) * [has\_ic() (in module curses)](library/curses#curses.has_ic) * [has\_il() (in module curses)](library/curses#curses.has_il) * [has\_ipv6 (in module socket)](library/socket#socket.has_ipv6) * [has\_key (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-has_key) * [has\_key() (in module curses)](library/curses#curses.has_key) * [has\_location (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.has_location) * [HAS\_NEVER\_CHECK\_COMMON\_NAME (in module ssl)](library/ssl#ssl.HAS_NEVER_CHECK_COMMON_NAME) * [has\_nonstandard\_attr() (http.cookiejar.Cookie method)](library/http.cookiejar#http.cookiejar.Cookie.has_nonstandard_attr) * [HAS\_NPN (in module ssl)](library/ssl#ssl.HAS_NPN) * [has\_option() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.has_option) + [(optparse.OptionParser method)](library/optparse#optparse.OptionParser.has_option) * [has\_section() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.has_section) * [HAS\_SNI (in module ssl)](library/ssl#ssl.HAS_SNI) * [HAS\_SSLv2 (in module ssl)](library/ssl#ssl.HAS_SSLv2) * [HAS\_SSLv3 (in module ssl)](library/ssl#ssl.HAS_SSLv3) * [has\_ticket (ssl.SSLSession attribute)](library/ssl#ssl.SSLSession.has_ticket) * [HAS\_TLSv1 (in module ssl)](library/ssl#ssl.HAS_TLSv1) * [HAS\_TLSv1\_1 (in module ssl)](library/ssl#ssl.HAS_TLSv1_1) * [HAS\_TLSv1\_2 (in module ssl)](library/ssl#ssl.HAS_TLSv1_2) * [HAS\_TLSv1\_3 (in module ssl)](library/ssl#ssl.HAS_TLSv1_3) * [hasattr() (built-in function)](library/functions#hasattr) * [hasAttribute() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.hasAttribute) * [hasAttributeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.hasAttributeNS) * [hasAttributes() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.hasAttributes) * [hasChildNodes() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.hasChildNodes) * [hascompare (in module dis)](library/dis#dis.hascompare) * [hasconst (in module dis)](library/dis#dis.hasconst) * [hasFeature() (xml.dom.DOMImplementation method)](library/xml.dom#xml.dom.DOMImplementation.hasFeature) * [hasfree (in module dis)](library/dis#dis.hasfree) * hash + [built-in function](c-api/object#index-6), [[1]](c-api/typeobj#index-2), [[2]](library/stdtypes#index-20), [[3]](reference/datamodel#index-76) * [hash character](reference/lexical_analysis#index-4) * [hash() (built-in function)](library/functions#hash) * [**hash-based pyc**](glossary#term-hash-based-pyc) * [hash.block\_size (in module hashlib)](library/hashlib#hashlib.hash.block_size) * [hash.digest\_size (in module hashlib)](library/hashlib#hashlib.hash.digest_size) * [hash\_info (in module sys)](library/sys#sys.hash_info) * [hashable](reference/expressions#index-20), [**[1]**](glossary#term-hashable) * [Hashable (class in collections.abc)](library/collections.abc#collections.abc.Hashable) + [(class in typing)](library/typing#typing.Hashable) * [hasHandlers() (logging.Logger method)](library/logging#logging.Logger.hasHandlers) * [hashfunc (C type)](c-api/typeobj#c.hashfunc) * [hashlib (module)](library/hashlib#module-hashlib) * [hasjabs (in module dis)](library/dis#dis.hasjabs) * [hasjrel (in module dis)](library/dis#dis.hasjrel) * [haslocal (in module dis)](library/dis#dis.haslocal) * [hasname (in module dis)](library/dis#dis.hasname) * [HAVE\_ARGUMENT (opcode)](library/dis#opcode-HAVE_ARGUMENT) * [HAVE\_CONTEXTVAR (in module decimal)](library/decimal#decimal.HAVE_CONTEXTVAR) * [HAVE\_DOCSTRINGS (in module test.support)](library/test#test.support.HAVE_DOCSTRINGS) * [HAVE\_THREADS (in module decimal)](library/decimal#decimal.HAVE_THREADS) * [HCI\_DATA\_DIR (in module socket)](library/socket#socket.HCI_DATA_DIR) * [HCI\_FILTER (in module socket)](library/socket#socket.HCI_FILTER) * [HCI\_TIME\_STAMP (in module socket)](library/socket#socket.HCI_TIME_STAMP) * [head() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.head) * [Header (class in email.header)](library/email.header#email.header.Header) * [header\_encode() (email.charset.Charset method)](library/email.charset#email.charset.Charset.header_encode) * [header\_encode\_lines() (email.charset.Charset method)](library/email.charset#email.charset.Charset.header_encode_lines) * [header\_encoding (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.header_encoding) * [header\_factory (email.policy.EmailPolicy attribute)](library/email.policy#email.policy.EmailPolicy.header_factory) * [header\_fetch\_parse() (email.policy.Compat32 method)](library/email.policy#email.policy.Compat32.header_fetch_parse) + [(email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.header_fetch_parse) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.header_fetch_parse) * [header\_items() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.header_items) * [header\_max\_count() (email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.header_max_count) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.header_max_count) * [header\_offset (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.header_offset) * [header\_source\_parse() (email.policy.Compat32 method)](library/email.policy#email.policy.Compat32.header_source_parse) + [(email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.header_source_parse) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.header_source_parse) * [header\_store\_parse() (email.policy.Compat32 method)](library/email.policy#email.policy.Compat32.header_store_parse) + [(email.policy.EmailPolicy method)](library/email.policy#email.policy.EmailPolicy.header_store_parse) + [(email.policy.Policy method)](library/email.policy#email.policy.Policy.header_store_parse) * [HeaderError](library/tarfile#tarfile.HeaderError) * [HeaderParseError](library/email.errors#email.errors.HeaderParseError) * [HeaderParser (class in email.parser)](library/email.parser#email.parser.HeaderParser) * [HeaderRegistry (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.HeaderRegistry) * headers + [MIME](library/cgi#index-0), [[1]](library/mimetypes#index-1) * [Headers (class in wsgiref.headers)](library/wsgiref#wsgiref.headers.Headers) * [headers (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.headers) + [(http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.headers) + [(urllib.error.HTTPError attribute)](library/urllib.error#urllib.error.HTTPError.headers) + [(urllib.response.addinfourl attribute)](library/urllib.request#urllib.response.addinfourl.headers) + [(xmlrpc.client.ProtocolError attribute)](library/xmlrpc.client#xmlrpc.client.ProtocolError.headers) * [heading() (in module turtle)](library/turtle#turtle.heading) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.heading) * [heapify() (in module heapq)](library/heapq#heapq.heapify) * [heapmin() (in module msvcrt)](library/msvcrt#msvcrt.heapmin) | * [heappop() (in module heapq)](library/heapq#heapq.heappop) * [heappush() (in module heapq)](library/heapq#heapq.heappush) * [heappushpop() (in module heapq)](library/heapq#heapq.heappushpop) * [heapq (module)](library/heapq#module-heapq) * [heapreplace() (in module heapq)](library/heapq#heapq.heapreplace) * [helo() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.helo) * help + [built-in function](tutorial/stdlib#index-0) + [online](library/pydoc#index-0) * [help (optparse.Option attribute)](library/optparse#optparse.Option.help) + [(pdb command)](library/pdb#pdbcommand-help) * [help() (built-in function)](library/functions#help) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.help) * [herror](library/socket#socket.herror) * [hex (uuid.UUID attribute)](library/uuid#uuid.UUID.hex) * [hex() (built-in function)](library/functions#hex) + [(bytearray method)](library/stdtypes#bytearray.hex) + [(bytes method)](library/stdtypes#bytes.hex) + [(float method)](library/stdtypes#float.hex) + [(memoryview method)](library/stdtypes#memoryview.hex) * hexadecimal + [literals](library/stdtypes#index-12) * [hexadecimal literal](reference/lexical_analysis#index-26) * [hexbin() (in module binhex)](library/binhex#binhex.hexbin) * [hexdigest() (hashlib.hash method)](library/hashlib#hashlib.hash.hexdigest) + [(hashlib.shake method)](library/hashlib#hashlib.shake.hexdigest) + [(hmac.HMAC method)](library/hmac#hmac.HMAC.hexdigest) * [hexdigits (in module string)](library/string#string.hexdigits) * [hexlify() (in module binascii)](library/binascii#binascii.hexlify) * [hexversion (in module sys)](library/sys#sys.hexversion) * [hidden() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.hidden) * [hide() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.hide) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.hide) * [hide\_cookie2 (http.cookiejar.CookiePolicy attribute)](library/http.cookiejar#http.cookiejar.CookiePolicy.hide_cookie2) * [hideturtle() (in module turtle)](library/turtle#turtle.hideturtle) * hierarchy + [type](reference/datamodel#index-4) * [HierarchyRequestErr](library/xml.dom#xml.dom.HierarchyRequestErr) * [HIGH\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.HIGH_PRIORITY_CLASS) * [HIGHEST\_PROTOCOL (in module pickle)](library/pickle#pickle.HIGHEST_PROTOCOL) * [HKEY\_CLASSES\_ROOT (in module winreg)](library/winreg#winreg.HKEY_CLASSES_ROOT) * [HKEY\_CURRENT\_CONFIG (in module winreg)](library/winreg#winreg.HKEY_CURRENT_CONFIG) * [HKEY\_CURRENT\_USER (in module winreg)](library/winreg#winreg.HKEY_CURRENT_USER) * [HKEY\_DYN\_DATA (in module winreg)](library/winreg#winreg.HKEY_DYN_DATA) * [HKEY\_LOCAL\_MACHINE (in module winreg)](library/winreg#winreg.HKEY_LOCAL_MACHINE) * [HKEY\_PERFORMANCE\_DATA (in module winreg)](library/winreg#winreg.HKEY_PERFORMANCE_DATA) * [HKEY\_USERS (in module winreg)](library/winreg#winreg.HKEY_USERS) * [hline() (curses.window method)](library/curses#curses.window.hline) * [HList (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.HList) * [hls\_to\_rgb() (in module colorsys)](library/colorsys#colorsys.hls_to_rgb) * [hmac (module)](library/hmac#module-hmac) * [HOME](distutils/apiref#index-1), [[1]](install/index#index-4), [[2]](install/index#index-5), [[3]](library/os.path#index-3), [[4]](library/os.path#index-7), [[5]](library/tkinter#index-1), [[6]](https://docs.python.org/3.9/whatsnew/3.8.html#index-14), [[7]](https://docs.python.org/3.9/whatsnew/3.8.html#index-21), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-54), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-55) * [home() (in module turtle)](library/turtle#turtle.home) + [(pathlib.Path class method)](library/pathlib#pathlib.Path.home) * [HOMEDRIVE](install/index#index-7), [[1]](library/os.path#index-6) * [HOMEPATH](install/index#index-8), [[1]](library/os.path#index-5) * [hook\_compressed() (in module fileinput)](library/fileinput#fileinput.hook_compressed) * [hook\_encoded() (in module fileinput)](library/fileinput#fileinput.hook_encoded) * hooks + [import](reference/import#index-9) + [meta](reference/import#index-9) + [path](reference/import#index-9) * [host (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.host) * [hostmask (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.hostmask) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.hostmask) * [hostname\_checks\_common\_name (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.hostname_checks_common_name) * [hosts (netrc.netrc attribute)](library/netrc#netrc.netrc.hosts) * [hosts() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.hosts) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.hosts) * [hour (datetime.datetime attribute)](library/datetime#datetime.datetime.hour) + [(datetime.time attribute)](library/datetime#datetime.time.hour) * [HRESULT (class in ctypes)](library/ctypes#ctypes.HRESULT) * [hStdError (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.hStdError) * [hStdInput (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.hStdInput) * [hStdOutput (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.hStdOutput) * [hsv\_to\_rgb() (in module colorsys)](library/colorsys#colorsys.hsv_to_rgb) * [ht() (in module turtle)](library/turtle#turtle.ht) * [HTML](library/html.parser#index-0), [[1]](library/urllib.request#index-12) * [html (module)](library/html#module-html) * [html() (in module cgitb)](library/cgitb#cgitb.html) * [html.entities (module)](library/html.entities#module-html.entities) * [html.parser (module)](library/html.parser#module-html.parser) * [html5 (in module html.entities)](library/html.entities#html.entities.html5) * [HTMLCalendar (class in calendar)](library/calendar#calendar.HTMLCalendar) * [HtmlDiff (class in difflib)](library/difflib#difflib.HtmlDiff) * [HTMLParser (class in html.parser)](library/html.parser#html.parser.HTMLParser) * [htonl() (in module socket)](library/socket#socket.htonl) * [htons() (in module socket)](library/socket#socket.htons) * HTTP + [http (standard module)](library/http#index-0) + [http.client (standard module)](library/http.client#index-0) + [protocol](library/cgi#index-0), [[1]](library/http.client#index-0), [[2]](library/http#index-0), [[3]](library/http.server#index-0), [[4]](library/urllib.request#index-11), [[5]](library/urllib.request#index-12) * [HTTP (in module email.policy)](library/email.policy#email.policy.HTTP) * [http (module)](library/http#module-http) * [http.client (module)](library/http.client#module-http.client) * [http.cookiejar (module)](library/http.cookiejar#module-http.cookiejar) * [http.cookies (module)](library/http.cookies#module-http.cookies) * http.server + [security](library/http.server#index-3) * [http.server (module)](library/http.server#module-http.server) * [http\_error\_301() (urllib.request.HTTPRedirectHandler method)](library/urllib.request#urllib.request.HTTPRedirectHandler.http_error_301) * [http\_error\_302() (urllib.request.HTTPRedirectHandler method)](library/urllib.request#urllib.request.HTTPRedirectHandler.http_error_302) * [http\_error\_303() (urllib.request.HTTPRedirectHandler method)](library/urllib.request#urllib.request.HTTPRedirectHandler.http_error_303) * [http\_error\_307() (urllib.request.HTTPRedirectHandler method)](library/urllib.request#urllib.request.HTTPRedirectHandler.http_error_307) * [http\_error\_401() (urllib.request.HTTPBasicAuthHandler method)](library/urllib.request#urllib.request.HTTPBasicAuthHandler.http_error_401) + [(urllib.request.HTTPDigestAuthHandler method)](library/urllib.request#urllib.request.HTTPDigestAuthHandler.http_error_401) * [http\_error\_407() (urllib.request.ProxyBasicAuthHandler method)](library/urllib.request#urllib.request.ProxyBasicAuthHandler.http_error_407) + [(urllib.request.ProxyDigestAuthHandler method)](library/urllib.request#urllib.request.ProxyDigestAuthHandler.http_error_407) * [http\_error\_auth\_reqed() (urllib.request.AbstractBasicAuthHandler method)](library/urllib.request#urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed) + [(urllib.request.AbstractDigestAuthHandler method)](library/urllib.request#urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed) * [http\_error\_default() (urllib.request.BaseHandler method)](library/urllib.request#urllib.request.BaseHandler.http_error_default) * [http\_open() (urllib.request.HTTPHandler method)](library/urllib.request#urllib.request.HTTPHandler.http_open) * [HTTP\_PORT (in module http.client)](library/http.client#http.client.HTTP_PORT) * [http\_proxy](howto/urllib2#index-3), [[1]](library/urllib.request#index-0), [[2]](library/urllib.request#index-9) * [http\_response() (urllib.request.HTTPErrorProcessor method)](library/urllib.request#urllib.request.HTTPErrorProcessor.http_response) * [http\_version (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.http_version) * [HTTPBasicAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.HTTPBasicAuthHandler) * [HTTPConnection (class in http.client)](library/http.client#http.client.HTTPConnection) * [HTTPCookieProcessor (class in urllib.request)](library/urllib.request#urllib.request.HTTPCookieProcessor) * [httpd](library/http.server#index-0) * [HTTPDefaultErrorHandler (class in urllib.request)](library/urllib.request#urllib.request.HTTPDefaultErrorHandler) * [HTTPDigestAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.HTTPDigestAuthHandler) * [HTTPError](library/urllib.error#urllib.error.HTTPError) * [HTTPErrorProcessor (class in urllib.request)](library/urllib.request#urllib.request.HTTPErrorProcessor) * [HTTPException](library/http.client#http.client.HTTPException) * [HTTPHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.HTTPHandler) + [(class in urllib.request)](library/urllib.request#urllib.request.HTTPHandler) * [HTTPPasswordMgr (class in urllib.request)](library/urllib.request#urllib.request.HTTPPasswordMgr) * [HTTPPasswordMgrWithDefaultRealm (class in urllib.request)](library/urllib.request#urllib.request.HTTPPasswordMgrWithDefaultRealm) * [HTTPPasswordMgrWithPriorAuth (class in urllib.request)](library/urllib.request#urllib.request.HTTPPasswordMgrWithPriorAuth) * [HTTPRedirectHandler (class in urllib.request)](library/urllib.request#urllib.request.HTTPRedirectHandler) * [HTTPResponse (class in http.client)](library/http.client#http.client.HTTPResponse) * [https\_open() (urllib.request.HTTPSHandler method)](library/urllib.request#urllib.request.HTTPSHandler.https_open) * [HTTPS\_PORT (in module http.client)](library/http.client#http.client.HTTPS_PORT) * [https\_response() (urllib.request.HTTPErrorProcessor method)](library/urllib.request#urllib.request.HTTPErrorProcessor.https_response) * [HTTPSConnection (class in http.client)](library/http.client#http.client.HTTPSConnection) * [HTTPServer (class in http.server)](library/http.server#http.server.HTTPServer) * [HTTPSHandler (class in urllib.request)](library/urllib.request#urllib.request.HTTPSHandler) * [HTTPStatus (class in http)](library/http#http.HTTPStatus) * [hypot() (in module math)](library/math#math.hypot) | I - | | | | --- | --- | | * [I (in module re)](library/re#re.I) * I/O control + [buffering](library/functions#index-7), [[1]](library/socket#index-6) + [POSIX](library/termios#index-0) + [tty](library/termios#index-0) + [UNIX](library/fcntl#index-0) * [iadd() (in module operator)](library/operator#operator.iadd) * [iand() (in module operator)](library/operator#operator.iand) * [iconcat() (in module operator)](library/operator#operator.iconcat) * id + [built-in function](reference/datamodel#index-1) * [id (ssl.SSLSession attribute)](library/ssl#ssl.SSLSession.id) * [id() (built-in function)](library/functions#id) + [(unittest.TestCase method)](library/unittest#unittest.TestCase.id) * [idcok() (curses.window method)](library/curses#curses.window.idcok) * [ident (select.kevent attribute)](library/select#select.kevent.ident) + [(threading.Thread attribute)](library/threading#threading.Thread.ident) * [identchars (cmd.Cmd attribute)](library/cmd#cmd.Cmd.identchars) * [identifier](reference/expressions#index-3), [[1]](reference/lexical_analysis#index-10) * [identify() (tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.identify) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.identify) + [(tkinter.ttk.Widget method)](library/tkinter.ttk#tkinter.ttk.Widget.identify) * [identify\_column() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.identify_column) * [identify\_element() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.identify_element) * [identify\_region() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.identify_region) * [identify\_row() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.identify_row) * identity + [test](reference/expressions#index-81) * [identity of an object](reference/datamodel#index-1) * [idioms (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-idioms) * [IDLE](library/idle#index-0), [**[1]**](glossary#term-idle) * [IDLE\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.IDLE_PRIORITY_CLASS) * [IDLESTARTUP](library/idle#index-5), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-108), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-78), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-83) * [idlok() (curses.window method)](library/curses#curses.window.idlok) * if + [conditional expression](reference/expressions#index-87) + [in comprehensions](reference/expressions#index-12) + [statement](library/stdtypes#index-1), [**[1]**](reference/compound_stmts#index-3) * [If (class in ast)](library/ast#ast.If) * [if\_indextoname() (in module socket)](library/socket#socket.if_indextoname) * [if\_nameindex() (in module socket)](library/socket#socket.if_nameindex) * [if\_nametoindex() (in module socket)](library/socket#socket.if_nametoindex) * [IfExp (class in ast)](library/ast#ast.IfExp) * [ifloordiv() (in module operator)](library/operator#operator.ifloordiv) * [iglob() (in module glob)](library/glob#glob.iglob) * [ignorableWhitespace() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.ignorableWhitespace) * ignore + [error handler's name](library/codecs#index-1) * [ignore (pdb command)](library/pdb#pdbcommand-ignore) * [ignore\_errors() (in module codecs)](library/codecs#codecs.ignore_errors) * [IGNORE\_EXCEPTION\_DETAIL (in module doctest)](library/doctest#doctest.IGNORE_EXCEPTION_DETAIL) * [ignore\_patterns() (in module shutil)](library/shutil#shutil.ignore_patterns) * [IGNORECASE (in module re)](library/re#re.IGNORECASE) * [ihave() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.ihave) * [IISCGIHandler (class in wsgiref.handlers)](library/wsgiref#wsgiref.handlers.IISCGIHandler) * [ilshift() (in module operator)](library/operator#operator.ilshift) * [imag (numbers.Complex attribute)](library/numbers#numbers.Complex.imag) * [imaginary literal](reference/lexical_analysis#index-26) * [imap() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.imap) * IMAP4 + [protocol](library/imaplib#index-0) * [IMAP4 (class in imaplib)](library/imaplib#imaplib.IMAP4) * [IMAP4.abort](library/imaplib#imaplib.IMAP4.abort) * [IMAP4.error](library/imaplib#imaplib.IMAP4.error) * [IMAP4.readonly](library/imaplib#imaplib.IMAP4.readonly) * IMAP4\_SSL + [protocol](library/imaplib#index-0) * [IMAP4\_SSL (class in imaplib)](library/imaplib#imaplib.IMAP4_SSL) * IMAP4\_stream + [protocol](library/imaplib#index-0) * [IMAP4\_stream (class in imaplib)](library/imaplib#imaplib.IMAP4_stream) * [imap\_unordered() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.imap_unordered) * [imaplib (module)](library/imaplib#module-imaplib) * [imatmul() (in module operator)](library/operator#operator.imatmul) * [imghdr (module)](library/imghdr#module-imghdr) * [immedok() (curses.window method)](library/curses#curses.window.immedok) * [**immutable**](glossary#term-immutable) + [data type](reference/expressions#index-7) + [object](reference/datamodel#index-17), [[1]](reference/expressions#index-20), [[2]](reference/expressions#index-7) + [sequence types](library/stdtypes#index-20) * [immutable object](reference/datamodel#index-1) * immutable sequence + [object](reference/datamodel#index-17) * immutable types + [subclassing](reference/datamodel#index-68) * [imod() (in module operator)](library/operator#operator.imod) * imp + [module](library/functions#index-12) * [imp (module)](library/imp#module-imp) * [ImpImporter (class in pkgutil)](library/pkgutil#pkgutil.ImpImporter) * [impl\_detail() (in module test.support)](library/test#test.support.impl_detail) * [implementation (in module sys)](library/sys#sys.implementation) * [ImpLoader (class in pkgutil)](library/pkgutil#pkgutil.ImpLoader) * import + [hooks](reference/import#index-9) + [statement](library/functions#index-12), [[1]](library/imp#index-0), [[2]](library/site#index-2), [[3]](reference/datamodel#index-42), [**[4]**](reference/simple_stmts#index-34) * [import (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-import) * [Import (class in ast)](library/ast#ast.Import) * [import hooks](reference/import#index-9) * [import machinery](reference/import#index-0) * [**import path**](glossary#term-import-path) * [import\_fresh\_module() (in module test.support)](library/test#test.support.import_fresh_module) * [IMPORT\_FROM (opcode)](library/dis#opcode-IMPORT_FROM) * [import\_module() (in module importlib)](library/importlib#importlib.import_module) + [(in module test.support)](library/test#test.support.import_module) * [IMPORT\_NAME (opcode)](library/dis#opcode-IMPORT_NAME) * [IMPORT\_STAR (opcode)](library/dis#opcode-IMPORT_STAR) * [**importer**](glossary#term-importer) * [ImportError](library/exceptions#ImportError) + [exception](reference/simple_stmts#index-34) * [ImportFrom (class in ast)](library/ast#ast.ImportFrom) * [**importing**](glossary#term-importing) * [importlib (module)](library/importlib#module-importlib) * [importlib.abc (module)](library/importlib#module-importlib.abc) * [importlib.machinery (module)](library/importlib#module-importlib.machinery) * [importlib.metadata (module)](library/importlib.metadata#module-importlib.metadata) * [importlib.resources (module)](library/importlib#module-importlib.resources) * [importlib.util (module)](library/importlib#module-importlib.util) * [imports (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-imports) * [imports2 (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-imports2) * [ImportWarning](library/exceptions#ImportWarning) * [ImproperConnectionState](library/http.client#http.client.ImproperConnectionState) * [imul() (in module operator)](library/operator#operator.imul) * in + [keyword](reference/compound_stmts#index-6) + [operator](library/stdtypes#index-10), [[1]](library/stdtypes#index-19), [[2]](reference/expressions#index-80) * [In (class in ast)](library/ast#ast.In) * [in\_dll() (ctypes.\_CData method)](library/ctypes#ctypes._CData.in_dll) * [in\_table\_a1() (in module stringprep)](library/stringprep#stringprep.in_table_a1) * [in\_table\_b1() (in module stringprep)](library/stringprep#stringprep.in_table_b1) * [in\_table\_c11() (in module stringprep)](library/stringprep#stringprep.in_table_c11) * [in\_table\_c11\_c12() (in module stringprep)](library/stringprep#stringprep.in_table_c11_c12) * [in\_table\_c12() (in module stringprep)](library/stringprep#stringprep.in_table_c12) * [in\_table\_c21() (in module stringprep)](library/stringprep#stringprep.in_table_c21) * [in\_table\_c21\_c22() (in module stringprep)](library/stringprep#stringprep.in_table_c21_c22) * [in\_table\_c22() (in module stringprep)](library/stringprep#stringprep.in_table_c22) * [in\_table\_c3() (in module stringprep)](library/stringprep#stringprep.in_table_c3) * [in\_table\_c4() (in module stringprep)](library/stringprep#stringprep.in_table_c4) * [in\_table\_c5() (in module stringprep)](library/stringprep#stringprep.in_table_c5) * [in\_table\_c6() (in module stringprep)](library/stringprep#stringprep.in_table_c6) * [in\_table\_c7() (in module stringprep)](library/stringprep#stringprep.in_table_c7) * [in\_table\_c8() (in module stringprep)](library/stringprep#stringprep.in_table_c8) * [in\_table\_c9() (in module stringprep)](library/stringprep#stringprep.in_table_c9) * [in\_table\_d1() (in module stringprep)](library/stringprep#stringprep.in_table_d1) * [in\_table\_d2() (in module stringprep)](library/stringprep#stringprep.in_table_d2) * [in\_transaction (sqlite3.Connection attribute)](library/sqlite3#sqlite3.Connection.in_transaction) * [inch() (curses.window method)](library/curses#curses.window.inch) * inclusive + [or](reference/expressions#index-76) * [inclusive (tracemalloc.DomainFilter attribute)](library/tracemalloc#tracemalloc.DomainFilter.inclusive) + [(tracemalloc.Filter attribute)](library/tracemalloc#tracemalloc.Filter.inclusive) * [Incomplete](library/binascii#binascii.Incomplete) * [IncompleteRead](library/http.client#http.client.IncompleteRead) * [IncompleteReadError](library/asyncio-exceptions#asyncio.IncompleteReadError) * [incr\_item()](c-api/intro#index-20), [[1]](c-api/intro#index-21) * [increment\_lineno() (in module ast)](library/ast#ast.increment_lineno) * [IncrementalDecoder (class in codecs)](library/codecs#codecs.IncrementalDecoder) * [incrementaldecoder (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.incrementaldecoder) * [IncrementalEncoder (class in codecs)](library/codecs#codecs.IncrementalEncoder) * [incrementalencoder (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.incrementalencoder) * [IncrementalNewlineDecoder (class in io)](library/io#io.IncrementalNewlineDecoder) * [IncrementalParser (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.IncrementalParser) * [indent (doctest.Example attribute)](library/doctest#doctest.Example.indent) * [INDENT (in module token)](library/token#token.INDENT) * [INDENT token](reference/lexical_analysis#index-9) * [indent() (in module textwrap)](library/textwrap#textwrap.indent) + [(in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.indent) * [indentation](reference/lexical_analysis#index-8) * [IndentationError](library/exceptions#IndentationError) * [index operation](reference/datamodel#index-15) * [index() (array.array method)](library/array#array.array.index) + [(bytearray method)](library/stdtypes#bytearray.index) + [(bytes method)](library/stdtypes#bytes.index) + [(collections.deque method)](library/collections#collections.deque.index) + [(in module operator)](library/operator#operator.index) + [(multiprocessing.shared\_memory.ShareableList method)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.ShareableList.index) + [(sequence method)](library/stdtypes#index-19) + [(str method)](library/stdtypes#str.index) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.index) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.index) * [IndexError](library/exceptions#IndexError) * [indexOf() (in module operator)](library/operator#operator.indexOf) * [IndexSizeErr](library/xml.dom#xml.dom.IndexSizeErr) * [indices() (slice method)](reference/datamodel#slice.indices) * [inet\_aton() (in module socket)](library/socket#socket.inet_aton) * [inet\_ntoa() (in module socket)](library/socket#socket.inet_ntoa) * [inet\_ntop() (in module socket)](library/socket#socket.inet_ntop) * [inet\_pton() (in module socket)](library/socket#socket.inet_pton) * [Inexact (class in decimal)](library/decimal#decimal.Inexact) * [inf (in module cmath)](library/cmath#cmath.inf) + [(in module math)](library/math#math.inf) * infile + [json.tool command line option](library/json#cmdoption-json-tool-arg-infile) * [infile (shlex.shlex attribute)](library/shlex#shlex.shlex.infile) * [Infinity](library/functions#index-2) * [infj (in module cmath)](library/cmath#cmath.infj) * [info() (dis.Bytecode method)](library/dis#dis.Bytecode.info) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.info) + [(http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.info) + [(in module logging)](library/logging#logging.info) + [(logging.Logger method)](library/logging#logging.Logger.info) + [(urllib.response.addinfourl method)](library/urllib.request#urllib.response.addinfourl.info) * [infolist() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.infolist) * [inheritance](reference/compound_stmts#index-31) * [ini file](library/configparser#index-0) * [init() (in module mimetypes)](library/mimetypes#mimetypes.init) * [init\_color() (in module curses)](library/curses#curses.init_color) * [init\_database() (in module msilib)](library/msilib#msilib.init_database) * [init\_pair() (in module curses)](library/curses#curses.init_pair) * [inited (in module mimetypes)](library/mimetypes#mimetypes.inited) * [initgroups() (in module os)](library/os#os.initgroups) * [initial\_indent (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.initial_indent) * [initialize\_options() (distutils.cmd.Command method)](distutils/apiref#distutils.cmd.Command.initialize_options) * [initproc (C type)](c-api/typeobj#c.initproc) * [initscr() (in module curses)](library/curses#curses.initscr) * [inode() (os.DirEntry method)](library/os#os.DirEntry.inode) * [INPLACE\_ADD (opcode)](library/dis#opcode-INPLACE_ADD) * [INPLACE\_AND (opcode)](library/dis#opcode-INPLACE_AND) * [INPLACE\_FLOOR\_DIVIDE (opcode)](library/dis#opcode-INPLACE_FLOOR_DIVIDE) * [INPLACE\_LSHIFT (opcode)](library/dis#opcode-INPLACE_LSHIFT) * [INPLACE\_MATRIX\_MULTIPLY (opcode)](library/dis#opcode-INPLACE_MATRIX_MULTIPLY) * [INPLACE\_MODULO (opcode)](library/dis#opcode-INPLACE_MODULO) * [INPLACE\_MULTIPLY (opcode)](library/dis#opcode-INPLACE_MULTIPLY) * [INPLACE\_OR (opcode)](library/dis#opcode-INPLACE_OR) * [INPLACE\_POWER (opcode)](library/dis#opcode-INPLACE_POWER) * [INPLACE\_RSHIFT (opcode)](library/dis#opcode-INPLACE_RSHIFT) * [INPLACE\_SUBTRACT (opcode)](library/dis#opcode-INPLACE_SUBTRACT) * [INPLACE\_TRUE\_DIVIDE (opcode)](library/dis#opcode-INPLACE_TRUE_DIVIDE) * [INPLACE\_XOR (opcode)](library/dis#opcode-INPLACE_XOR) * [input](reference/toplevel_components#index-5) + [(2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-input) * [input() (built-in function)](library/functions#input) + [(in module fileinput)](library/fileinput#fileinput.input) * [input\_charset (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.input_charset) * [input\_codec (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.input_codec) * [InputOnly (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.InputOnly) * [InputSource (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.InputSource) * [inquiry (C type)](c-api/gcsupport#c.inquiry) * [insch() (curses.window method)](library/curses#curses.window.insch) * [insdelln() (curses.window method)](library/curses#curses.window.insdelln) * [insert() (array.array method)](library/array#array.array.insert) + [(collections.deque method)](library/collections#collections.deque.insert) + [(sequence method)](library/stdtypes#index-22) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.insert) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.insert) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.insert) * [insert\_text() (in module readline)](library/readline#readline.insert_text) * [insertBefore() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.insertBefore) * [insertln() (curses.window method)](library/curses#curses.window.insertln) * [insnstr() (curses.window method)](library/curses#curses.window.insnstr) * [insort() (in module bisect)](library/bisect#bisect.insort) * [insort\_left() (in module bisect)](library/bisect#bisect.insort_left) * [insort\_right() (in module bisect)](library/bisect#bisect.insort_right) * [inspect (module)](library/inspect#module-inspect) * inspect command line option + [--details](library/inspect#cmdoption-inspect-details) * [InspectLoader (class in importlib.abc)](library/importlib#importlib.abc.InspectLoader) * [insstr() (curses.window method)](library/curses#curses.window.insstr) * [install() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.install) + [(in module gettext)](library/gettext#gettext.install) * [install\_opener() (in module urllib.request)](library/urllib.request#urllib.request.install_opener) * [install\_scripts() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.install_scripts) * [installHandler() (in module unittest)](library/unittest#unittest.installHandler) * instance + [call](reference/datamodel#index-93), [[1]](reference/expressions#index-56) + [class](reference/datamodel#index-49) + [object](reference/datamodel#index-45), [[1]](reference/datamodel#index-49), [[2]](reference/expressions#index-55) * instancemethod + [object](c-api/method#index-0) * [instate() (tkinter.ttk.Widget method)](library/tkinter.ttk#tkinter.ttk.Widget.instate) * [instr() (curses.window method)](library/curses#curses.window.instr) * [instream (shlex.shlex attribute)](library/shlex#shlex.shlex.instream) * [Instruction (class in dis)](library/dis#dis.Instruction) * [Instruction.arg (in module dis)](library/dis#dis.Instruction.arg) * [Instruction.argrepr (in module dis)](library/dis#dis.Instruction.argrepr) * [Instruction.argval (in module dis)](library/dis#dis.Instruction.argval) * [Instruction.is\_jump\_target (in module dis)](library/dis#dis.Instruction.is_jump_target) * [Instruction.offset (in module dis)](library/dis#dis.Instruction.offset) * [Instruction.opcode (in module dis)](library/dis#dis.Instruction.opcode) * [Instruction.opname (in module dis)](library/dis#dis.Instruction.opname) * [Instruction.starts\_line (in module dis)](library/dis#dis.Instruction.starts_line) * int + [built-in function](c-api/number#index-4), [[1]](library/stdtypes#index-13), [[2]](reference/datamodel#index-100) * [int (built-in class)](library/functions#int) + [(uuid.UUID attribute)](library/uuid#uuid.UUID.int) * [Int2AP() (in module imaplib)](library/imaplib#imaplib.Int2AP) * [int\_info (in module sys)](library/sys#sys.int_info) * [integer](reference/datamodel#index-19) + [literals](library/stdtypes#index-12) + [object](c-api/long#index-0), [[1]](library/stdtypes#index-11), [[2]](reference/datamodel#index-10) + [representation](reference/datamodel#index-12) + [types, operations on](library/stdtypes#index-16) * [integer literal](reference/lexical_analysis#index-26) * [Integral (class in numbers)](library/numbers#numbers.Integral) * [Integrated Development Environment](library/idle#index-0) * [IntegrityError](library/sqlite3#sqlite3.IntegrityError) * [Intel/DVI ADPCM](library/audioop#index-1) * [IntEnum (class in enum)](library/enum#enum.IntEnum) * [interact (pdb command)](library/pdb#pdbcommand-interact) * [interact() (code.InteractiveConsole method)](library/code#code.InteractiveConsole.interact) + [(in module code)](library/code#code.interact) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.interact) * [**interactive**](glossary#term-interactive) * [interactive mode](reference/toplevel_components#index-3) * [InteractiveConsole (class in code)](library/code#code.InteractiveConsole) * [InteractiveInterpreter (class in code)](library/code#code.InteractiveInterpreter) * [intern (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-intern) * [intern() (in module sys)](library/sys#sys.intern) * [internal type](reference/datamodel#index-54) * [internal\_attr (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.internal_attr) * [Internaldate2tuple() (in module imaplib)](library/imaplib#imaplib.Internaldate2tuple) * [internalSubset (xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.internalSubset) * [Internet](library/internet#index-0) * [INTERNET\_TIMEOUT (in module test.support)](library/test#test.support.INTERNET_TIMEOUT) * [interpolated string literal](reference/lexical_analysis#index-24) * interpolation + [bytearray (%)](library/stdtypes#index-43) + [bytes (%)](library/stdtypes#index-43) * [interpolation, string (%)](library/stdtypes#index-33) * [InterpolationDepthError](library/configparser#configparser.InterpolationDepthError) * [InterpolationError](library/configparser#configparser.InterpolationError) * [InterpolationMissingOptionError](library/configparser#configparser.InterpolationMissingOptionError) * [InterpolationSyntaxError](library/configparser#configparser.InterpolationSyntaxError) * [**interpreted**](glossary#term-interpreted) * [interpreter](reference/toplevel_components#index-0) * [interpreter lock](c-api/init#index-33) * [interpreter prompts](library/sys#index-26) * [**interpreter shutdown**](glossary#term-interpreter-shutdown) * [interpreter\_requires\_environment() (in module test.support.script\_helper)](library/test#test.support.script_helper.interpreter_requires_environment) * [interrupt() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.interrupt) * [interrupt\_main() (in module \_thread)](library/_thread#_thread.interrupt_main) * [InterruptedError](library/exceptions#InterruptedError) * [intersection() (frozenset method)](library/stdtypes#frozenset.intersection) * [intersection\_update() (frozenset method)](library/stdtypes#frozenset.intersection_update) * [IntFlag (class in enum)](library/enum#enum.IntFlag) * [intro (cmd.Cmd attribute)](library/cmd#cmd.Cmd.intro) * [InuseAttributeErr](library/xml.dom#xml.dom.InuseAttributeErr) * [inv() (in module operator)](library/operator#operator.inv) * [inv\_cdf() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.inv_cdf) * [InvalidAccessErr](library/xml.dom#xml.dom.InvalidAccessErr) * [invalidate\_caches() (importlib.abc.MetaPathFinder method)](library/importlib#importlib.abc.MetaPathFinder.invalidate_caches) + [(importlib.abc.PathEntryFinder method)](library/importlib#importlib.abc.PathEntryFinder.invalidate_caches) + [(importlib.machinery.FileFinder method)](library/importlib#importlib.machinery.FileFinder.invalidate_caches) + [(importlib.machinery.PathFinder class method)](library/importlib#importlib.machinery.PathFinder.invalidate_caches) + [(in module importlib)](library/importlib#importlib.invalidate_caches) * [InvalidCharacterErr](library/xml.dom#xml.dom.InvalidCharacterErr) * [InvalidModificationErr](library/xml.dom#xml.dom.InvalidModificationErr) * [InvalidOperation (class in decimal)](library/decimal#decimal.InvalidOperation) * [InvalidStateErr](library/xml.dom#xml.dom.InvalidStateErr) * [InvalidStateError](library/asyncio-exceptions#asyncio.InvalidStateError), [[1]](library/concurrent.futures#concurrent.futures.InvalidStateError) * [InvalidTZPathWarning](library/zoneinfo#zoneinfo.InvalidTZPathWarning) * [InvalidURL](library/http.client#http.client.InvalidURL) * [inversion](reference/expressions#index-62) * [Invert (class in ast)](library/ast#ast.Invert) * [invert() (in module operator)](library/operator#operator.invert) * [invocation](reference/datamodel#index-32) * io + [module](reference/datamodel#index-53) * [IO (class in typing)](library/typing#typing.IO) * [io (module)](library/io#module-io) * io.StringIO + [object](library/stdtypes#index-27) * [IO\_REPARSE\_TAG\_APPEXECLINK (in module stat)](library/stat#stat.IO_REPARSE_TAG_APPEXECLINK) * [IO\_REPARSE\_TAG\_MOUNT\_POINT (in module stat)](library/stat#stat.IO_REPARSE_TAG_MOUNT_POINT) * [IO\_REPARSE\_TAG\_SYMLINK (in module stat)](library/stat#stat.IO_REPARSE_TAG_SYMLINK) | * [IOBase (class in io)](library/io#io.IOBase) * [ioctl() (in module fcntl)](library/fcntl#fcntl.ioctl) + [(socket.socket method)](library/socket#socket.socket.ioctl) * [IOCTL\_VM\_SOCKETS\_GET\_LOCAL\_CID (in module socket)](library/socket#socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID) * [IOError](library/exceptions#IOError) * [ior() (in module operator)](library/operator#operator.ior) * [ip (ipaddress.IPv4Interface attribute)](library/ipaddress#ipaddress.IPv4Interface.ip) + [(ipaddress.IPv6Interface attribute)](library/ipaddress#ipaddress.IPv6Interface.ip) * [ip\_address() (in module ipaddress)](library/ipaddress#ipaddress.ip_address) * [ip\_interface() (in module ipaddress)](library/ipaddress#ipaddress.ip_interface) * [ip\_network() (in module ipaddress)](library/ipaddress#ipaddress.ip_network) * [ipaddress (module)](library/ipaddress#module-ipaddress) * [ipow() (in module operator)](library/operator#operator.ipow) * [ipv4\_mapped (ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.ipv4_mapped) * [IPv4Address (class in ipaddress)](library/ipaddress#ipaddress.IPv4Address) * [IPv4Interface (class in ipaddress)](library/ipaddress#ipaddress.IPv4Interface) * [IPv4Network (class in ipaddress)](library/ipaddress#ipaddress.IPv4Network) * [IPV6\_ENABLED (in module test.support.socket\_helper)](library/test#test.support.socket_helper.IPV6_ENABLED) * [IPv6Address (class in ipaddress)](library/ipaddress#ipaddress.IPv6Address) * [IPv6Interface (class in ipaddress)](library/ipaddress#ipaddress.IPv6Interface) * [IPv6Network (class in ipaddress)](library/ipaddress#ipaddress.IPv6Network) * [irshift() (in module operator)](library/operator#operator.irshift) * is + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-81) * [Is (class in ast)](library/ast#ast.Is) * is not + [operator](library/stdtypes#index-7), [[1]](reference/expressions#index-81) * [is\_() (in module operator)](library/operator#operator.is_) * [is\_absolute() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.is_absolute) * [is\_active() (asyncio.AbstractChildWatcher method)](library/asyncio-policy#asyncio.AbstractChildWatcher.is_active) + [(graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.is_active) * [is\_alive() (multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.is_alive) + [(threading.Thread method)](library/threading#threading.Thread.is_alive) * [is\_android (in module test.support)](library/test#test.support.is_android) * [is\_annotated() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_annotated) * [is\_assigned() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_assigned) * [is\_attachment() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.is_attachment) * [is\_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth method)](library/urllib.request#urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated) * [is\_block\_device() (pathlib.Path method)](library/pathlib#pathlib.Path.is_block_device) * [is\_blocked() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.is_blocked) * [is\_canonical() (decimal.Context method)](library/decimal#decimal.Context.is_canonical) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_canonical) * [is\_char\_device() (pathlib.Path method)](library/pathlib#pathlib.Path.is_char_device) * [IS\_CHARACTER\_JUNK() (in module difflib)](library/difflib#difflib.IS_CHARACTER_JUNK) * [is\_check\_supported() (in module lzma)](library/lzma#lzma.is_check_supported) * [is\_closed() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.is_closed) * [is\_closing() (asyncio.BaseTransport method)](library/asyncio-protocol#asyncio.BaseTransport.is_closing) + [(asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.is_closing) * [is\_dataclass() (in module dataclasses)](library/dataclasses#dataclasses.is_dataclass) * [is\_declared\_global() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_declared_global) * [is\_dir() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.is_dir) + [(os.DirEntry method)](library/os#os.DirEntry.is_dir) + [(pathlib.Path method)](library/pathlib#pathlib.Path.is_dir) + [(zipfile.Path method)](library/zipfile#zipfile.Path.is_dir) + [(zipfile.ZipInfo method)](library/zipfile#zipfile.ZipInfo.is_dir) * [is\_enabled() (in module faulthandler)](library/faulthandler#faulthandler.is_enabled) * [is\_expired() (http.cookiejar.Cookie method)](library/http.cookiejar#http.cookiejar.Cookie.is_expired) * [is\_fifo() (pathlib.Path method)](library/pathlib#pathlib.Path.is_fifo) * [is\_file() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.is_file) + [(os.DirEntry method)](library/os#os.DirEntry.is_file) + [(pathlib.Path method)](library/pathlib#pathlib.Path.is_file) + [(zipfile.Path method)](library/zipfile#zipfile.Path.is_file) * [is\_finalized() (in module gc)](library/gc#gc.is_finalized) * [is\_finalizing() (in module sys)](library/sys#sys.is_finalizing) * [is\_finite() (decimal.Context method)](library/decimal#decimal.Context.is_finite) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_finite) * [is\_free() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_free) * [is\_global (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_global) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_global) * [is\_global() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_global) * [is\_hop\_by\_hop() (in module wsgiref.util)](library/wsgiref#wsgiref.util.is_hop_by_hop) * [is\_imported() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_imported) * [is\_infinite() (decimal.Context method)](library/decimal#decimal.Context.is_infinite) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_infinite) * [is\_integer() (float method)](library/stdtypes#float.is_integer) * [is\_jython (in module test.support)](library/test#test.support.is_jython) * [IS\_LINE\_JUNK() (in module difflib)](library/difflib#difflib.IS_LINE_JUNK) * [is\_linetouched() (curses.window method)](library/curses#curses.window.is_linetouched) * [is\_link\_local (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_link_local) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_link_local) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_link_local) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_link_local) * [is\_local() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_local) * [is\_loopback (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_loopback) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_loopback) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_loopback) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_loopback) * [is\_mount() (pathlib.Path method)](library/pathlib#pathlib.Path.is_mount) * [is\_multicast (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_multicast) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_multicast) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_multicast) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_multicast) * [is\_multipart() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.is_multipart) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.is_multipart) * [is\_namespace() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_namespace) * [is\_nan() (decimal.Context method)](library/decimal#decimal.Context.is_nan) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_nan) * [is\_nested() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.is_nested) * [is\_nonlocal() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_nonlocal) * [is\_normal() (decimal.Context method)](library/decimal#decimal.Context.is_normal) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_normal) * [is\_normalized() (in module unicodedata)](library/unicodedata#unicodedata.is_normalized) * [is\_not() (in module operator)](library/operator#operator.is_not) * [is\_not\_allowed() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.is_not_allowed) * [IS\_OP (opcode)](library/dis#opcode-IS_OP) * [is\_optimized() (symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.is_optimized) * [is\_package() (importlib.abc.InspectLoader method)](library/importlib#importlib.abc.InspectLoader.is_package) + [(importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.is_package) + [(importlib.machinery.ExtensionFileLoader method)](library/importlib#importlib.machinery.ExtensionFileLoader.is_package) + [(importlib.machinery.SourceFileLoader method)](library/importlib#importlib.machinery.SourceFileLoader.is_package) + [(importlib.machinery.SourcelessFileLoader method)](library/importlib#importlib.machinery.SourcelessFileLoader.is_package) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.is_package) * [is\_parameter() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_parameter) * [is\_private (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_private) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_private) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_private) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_private) * [is\_python\_build() (in module sysconfig)](library/sysconfig#sysconfig.is_python_build) * [is\_qnan() (decimal.Context method)](library/decimal#decimal.Context.is_qnan) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_qnan) * [is\_reading() (asyncio.ReadTransport method)](library/asyncio-protocol#asyncio.ReadTransport.is_reading) * [is\_referenced() (symtable.Symbol method)](library/symtable#symtable.Symbol.is_referenced) * [is\_relative\_to() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.is_relative_to) * [is\_reserved (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_reserved) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_reserved) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_reserved) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_reserved) * [is\_reserved() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.is_reserved) * [is\_resource() (importlib.abc.ResourceReader method)](library/importlib#importlib.abc.ResourceReader.is_resource) + [(in module importlib.resources)](library/importlib#importlib.resources.is_resource) * [is\_resource\_enabled() (in module test.support)](library/test#test.support.is_resource_enabled) * [is\_running() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.is_running) * [is\_safe (uuid.UUID attribute)](library/uuid#uuid.UUID.is_safe) * [is\_serving() (asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.is_serving) * [is\_set() (asyncio.Event method)](library/asyncio-sync#asyncio.Event.is_set) + [(threading.Event method)](library/threading#threading.Event.is_set) * [is\_signed() (decimal.Context method)](library/decimal#decimal.Context.is_signed) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_signed) * [is\_site\_local (ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_site_local) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_site_local) * [is\_snan() (decimal.Context method)](library/decimal#decimal.Context.is_snan) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_snan) * [is\_socket() (pathlib.Path method)](library/pathlib#pathlib.Path.is_socket) * [is\_subnormal() (decimal.Context method)](library/decimal#decimal.Context.is_subnormal) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_subnormal) * [is\_symlink() (os.DirEntry method)](library/os#os.DirEntry.is_symlink) + [(pathlib.Path method)](library/pathlib#pathlib.Path.is_symlink) * [is\_tarfile() (in module tarfile)](library/tarfile#tarfile.is_tarfile) * [is\_term\_resized() (in module curses)](library/curses#curses.is_term_resized) * [is\_tracing() (in module tracemalloc)](library/tracemalloc#tracemalloc.is_tracing) * [is\_tracked() (in module gc)](library/gc#gc.is_tracked) * [is\_unspecified (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.is_unspecified) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.is_unspecified) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.is_unspecified) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.is_unspecified) * [is\_wintouched() (curses.window method)](library/curses#curses.window.is_wintouched) * [is\_zero() (decimal.Context method)](library/decimal#decimal.Context.is_zero) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.is_zero) * [is\_zipfile() (in module zipfile)](library/zipfile#zipfile.is_zipfile) * [isabs() (in module os.path)](library/os.path#os.path.isabs) * [isabstract() (in module inspect)](library/inspect#inspect.isabstract) * [IsADirectoryError](library/exceptions#IsADirectoryError) * [isalnum() (bytearray method)](library/stdtypes#bytearray.isalnum) + [(bytes method)](library/stdtypes#bytes.isalnum) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isalnum) + [(str method)](library/stdtypes#str.isalnum) * [isalpha() (bytearray method)](library/stdtypes#bytearray.isalpha) + [(bytes method)](library/stdtypes#bytes.isalpha) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isalpha) + [(str method)](library/stdtypes#str.isalpha) * [isascii() (bytearray method)](library/stdtypes#bytearray.isascii) + [(bytes method)](library/stdtypes#bytes.isascii) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isascii) + [(str method)](library/stdtypes#str.isascii) * [isasyncgen() (in module inspect)](library/inspect#inspect.isasyncgen) * [isasyncgenfunction() (in module inspect)](library/inspect#inspect.isasyncgenfunction) * [isatty() (chunk.Chunk method)](library/chunk#chunk.Chunk.isatty) + [(in module os)](library/os#os.isatty) + [(io.IOBase method)](library/io#io.IOBase.isatty) * [isawaitable() (in module inspect)](library/inspect#inspect.isawaitable) * [isblank() (in module curses.ascii)](library/curses.ascii#curses.ascii.isblank) * [isblk() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isblk) * [isbuiltin() (in module inspect)](library/inspect#inspect.isbuiltin) * [ischr() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.ischr) * [isclass() (in module inspect)](library/inspect#inspect.isclass) * [isclose() (in module cmath)](library/cmath#cmath.isclose) + [(in module math)](library/math#math.isclose) * [iscntrl() (in module curses.ascii)](library/curses.ascii#curses.ascii.iscntrl) * [iscode() (in module inspect)](library/inspect#inspect.iscode) * [iscoroutine() (in module asyncio)](library/asyncio-task#asyncio.iscoroutine) + [(in module inspect)](library/inspect#inspect.iscoroutine) * [iscoroutinefunction() (in module asyncio)](library/asyncio-task#asyncio.iscoroutinefunction) + [(in module inspect)](library/inspect#inspect.iscoroutinefunction) * [isctrl() (in module curses.ascii)](library/curses.ascii#curses.ascii.isctrl) * [isDaemon() (threading.Thread method)](library/threading#threading.Thread.isDaemon) * [isdatadescriptor() (in module inspect)](library/inspect#inspect.isdatadescriptor) * [isdecimal() (str method)](library/stdtypes#str.isdecimal) * [isdev() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isdev) * [isdigit() (bytearray method)](library/stdtypes#bytearray.isdigit) + [(bytes method)](library/stdtypes#bytes.isdigit) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isdigit) + [(str method)](library/stdtypes#str.isdigit) * [isdir() (in module os.path)](library/os.path#os.path.isdir) + [(tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isdir) * [isdisjoint() (frozenset method)](library/stdtypes#frozenset.isdisjoint) * [isdown() (in module turtle)](library/turtle#turtle.isdown) * [iselement() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.iselement) * [isenabled() (in module gc)](library/gc#gc.isenabled) * [isEnabledFor() (logging.Logger method)](library/logging#logging.Logger.isEnabledFor) * [isendwin() (in module curses)](library/curses#curses.isendwin) * [ISEOF() (in module token)](library/token#token.ISEOF) * [isexpr() (in module parser)](library/parser#parser.isexpr) + [(parser.ST method)](library/parser#parser.ST.isexpr) * [isfifo() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isfifo) * [isfile() (in module os.path)](library/os.path#os.path.isfile) + [(tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isfile) * [isfinite() (in module cmath)](library/cmath#cmath.isfinite) + [(in module math)](library/math#math.isfinite) * [isfirstline() (in module fileinput)](library/fileinput#fileinput.isfirstline) * [isframe() (in module inspect)](library/inspect#inspect.isframe) * [isfunction() (in module inspect)](library/inspect#inspect.isfunction) * [isfuture() (in module asyncio)](library/asyncio-future#asyncio.isfuture) * [isgenerator() (in module inspect)](library/inspect#inspect.isgenerator) * [isgeneratorfunction() (in module inspect)](library/inspect#inspect.isgeneratorfunction) * [isgetsetdescriptor() (in module inspect)](library/inspect#inspect.isgetsetdescriptor) * [isgraph() (in module curses.ascii)](library/curses.ascii#curses.ascii.isgraph) * [isidentifier() (str method)](library/stdtypes#str.isidentifier) * [isinf() (in module cmath)](library/cmath#cmath.isinf) + [(in module math)](library/math#math.isinf) * [isinstance (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-isinstance) * [isinstance() (built-in function)](library/functions#isinstance) * [iskeyword() (in module keyword)](library/keyword#keyword.iskeyword) * [isleap() (in module calendar)](library/calendar#calendar.isleap) * [islice() (in module itertools)](library/itertools#itertools.islice) * [islink() (in module os.path)](library/os.path#os.path.islink) * [islnk() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.islnk) * [islower() (bytearray method)](library/stdtypes#bytearray.islower) + [(bytes method)](library/stdtypes#bytes.islower) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.islower) + [(str method)](library/stdtypes#str.islower) * [ismemberdescriptor() (in module inspect)](library/inspect#inspect.ismemberdescriptor) * [ismeta() (in module curses.ascii)](library/curses.ascii#curses.ascii.ismeta) * [ismethod() (in module inspect)](library/inspect#inspect.ismethod) * [ismethoddescriptor() (in module inspect)](library/inspect#inspect.ismethoddescriptor) * [ismodule() (in module inspect)](library/inspect#inspect.ismodule) * [ismount() (in module os.path)](library/os.path#os.path.ismount) * [isnan() (in module cmath)](library/cmath#cmath.isnan) + [(in module math)](library/math#math.isnan) * [ISNONTERMINAL() (in module token)](library/token#token.ISNONTERMINAL) * [IsNot (class in ast)](library/ast#ast.IsNot) * [isnumeric() (str method)](library/stdtypes#str.isnumeric) * [isocalendar() (datetime.date method)](library/datetime#datetime.date.isocalendar) + [(datetime.datetime method)](library/datetime#datetime.datetime.isocalendar) * [isoformat() (datetime.date method)](library/datetime#datetime.date.isoformat) + [(datetime.datetime method)](library/datetime#datetime.datetime.isoformat) + [(datetime.time method)](library/datetime#datetime.time.isoformat) * [IsolatedAsyncioTestCase (class in unittest)](library/unittest#unittest.IsolatedAsyncioTestCase) * [isolation\_level (sqlite3.Connection attribute)](library/sqlite3#sqlite3.Connection.isolation_level) * [isoweekday() (datetime.date method)](library/datetime#datetime.date.isoweekday) + [(datetime.datetime method)](library/datetime#datetime.datetime.isoweekday) * [isprint() (in module curses.ascii)](library/curses.ascii#curses.ascii.isprint) * [isprintable() (str method)](library/stdtypes#str.isprintable) * [ispunct() (in module curses.ascii)](library/curses.ascii#curses.ascii.ispunct) * [isqrt() (in module math)](library/math#math.isqrt) * [isreadable() (in module pprint)](library/pprint#pprint.isreadable) + [(pprint.PrettyPrinter method)](library/pprint#pprint.PrettyPrinter.isreadable) * [isrecursive() (in module pprint)](library/pprint#pprint.isrecursive) + [(pprint.PrettyPrinter method)](library/pprint#pprint.PrettyPrinter.isrecursive) * [isreg() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.isreg) * [isReservedKey() (http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.isReservedKey) * [isroutine() (in module inspect)](library/inspect#inspect.isroutine) * [isSameNode() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.isSameNode) * [issoftkeyword() (in module keyword)](library/keyword#keyword.issoftkeyword) * [isspace() (bytearray method)](library/stdtypes#bytearray.isspace) + [(bytes method)](library/stdtypes#bytes.isspace) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isspace) + [(str method)](library/stdtypes#str.isspace) * [isstdin() (in module fileinput)](library/fileinput#fileinput.isstdin) * [issubclass() (built-in function)](library/functions#issubclass) * [issubset() (frozenset method)](library/stdtypes#frozenset.issubset) * [issuite() (in module parser)](library/parser#parser.issuite) + [(parser.ST method)](library/parser#parser.ST.issuite) * [issuperset() (frozenset method)](library/stdtypes#frozenset.issuperset) * [issym() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.issym) * [ISTERMINAL() (in module token)](library/token#token.ISTERMINAL) * [istitle() (bytearray method)](library/stdtypes#bytearray.istitle) + [(bytes method)](library/stdtypes#bytes.istitle) + [(str method)](library/stdtypes#str.istitle) * [istraceback() (in module inspect)](library/inspect#inspect.istraceback) * [isub() (in module operator)](library/operator#operator.isub) * [isupper() (bytearray method)](library/stdtypes#bytearray.isupper) + [(bytes method)](library/stdtypes#bytes.isupper) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.isupper) + [(str method)](library/stdtypes#str.isupper) * [isvisible() (in module turtle)](library/turtle#turtle.isvisible) * [isxdigit() (in module curses.ascii)](library/curses.ascii#curses.ascii.isxdigit) * [ITALIC (in module tkinter.font)](library/tkinter.font#tkinter.font.ITALIC) * item + [sequence](reference/expressions#index-42) + [string](reference/expressions#index-43) * [item selection](reference/datamodel#index-15) * [item() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.item) + [(xml.dom.NamedNodeMap method)](library/xml.dom#xml.dom.NamedNodeMap.item) + [(xml.dom.NodeList method)](library/xml.dom#xml.dom.NodeList.item) * [itemgetter() (in module operator)](library/operator#operator.itemgetter) * [items() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.items) + [(contextvars.Context method)](library/contextvars#contextvars.Context.items) + [(dict method)](library/stdtypes#dict.items) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.items) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.items) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.items) + [(types.MappingProxyType method)](library/types#types.MappingProxyType.items) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.items) * [itemsize (array.array attribute)](library/array#array.array.itemsize) + [(memoryview attribute)](library/stdtypes#memoryview.itemsize) * [ItemsView (class in collections.abc)](library/collections.abc#collections.abc.ItemsView) + [(class in typing)](library/typing#typing.ItemsView) * [iter() (built-in function)](library/functions#iter) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.iter) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.iter) * [iter\_attachments() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.iter_attachments) * [iter\_child\_nodes() (in module ast)](library/ast#ast.iter_child_nodes) * [iter\_fields() (in module ast)](library/ast#ast.iter_fields) * [iter\_importers() (in module pkgutil)](library/pkgutil#pkgutil.iter_importers) * [iter\_modules() (in module pkgutil)](library/pkgutil#pkgutil.iter_modules) * [iter\_parts() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.iter_parts) * [iter\_unpack() (in module struct)](library/struct#struct.iter_unpack) + [(struct.Struct method)](library/struct#struct.Struct.iter_unpack) * [**iterable**](glossary#term-iterable) + [unpacking](reference/expressions#index-92) * [Iterable (class in collections.abc)](library/collections.abc#collections.abc.Iterable) + [(class in typing)](library/typing#typing.Iterable) * [**iterator**](glossary#term-iterator) * [Iterator (class in collections.abc)](library/collections.abc#collections.abc.Iterator) + [(class in typing)](library/typing#typing.Iterator) * [iterator protocol](library/stdtypes#index-17) * [iterdecode() (in module codecs)](library/codecs#codecs.iterdecode) * [iterdir() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.iterdir) + [(pathlib.Path method)](library/pathlib#pathlib.Path.iterdir) + [(zipfile.Path method)](library/zipfile#zipfile.Path.iterdir) * [iterdump() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.iterdump) * [iterencode() (in module codecs)](library/codecs#codecs.iterencode) + [(json.JSONEncoder method)](library/json#json.JSONEncoder.iterencode) * [iterfind() (xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.iterfind) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.iterfind) * [iteritems() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.iteritems) * [iterkeys() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.iterkeys) * [itermonthdates() (calendar.Calendar method)](library/calendar#calendar.Calendar.itermonthdates) * [itermonthdays() (calendar.Calendar method)](library/calendar#calendar.Calendar.itermonthdays) * [itermonthdays2() (calendar.Calendar method)](library/calendar#calendar.Calendar.itermonthdays2) * [itermonthdays3() (calendar.Calendar method)](library/calendar#calendar.Calendar.itermonthdays3) * [itermonthdays4() (calendar.Calendar method)](library/calendar#calendar.Calendar.itermonthdays4) * [iternextfunc (C type)](c-api/typeobj#c.iternextfunc) * [iterparse() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.iterparse) * [itertext() (xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.itertext) * [itertools (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-itertools) + [(module)](library/itertools#module-itertools) * [itertools\_imports (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-itertools_imports) * [itervalues() (mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.itervalues) * [iterweekdays() (calendar.Calendar method)](library/calendar#calendar.Calendar.iterweekdays) * [ITIMER\_PROF (in module signal)](library/signal#signal.ITIMER_PROF) * [ITIMER\_REAL (in module signal)](library/signal#signal.ITIMER_REAL) * [ITIMER\_VIRTUAL (in module signal)](library/signal#signal.ITIMER_VIRTUAL) * [ItimerError](library/signal#signal.ItimerError) * [itruediv() (in module operator)](library/operator#operator.itruediv) * [ixor() (in module operator)](library/operator#operator.ixor) | J - | | | | --- | --- | | * j + [in numeric literal](reference/lexical_analysis#index-29) * [Jansen, Jack](library/uu#index-1) * Java + [language](reference/datamodel#index-13) * [java\_ver() (in module platform)](library/platform#platform.java_ver) * [join() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.join) + [(bytearray method)](library/stdtypes#bytearray.join) + [(bytes method)](library/stdtypes#bytes.join) + [(in module os.path)](library/os.path#os.path.join) + [(in module shlex)](library/shlex#shlex.join) + [(multiprocessing.JoinableQueue method)](library/multiprocessing#multiprocessing.JoinableQueue.join) + [(multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.join) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.join) + [(queue.Queue method)](library/queue#queue.Queue.join) + [(str method)](library/stdtypes#str.join) + [(threading.Thread method)](library/threading#threading.Thread.join) * [join\_thread() (in module test.support)](library/test#test.support.join_thread) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.join_thread) * [JoinableQueue (class in multiprocessing)](library/multiprocessing#multiprocessing.JoinableQueue) * [JoinedStr (class in ast)](library/ast#ast.JoinedStr) * [joinpath() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.joinpath) + [(pathlib.PurePath method)](library/pathlib#pathlib.PurePath.joinpath) * [js\_output() (http.cookies.BaseCookie method)](library/http.cookies#http.cookies.BaseCookie.js_output) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.js_output) | * json + [module](tutorial/inputoutput#index-1) * [json (module)](library/json#module-json) * [json.tool (module)](library/json#module-json.tool) * json.tool command line option + [--compact](library/json#cmdoption-json-tool-indent) + [--help](library/json#cmdoption-json-tool-h) + [--indent](library/json#cmdoption-json-tool-indent) + [--json-lines](library/json#cmdoption-json-tool-json-lines) + [--no-ensure-ascii](library/json#cmdoption-json-tool-no-ensure-ascii) + [--no-indent](library/json#cmdoption-json-tool-indent) + [--sort-keys](library/json#cmdoption-json-tool-sort-keys) + [--tab](library/json#cmdoption-json-tool-indent) + [-h](library/json#cmdoption-json-tool-h) + [infile](library/json#cmdoption-json-tool-arg-infile) + [outfile](library/json#cmdoption-json-tool-arg-outfile) * [JSONDecodeError](library/json#json.JSONDecodeError) * [JSONDecoder (class in json)](library/json#json.JSONDecoder) * [JSONEncoder (class in json)](library/json#json.JSONEncoder) * [jump (pdb command)](library/pdb#pdbcommand-jump) * [JUMP\_ABSOLUTE (opcode)](library/dis#opcode-JUMP_ABSOLUTE) * [JUMP\_FORWARD (opcode)](library/dis#opcode-JUMP_FORWARD) * [JUMP\_IF\_FALSE\_OR\_POP (opcode)](library/dis#opcode-JUMP_IF_FALSE_OR_POP) * [JUMP\_IF\_NOT\_EXC\_MATCH (opcode)](library/dis#opcode-JUMP_IF_NOT_EXC_MATCH) * [JUMP\_IF\_TRUE\_OR\_POP (opcode)](library/dis#opcode-JUMP_IF_TRUE_OR_POP) | K - | | | | --- | --- | | * [kbhit() (in module msvcrt)](library/msvcrt#msvcrt.kbhit) * [KDEDIR](library/webbrowser#index-2) * [kevent() (in module select)](library/select#select.kevent) * [key](reference/expressions#index-17) + [(http.cookies.Morsel attribute)](library/http.cookies#http.cookies.Morsel.key) + [(zoneinfo.ZoneInfo attribute)](library/zoneinfo#zoneinfo.ZoneInfo.key) * [**key function**](glossary#term-key-function) * [key/datum pair](reference/expressions#index-17) * [KEY\_ALL\_ACCESS (in module winreg)](library/winreg#winreg.KEY_ALL_ACCESS) * [KEY\_CREATE\_LINK (in module winreg)](library/winreg#winreg.KEY_CREATE_LINK) * [KEY\_CREATE\_SUB\_KEY (in module winreg)](library/winreg#winreg.KEY_CREATE_SUB_KEY) * [KEY\_ENUMERATE\_SUB\_KEYS (in module winreg)](library/winreg#winreg.KEY_ENUMERATE_SUB_KEYS) * [KEY\_EXECUTE (in module winreg)](library/winreg#winreg.KEY_EXECUTE) * [KEY\_NOTIFY (in module winreg)](library/winreg#winreg.KEY_NOTIFY) * [KEY\_QUERY\_VALUE (in module winreg)](library/winreg#winreg.KEY_QUERY_VALUE) * [KEY\_READ (in module winreg)](library/winreg#winreg.KEY_READ) * [KEY\_SET\_VALUE (in module winreg)](library/winreg#winreg.KEY_SET_VALUE) * [KEY\_WOW64\_32KEY (in module winreg)](library/winreg#winreg.KEY_WOW64_32KEY) * [KEY\_WOW64\_64KEY (in module winreg)](library/winreg#winreg.KEY_WOW64_64KEY) * [KEY\_WRITE (in module winreg)](library/winreg#winreg.KEY_WRITE) * [KeyboardInterrupt](library/exceptions#KeyboardInterrupt) + [(built-in exception)](c-api/exceptions#index-1), [[1]](c-api/exceptions#index-2) * [KeyError](library/exceptions#KeyError) * [keylog\_filename (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.keylog_filename) * [keyname() (in module curses)](library/curses#curses.keyname) * [keypad() (curses.window method)](library/curses#curses.window.keypad) * [keyrefs() (weakref.WeakKeyDictionary method)](library/weakref#weakref.WeakKeyDictionary.keyrefs) * [keys() (contextvars.Context method)](library/contextvars#contextvars.Context.keys) + [(dict method)](library/stdtypes#dict.keys) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.keys) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.keys) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.keys) + [(sqlite3.Row method)](library/sqlite3#sqlite3.Row.keys) + [(types.MappingProxyType method)](library/types#types.MappingProxyType.keys) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.keys) | * [KeysView (class in collections.abc)](library/collections.abc#collections.abc.KeysView) + [(class in typing)](library/typing#typing.KeysView) * [keyword](reference/lexical_analysis#index-13) + [as](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-16), [[2]](reference/simple_stmts#index-34) + [async](reference/compound_stmts#index-38) + [await](reference/compound_stmts#index-38), [[1]](reference/expressions#index-57) + [elif](reference/compound_stmts#index-3) + [else](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-13), [[2]](reference/compound_stmts#index-3), [[3]](reference/compound_stmts#index-4), [[4]](reference/compound_stmts#index-6), [[5]](reference/simple_stmts#index-31) + [except](reference/compound_stmts#index-10) + [finally](reference/compound_stmts#index-10), [[1]](reference/compound_stmts#index-14), [[2]](reference/simple_stmts#index-25), [[3]](reference/simple_stmts#index-32), [[4]](reference/simple_stmts#index-33) + [from](reference/expressions#index-23), [[1]](reference/simple_stmts#index-34) + [in](reference/compound_stmts#index-6) + [yield](reference/expressions#index-23) * [keyword (class in ast)](library/ast#ast.keyword) + [(module)](library/keyword#module-keyword) * [**keyword argument**](glossary#term-keyword-argument) * [keywords (functools.partial attribute)](library/functools#functools.partial.keywords) * [kill() (asyncio.subprocess.Process method)](library/asyncio-subprocess#asyncio.subprocess.Process.kill) + [(asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.kill) + [(in module os)](library/os#os.kill) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.kill) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.kill) * [kill\_python() (in module test.support.script\_helper)](library/test#test.support.script_helper.kill_python) * [killchar() (in module curses)](library/curses#curses.killchar) * [killpg() (in module os)](library/os#os.killpg) * [kind (inspect.Parameter attribute)](library/inspect#inspect.Parameter.kind) * [knownfiles (in module mimetypes)](library/mimetypes#mimetypes.knownfiles) * [kqueue() (in module select)](library/select#select.kqueue) * [KqueueSelector (class in selectors)](library/selectors#selectors.KqueueSelector) * [kwargs (inspect.BoundArguments attribute)](library/inspect#inspect.BoundArguments.kwargs) * [kwlist (in module keyword)](library/keyword#keyword.kwlist) | L - | | | | --- | --- | | * [L (in module re)](library/re#re.L) * [LabelEntry (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.LabelEntry) * [LabelFrame (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.LabelFrame) * [**lambda**](glossary#term-lambda) + [expression](reference/compound_stmts#index-26), [[1]](reference/expressions#index-89) + [form](reference/expressions#index-89) * [Lambda (class in ast)](library/ast#ast.Lambda) * [LambdaType (in module types)](library/types#types.LambdaType) * [LANG](library/gettext#index-3), [[1]](library/gettext#index-8), [[2]](library/locale#index-1), [[3]](library/locale#index-2), [[4]](library/locale#index-3) * [LANGUAGE](library/gettext#index-0), [[1]](library/gettext#index-5) * language + [C](library/stdtypes#index-11), [[1]](library/stdtypes#index-15), [[2]](reference/datamodel#index-13), [[3]](reference/datamodel#index-4), [[4]](reference/datamodel#index-40), [[5]](reference/expressions#index-77) + [Java](reference/datamodel#index-13) * [large files](library/posix#index-1) * [LARGEST (in module test.support)](library/test#test.support.LARGEST) * [LargeZipFile](library/zipfile#zipfile.LargeZipFile) * [last() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.last) * [last\_accepted (multiprocessing.connection.Listener attribute)](library/multiprocessing#multiprocessing.connection.Listener.last_accepted) * [last\_traceback (in module sys)](library/sys#sys.last_traceback), [[1]](reference/datamodel#index-62) * [last\_type (in module sys)](library/sys#sys.last_type) * [last\_value (in module sys)](library/sys#sys.last_value) * [lastChild (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.lastChild) * [lastcmd (cmd.Cmd attribute)](library/cmd#cmd.Cmd.lastcmd) * [lastgroup (re.Match attribute)](library/re#re.Match.lastgroup) * [lastindex (re.Match attribute)](library/re#re.Match.lastindex) * [lastResort (in module logging)](library/logging#logging.lastResort) * [lastrowid (sqlite3.Cursor attribute)](library/sqlite3#sqlite3.Cursor.lastrowid) * [layout() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.layout) * [lazycache() (in module linecache)](library/linecache#linecache.lazycache) * [LazyLoader (class in importlib.util)](library/importlib#importlib.util.LazyLoader) * [LBRACE (in module token)](library/token#token.LBRACE) * [**LBYL**](glossary#term-lbyl) * [LC\_ALL](library/gettext#index-1), [[1]](library/gettext#index-6) + [(in module locale)](library/locale#locale.LC_ALL) * [LC\_COLLATE (in module locale)](library/locale#locale.LC_COLLATE) * [LC\_CTYPE (in module locale)](library/locale#locale.LC_CTYPE) * [LC\_MESSAGES](library/gettext#index-2), [[1]](library/gettext#index-7) + [(in module locale)](library/locale#locale.LC_MESSAGES) * [LC\_MONETARY (in module locale)](library/locale#locale.LC_MONETARY) * [LC\_NUMERIC (in module locale)](library/locale#locale.LC_NUMERIC) * [LC\_TIME (in module locale)](library/locale#locale.LC_TIME) * [lchflags() (in module os)](library/os#os.lchflags) * [lchmod() (in module os)](library/os#os.lchmod) + [(pathlib.Path method)](library/pathlib#pathlib.Path.lchmod) * [lchown() (in module os)](library/os#os.lchown) * [lcm() (in module math)](library/math#math.lcm) * [LDCXXSHARED](https://docs.python.org/3.9/whatsnew/2.7.html#index-12) * [ldexp() (in module math)](library/math#math.ldexp) * [LDFLAGS](https://docs.python.org/3.9/whatsnew/2.3.html#index-27) * [ldgettext() (in module gettext)](library/gettext#gettext.ldgettext) * [ldngettext() (in module gettext)](library/gettext#gettext.ldngettext) * [le() (in module operator)](library/operator#operator.le) * [leading whitespace](reference/lexical_analysis#index-8) * [leapdays() (in module calendar)](library/calendar#calendar.leapdays) * [leaveok() (curses.window method)](library/curses#curses.window.leaveok) * [left (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.left) * [left() (in module turtle)](library/turtle#turtle.left) * [left\_list (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.left_list) * [left\_only (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.left_only) * [LEFTSHIFT (in module token)](library/token#token.LEFTSHIFT) * [LEFTSHIFTEQUAL (in module token)](library/token#token.LEFTSHIFTEQUAL) * len + [built-in function](c-api/dict#index-2), [[1]](c-api/list#index-1), [[2]](c-api/mapping#index-0), [[3]](c-api/object#index-8), [[4]](c-api/sequence#index-0), [[5]](c-api/set#index-1), [[6]](library/stdtypes#index-19), [[7]](library/stdtypes#index-50), [[8]](reference/datamodel#index-15), [[9]](reference/datamodel#index-26), [[10]](reference/datamodel#index-29), [[11]](reference/datamodel#index-94) * [len() (built-in function)](library/functions#len) * [lenfunc (C type)](c-api/typeobj#c.lenfunc) * [length (xml.dom.NamedNodeMap attribute)](library/xml.dom#xml.dom.NamedNodeMap.length) + [(xml.dom.NodeList attribute)](library/xml.dom#xml.dom.NodeList.length) * [length\_hint() (in module operator)](library/operator#operator.length_hint) * [LESS (in module token)](library/token#token.LESS) * [LESSEQUAL (in module token)](library/token#token.LESSEQUAL) * [lexical analysis](reference/lexical_analysis#index-0) * [lexical definitions](reference/introduction#index-1) * [lexists() (in module os.path)](library/os.path#os.path.lexists) * [lgamma() (in module math)](library/math#math.lgamma) * [lgettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.lgettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.lgettext) + [(in module gettext)](library/gettext#gettext.lgettext) * [lib2to3 (module)](https://docs.python.org/3.9/library/2to3.html#module-lib2to3) * [libc\_ver() (in module platform)](library/platform#platform.libc_ver) * [library (in module dbm.ndbm)](library/dbm#dbm.ndbm.library) + [(ssl.SSLError attribute)](library/ssl#ssl.SSLError.library) * [library\_dir\_option() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.library_dir_option) * [library\_filename() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.library_filename) * [library\_option() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.library_option) * [LibraryLoader (class in ctypes)](library/ctypes#ctypes.LibraryLoader) * [license (built-in variable)](library/constants#license) * [LifoQueue (class in asyncio)](library/asyncio-queue#asyncio.LifoQueue) + [(class in queue)](library/queue#queue.LifoQueue) * [light-weight processes](library/_thread#index-0) * [limit\_denominator() (fractions.Fraction method)](library/fractions#fractions.Fraction.limit_denominator) * [LimitOverrunError](library/asyncio-exceptions#asyncio.LimitOverrunError) * [lin2adpcm() (in module audioop)](library/audioop#audioop.lin2adpcm) * [lin2alaw() (in module audioop)](library/audioop#audioop.lin2alaw) * [lin2lin() (in module audioop)](library/audioop#audioop.lin2lin) * [lin2ulaw() (in module audioop)](library/audioop#audioop.lin2ulaw) * [line continuation](reference/lexical_analysis#index-6) * [line joining](reference/lexical_analysis#index-3), [[1]](reference/lexical_analysis#index-6) * [line structure](reference/lexical_analysis#index-2) * [line() (msilib.Dialog method)](library/msilib#msilib.Dialog.line) * [line-buffered I/O](library/functions#index-7) * [line\_buffering (io.TextIOWrapper attribute)](library/io#io.TextIOWrapper.line_buffering) * [line\_num (csv.csvreader attribute)](library/csv#csv.csvreader.line_num) * [linecache (module)](library/linecache#module-linecache) * [lineno (ast.AST attribute)](library/ast#ast.AST.lineno) + [(doctest.DocTest attribute)](library/doctest#doctest.DocTest.lineno) + [(doctest.Example attribute)](library/doctest#doctest.Example.lineno) + [(json.JSONDecodeError attribute)](library/json#json.JSONDecodeError.lineno) + [(pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.lineno) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.lineno) + [(re.error attribute)](library/re#re.error.lineno) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.lineno) + [(SyntaxError attribute)](library/exceptions#SyntaxError.lineno) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.lineno) + [(tracemalloc.Filter attribute)](library/tracemalloc#tracemalloc.Filter.lineno) + [(tracemalloc.Frame attribute)](library/tracemalloc#tracemalloc.Frame.lineno) + [(xml.parsers.expat.ExpatError attribute)](library/pyexpat#xml.parsers.expat.ExpatError.lineno) * [lineno() (in module fileinput)](library/fileinput#fileinput.lineno) * [LINES](library/curses#index-0), [[1]](library/curses#index-3), [[2]](library/curses#index-5), [[3]](library/curses#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-31) * [lines (os.terminal\_size attribute)](library/os#os.terminal_size.lines) * [linesep (email.policy.Policy attribute)](library/email.policy#email.policy.Policy.linesep) + [(in module os)](library/os#os.linesep) * [lineterminator (csv.Dialect attribute)](library/csv#csv.Dialect.lineterminator) * [LineTooLong](library/http.client#http.client.LineTooLong) * [link() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.link) + [(in module os)](library/os#os.link) * [link\_executable() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.link_executable) * [link\_shared\_lib() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.link_shared_lib) * [link\_shared\_object() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.link_shared_object) * [link\_to() (pathlib.Path method)](library/pathlib#pathlib.Path.link_to) * [linkname (tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.linkname) * [**list**](glossary#term-list) + [assignment, target](reference/simple_stmts#index-6) + [comprehensions](reference/expressions#index-15) + [deletion target](reference/simple_stmts#index-21) + [display](reference/expressions#index-15) + [empty](reference/expressions#index-15) + [expression](reference/expressions#index-90), [[1]](reference/simple_stmts#index-1), [[2]](reference/simple_stmts#index-2) + [object](c-api/list#index-0), [[1]](library/stdtypes#index-21), [[2]](library/stdtypes#index-23), [[3]](reference/datamodel#index-23), [[4]](reference/expressions#index-15), [[5]](reference/expressions#index-40), [[6]](reference/expressions#index-42), [[7]](reference/expressions#index-45), [[8]](reference/simple_stmts#index-10) + [target](reference/compound_stmts#index-6), [[1]](reference/simple_stmts#index-5) + [type, operations on](library/stdtypes#index-22) * [list (built-in class)](library/stdtypes#list) * [List (class in ast)](library/ast#ast.List) + [(class in typing)](library/typing#typing.List) * [list (pdb command)](library/pdb#pdbcommand-list) * [**list comprehension**](glossary#term-list-comprehension) * [list() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.list) + [(multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.list) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.list) + [(poplib.POP3 method)](library/poplib#poplib.POP3.list) + [(tarfile.TarFile method)](library/tarfile#tarfile.TarFile.list) * [LIST\_APPEND (opcode)](library/dis#opcode-LIST_APPEND) * [list\_dialects() (in module csv)](library/csv#csv.list_dialects) * [LIST\_EXTEND (opcode)](library/dis#opcode-LIST_EXTEND) * [list\_folders() (mailbox.Maildir method)](library/mailbox#mailbox.Maildir.list_folders) + [(mailbox.MH method)](library/mailbox#mailbox.MH.list_folders) * [LIST\_TO\_TUPLE (opcode)](library/dis#opcode-LIST_TO_TUPLE) * [ListComp (class in ast)](library/ast#ast.ListComp) * [listdir() (in module os)](library/os#os.listdir) * [listen() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.listen) + [(in module logging.config)](library/logging.config#logging.config.listen) + [(in module turtle)](library/turtle#turtle.listen) + [(socket.socket method)](library/socket#socket.socket.listen) * [Listener (class in multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.Listener) * [listMethods() (xmlrpc.client.ServerProxy.system method)](library/xmlrpc.client#xmlrpc.client.ServerProxy.system.listMethods) * [ListNoteBook (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.ListNoteBook) * [listxattr() (in module os)](library/os#os.listxattr) * [literal](reference/expressions#index-6), [[1]](reference/lexical_analysis#index-15) * [Literal (in module typing)](library/typing#typing.Literal) * [literal\_eval() (in module ast)](library/ast#ast.literal_eval) * literals + [binary](library/stdtypes#index-12) + [complex number](library/stdtypes#index-12) + [floating point](library/stdtypes#index-12) + [hexadecimal](library/stdtypes#index-12) + [integer](library/stdtypes#index-12) + [numeric](library/stdtypes#index-12) + [octal](library/stdtypes#index-12) * [LittleEndianStructure (class in ctypes)](library/ctypes#ctypes.LittleEndianStructure) * [ljust() (bytearray method)](library/stdtypes#bytearray.ljust) + [(bytes method)](library/stdtypes#bytes.ljust) + [(str method)](library/stdtypes#str.ljust) * [LK\_LOCK (in module msvcrt)](library/msvcrt#msvcrt.LK_LOCK) * [LK\_NBLCK (in module msvcrt)](library/msvcrt#msvcrt.LK_NBLCK) * [LK\_NBRLCK (in module msvcrt)](library/msvcrt#msvcrt.LK_NBRLCK) | * [LK\_RLCK (in module msvcrt)](library/msvcrt#msvcrt.LK_RLCK) * [LK\_UNLCK (in module msvcrt)](library/msvcrt#msvcrt.LK_UNLCK) * [ll (pdb command)](library/pdb#pdbcommand-ll) * [LMTP (class in smtplib)](library/smtplib#smtplib.LMTP) * [ln() (decimal.Context method)](library/decimal#decimal.Context.ln) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.ln) * [LNAME](library/getpass#index-2) * [lngettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.lngettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.lngettext) + [(in module gettext)](library/gettext#gettext.lngettext) * [Load (class in ast)](library/ast#ast.Load) * [load() (http.cookiejar.FileCookieJar method)](library/http.cookiejar#http.cookiejar.FileCookieJar.load) + [(http.cookies.BaseCookie method)](library/http.cookies#http.cookies.BaseCookie.load) + [(in module json)](library/json#json.load) + [(in module marshal)](library/marshal#marshal.load) + [(in module pickle)](library/pickle#pickle.load) + [(in module plistlib)](library/plistlib#plistlib.load) + [(pickle.Unpickler method)](library/pickle#pickle.Unpickler.load) + [(tracemalloc.Snapshot class method)](library/tracemalloc#tracemalloc.Snapshot.load) * [LOAD\_ASSERTION\_ERROR (opcode)](library/dis#opcode-LOAD_ASSERTION_ERROR) * [LOAD\_ATTR (opcode)](library/dis#opcode-LOAD_ATTR) * [LOAD\_BUILD\_CLASS (opcode)](library/dis#opcode-LOAD_BUILD_CLASS) * [load\_cert\_chain() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.load_cert_chain) * [LOAD\_CLASSDEREF (opcode)](library/dis#opcode-LOAD_CLASSDEREF) * [LOAD\_CLOSURE (opcode)](library/dis#opcode-LOAD_CLOSURE) * [LOAD\_CONST (opcode)](library/dis#opcode-LOAD_CONST) * [load\_default\_certs() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.load_default_certs) * [LOAD\_DEREF (opcode)](library/dis#opcode-LOAD_DEREF) * [load\_dh\_params() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.load_dh_params) * [load\_extension() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.load_extension) * [LOAD\_FAST (opcode)](library/dis#opcode-LOAD_FAST) * [LOAD\_GLOBAL (opcode)](library/dis#opcode-LOAD_GLOBAL) * [LOAD\_METHOD (opcode)](library/dis#opcode-LOAD_METHOD) * [load\_module() (importlib.abc.FileLoader method)](library/importlib#importlib.abc.FileLoader.load_module) + [(importlib.abc.InspectLoader method)](library/importlib#importlib.abc.InspectLoader.load_module) + [(importlib.abc.Loader method)](library/importlib#importlib.abc.Loader.load_module) + [(importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.load_module) + [(importlib.machinery.SourceFileLoader method)](library/importlib#importlib.machinery.SourceFileLoader.load_module) + [(importlib.machinery.SourcelessFileLoader method)](library/importlib#importlib.machinery.SourcelessFileLoader.load_module) + [(in module imp)](library/imp#imp.load_module) + [(zipimport.zipimporter method)](library/zipimport#zipimport.zipimporter.load_module) * [LOAD\_NAME (opcode)](library/dis#opcode-LOAD_NAME) * [load\_package\_tests() (in module test.support)](library/test#test.support.load_package_tests) * [load\_verify\_locations() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.load_verify_locations) * [loader](reference/import#index-8), [**[1]**](glossary#term-loader) * [Loader (class in importlib.abc)](library/importlib#importlib.abc.Loader) * [loader (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.loader) * [loader\_state (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.loader_state) * [LoadError](library/http.cookiejar#http.cookiejar.LoadError) * [LoadFileDialog (class in tkinter.filedialog)](library/dialog#tkinter.filedialog.LoadFileDialog) * [LoadKey() (in module winreg)](library/winreg#winreg.LoadKey) * [LoadLibrary() (ctypes.LibraryLoader method)](library/ctypes#ctypes.LibraryLoader.LoadLibrary) * [loads() (in module json)](library/json#json.loads) + [(in module marshal)](library/marshal#marshal.loads) + [(in module pickle)](library/pickle#pickle.loads) + [(in module plistlib)](library/plistlib#plistlib.loads) + [(in module xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.loads) * [loadTestsFromModule() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.loadTestsFromModule) * [loadTestsFromName() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.loadTestsFromName) * [loadTestsFromNames() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.loadTestsFromNames) * [loadTestsFromTestCase() (unittest.TestLoader method)](library/unittest#unittest.TestLoader.loadTestsFromTestCase) * [local (class in threading)](library/threading#threading.local) * [localcontext() (in module decimal)](library/decimal#decimal.localcontext) * [LOCALE (in module re)](library/re#re.LOCALE) * [locale (module)](library/locale#module-locale) * [localeconv() (in module locale)](library/locale#locale.localeconv) * [LocaleHTMLCalendar (class in calendar)](library/calendar#calendar.LocaleHTMLCalendar) * [LocaleTextCalendar (class in calendar)](library/calendar#calendar.LocaleTextCalendar) * [localName (xml.dom.Attr attribute)](library/xml.dom#xml.dom.Attr.localName) + [(xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.localName) * [locals() (built-in function)](library/functions#locals) * [localtime() (in module email.utils)](library/email.utils#email.utils.localtime) + [(in module time)](library/time#time.localtime) * [Locator (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.Locator) * [Lock (class in asyncio)](library/asyncio-sync#asyncio.Lock) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.Lock) + [(class in threading)](library/threading#threading.Lock) * [lock() (mailbox.Babyl method)](library/mailbox#mailbox.Babyl.lock) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.lock) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.lock) + [(mailbox.mbox method)](library/mailbox#mailbox.mbox.lock) + [(mailbox.MH method)](library/mailbox#mailbox.MH.lock) + [(mailbox.MMDF method)](library/mailbox#mailbox.MMDF.lock) * [Lock() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Lock) * [lock, interpreter](c-api/init#index-33) * [lock\_held() (in module imp)](library/imp#imp.lock_held) * [locked() (\_thread.lock method)](library/_thread#_thread.lock.locked) + [(asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.locked) + [(asyncio.Lock method)](library/asyncio-sync#asyncio.Lock.locked) + [(asyncio.Semaphore method)](library/asyncio-sync#asyncio.Semaphore.locked) + [(threading.Lock method)](library/threading#threading.Lock.locked) * [lockf() (in module fcntl)](library/fcntl#fcntl.lockf) + [(in module os)](library/os#os.lockf) * [locking() (in module msvcrt)](library/msvcrt#msvcrt.locking) * [LockType (in module \_thread)](library/_thread#_thread.LockType) * [log() (in module cmath)](library/cmath#cmath.log) + [(in module logging)](library/logging#logging.log) + [(in module math)](library/math#math.log) + [(logging.Logger method)](library/logging#logging.Logger.log) * [log10() (decimal.Context method)](library/decimal#decimal.Context.log10) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.log10) + [(in module cmath)](library/cmath#cmath.log10) + [(in module math)](library/math#math.log10) * [log1p() (in module math)](library/math#math.log1p) * [log2() (in module math)](library/math#math.log2) * [log\_date\_time\_string() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.log_date_time_string) * [log\_error() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.log_error) * [log\_exception() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.log_exception) * [log\_message() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.log_message) * [log\_request() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.log_request) * [log\_to\_stderr() (in module multiprocessing)](library/multiprocessing#multiprocessing.log_to_stderr) * [logb() (decimal.Context method)](library/decimal#decimal.Context.logb) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.logb) * [Logger (class in logging)](library/logging#logging.Logger) * [LoggerAdapter (class in logging)](library/logging#logging.LoggerAdapter) * logging + [Errors](library/logging#index-0) * [logging (module)](library/logging#module-logging) * [logging.config (module)](library/logging.config#module-logging.config) * [logging.handlers (module)](library/logging.handlers#module-logging.handlers) * [logical line](reference/lexical_analysis#index-3) * [logical\_and() (decimal.Context method)](library/decimal#decimal.Context.logical_and) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.logical_and) * [logical\_invert() (decimal.Context method)](library/decimal#decimal.Context.logical_invert) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.logical_invert) * [logical\_or() (decimal.Context method)](library/decimal#decimal.Context.logical_or) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.logical_or) * [logical\_xor() (decimal.Context method)](library/decimal#decimal.Context.logical_xor) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.logical_xor) * [login() (ftplib.FTP method)](library/ftplib#ftplib.FTP.login) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.login) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.login) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.login) * [login\_cram\_md5() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.login_cram_md5) * [LOGNAME](library/getpass#index-0), [[1]](library/os#index-4) * [lognormvariate() (in module random)](library/random#random.lognormvariate) * [logout() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.logout) * [LogRecord (class in logging)](library/logging#logging.LogRecord) * [long (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-long) * long integer + [object](c-api/long#index-0) * [LONG\_MAX](c-api/long#index-1) * [LONG\_TIMEOUT (in module test.support)](library/test#test.support.LONG_TIMEOUT) * [longMessage (unittest.TestCase attribute)](library/unittest#unittest.TestCase.longMessage) * [longname() (in module curses)](library/curses#curses.longname) * [lookup() (in module codecs)](library/codecs#codecs.lookup) + [(in module unicodedata)](library/unicodedata#unicodedata.lookup) + [(symtable.SymbolTable method)](library/symtable#symtable.SymbolTable.lookup) + [(tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.lookup) * [lookup\_error() (in module codecs)](library/codecs#codecs.lookup_error) * [LookupError](library/exceptions#LookupError) * loop + [over mutable sequence](reference/compound_stmts#index-9) + [statement](reference/compound_stmts#index-4), [[1]](reference/compound_stmts#index-6), [[2]](reference/simple_stmts#index-30), [[3]](reference/simple_stmts#index-33) * loop control + [target](reference/simple_stmts#index-31) * [loop() (in module asyncore)](library/asyncore#asyncore.loop) * [LOOPBACK\_TIMEOUT (in module test.support)](library/test#test.support.LOOPBACK_TIMEOUT) * [lower() (bytearray method)](library/stdtypes#bytearray.lower) + [(bytes method)](library/stdtypes#bytes.lower) + [(str method)](library/stdtypes#str.lower) * [LPAR (in module token)](library/token#token.LPAR) * [lpAttributeList (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.lpAttributeList) * [lru\_cache() (in module functools)](library/functools#functools.lru_cache) * [lseek() (in module os)](library/os#os.lseek) * [LShift (class in ast)](library/ast#ast.LShift) * [lshift() (in module operator)](library/operator#operator.lshift) * [LSQB (in module token)](library/token#token.LSQB) * [lstat() (in module os)](library/os#os.lstat) + [(pathlib.Path method)](library/pathlib#pathlib.Path.lstat) * [lstrip() (bytearray method)](library/stdtypes#bytearray.lstrip) + [(bytes method)](library/stdtypes#bytes.lstrip) + [(str method)](library/stdtypes#str.lstrip) * [lsub() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.lsub) * [Lt (class in ast)](library/ast#ast.Lt) * [lt() (in module operator)](library/operator#operator.lt) + [(in module turtle)](library/turtle#turtle.lt) * [LtE (class in ast)](library/ast#ast.LtE) * [LWPCookieJar (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.LWPCookieJar) * [lzma (module)](library/lzma#module-lzma) * [LZMACompressor (class in lzma)](library/lzma#lzma.LZMACompressor) * [LZMADecompressor (class in lzma)](library/lzma#lzma.LZMADecompressor) * [LZMAError](library/lzma#lzma.LZMAError) * [LZMAFile (class in lzma)](library/lzma#lzma.LZMAFile) | M - | | | | --- | --- | | * [M (in module re)](library/re#re.M) * [mac\_ver() (in module platform)](library/platform#platform.mac_ver) * [machine() (in module platform)](library/platform#platform.machine) * [macros (netrc.netrc attribute)](library/netrc#netrc.netrc.macros) * [MADV\_AUTOSYNC (in module mmap)](library/mmap#mmap.MADV_AUTOSYNC) * [MADV\_CORE (in module mmap)](library/mmap#mmap.MADV_CORE) * [MADV\_DODUMP (in module mmap)](library/mmap#mmap.MADV_DODUMP) * [MADV\_DOFORK (in module mmap)](library/mmap#mmap.MADV_DOFORK) * [MADV\_DONTDUMP (in module mmap)](library/mmap#mmap.MADV_DONTDUMP) * [MADV\_DONTFORK (in module mmap)](library/mmap#mmap.MADV_DONTFORK) * [MADV\_DONTNEED (in module mmap)](library/mmap#mmap.MADV_DONTNEED) * [MADV\_FREE (in module mmap)](library/mmap#mmap.MADV_FREE) * [MADV\_HUGEPAGE (in module mmap)](library/mmap#mmap.MADV_HUGEPAGE) * [MADV\_HWPOISON (in module mmap)](library/mmap#mmap.MADV_HWPOISON) * [MADV\_MERGEABLE (in module mmap)](library/mmap#mmap.MADV_MERGEABLE) * [MADV\_NOCORE (in module mmap)](library/mmap#mmap.MADV_NOCORE) * [MADV\_NOHUGEPAGE (in module mmap)](library/mmap#mmap.MADV_NOHUGEPAGE) * [MADV\_NORMAL (in module mmap)](library/mmap#mmap.MADV_NORMAL) * [MADV\_NOSYNC (in module mmap)](library/mmap#mmap.MADV_NOSYNC) * [MADV\_PROTECT (in module mmap)](library/mmap#mmap.MADV_PROTECT) * [MADV\_RANDOM (in module mmap)](library/mmap#mmap.MADV_RANDOM) * [MADV\_REMOVE (in module mmap)](library/mmap#mmap.MADV_REMOVE) * [MADV\_SEQUENTIAL (in module mmap)](library/mmap#mmap.MADV_SEQUENTIAL) * [MADV\_SOFT\_OFFLINE (in module mmap)](library/mmap#mmap.MADV_SOFT_OFFLINE) * [MADV\_UNMERGEABLE (in module mmap)](library/mmap#mmap.MADV_UNMERGEABLE) * [MADV\_WILLNEED (in module mmap)](library/mmap#mmap.MADV_WILLNEED) * [madvise() (mmap.mmap method)](library/mmap#mmap.mmap.madvise) * magic + [method](glossary#index-26) * [**magic method**](glossary#term-magic-method) * [MAGIC\_NUMBER (in module importlib.util)](library/importlib#importlib.util.MAGIC_NUMBER) * [MagicMock (class in unittest.mock)](library/unittest.mock#unittest.mock.MagicMock) * [Mailbox (class in mailbox)](library/mailbox#mailbox.Mailbox) * [mailbox (module)](library/mailbox#module-mailbox) * [mailcap (module)](library/mailcap#module-mailcap) * [Maildir (class in mailbox)](library/mailbox#mailbox.Maildir) * [MaildirMessage (class in mailbox)](library/mailbox#mailbox.MaildirMessage) * [mailfrom (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.mailfrom) * [MailmanProxy (class in smtpd)](library/smtpd#smtpd.MailmanProxy) * [main()](c-api/init#index-17), [[1]](c-api/init#index-20), [[2]](c-api/init#index-30) + [(in module py\_compile)](library/py_compile#py_compile.main) + [(in module site)](library/site#site.main) + [(in module unittest)](library/unittest#unittest.main) * [main\_thread() (in module threading)](library/threading#threading.main_thread) * [mainloop() (in module turtle)](library/turtle#turtle.mainloop) * [maintype (email.headerregistry.ContentTypeHeader attribute)](library/email.headerregistry#email.headerregistry.ContentTypeHeader.maintype) * [major (email.headerregistry.MIMEVersionHeader attribute)](library/email.headerregistry#email.headerregistry.MIMEVersionHeader.major) * [major() (in module os)](library/os#os.major) * [make\_alternative() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.make_alternative) * [make\_archive() (in module distutils.archive\_util)](distutils/apiref#distutils.archive_util.make_archive) + [(in module shutil)](library/shutil#shutil.make_archive) * [make\_bad\_fd() (in module test.support)](library/test#test.support.make_bad_fd) * [make\_cookies() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.make_cookies) * [make\_dataclass() (in module dataclasses)](library/dataclasses#dataclasses.make_dataclass) * [make\_file() (difflib.HtmlDiff method)](library/difflib#difflib.HtmlDiff.make_file) * [MAKE\_FUNCTION (opcode)](library/dis#opcode-MAKE_FUNCTION) * [make\_header() (in module email.header)](library/email.header#email.header.make_header) * [make\_legacy\_pyc() (in module test.support)](library/test#test.support.make_legacy_pyc) * [make\_mixed() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.make_mixed) * [make\_msgid() (in module email.utils)](library/email.utils#email.utils.make_msgid) * [make\_parser() (in module xml.sax)](library/xml.sax#xml.sax.make_parser) * [make\_pkg() (in module test.support.script\_helper)](library/test#test.support.script_helper.make_pkg) * [make\_related() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.make_related) * [make\_script() (in module test.support.script\_helper)](library/test#test.support.script_helper.make_script) * [make\_server() (in module wsgiref.simple\_server)](library/wsgiref#wsgiref.simple_server.make_server) * [make\_table() (difflib.HtmlDiff method)](library/difflib#difflib.HtmlDiff.make_table) * [make\_tarball() (in module distutils.archive\_util)](distutils/apiref#distutils.archive_util.make_tarball) * [make\_zip\_pkg() (in module test.support.script\_helper)](library/test#test.support.script_helper.make_zip_pkg) * [make\_zip\_script() (in module test.support.script\_helper)](library/test#test.support.script_helper.make_zip_script) * [make\_zipfile() (in module distutils.archive\_util)](distutils/apiref#distutils.archive_util.make_zipfile) * [makedev() (in module os)](library/os#os.makedev) * [makedirs() (in module os)](library/os#os.makedirs) * [makeelement() (xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.makeelement) * [makefile() (socket method)](reference/datamodel#index-53) + [(socket.socket method)](library/socket#socket.socket.makefile) * [makeLogRecord() (in module logging)](library/logging#logging.makeLogRecord) * [makePickle() (logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.makePickle) * [makeRecord() (logging.Logger method)](library/logging#logging.Logger.makeRecord) * [makeSocket() (logging.handlers.DatagramHandler method)](library/logging.handlers#logging.handlers.DatagramHandler.makeSocket) + [(logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.makeSocket) * [maketrans() (bytearray static method)](library/stdtypes#bytearray.maketrans) + [(bytes static method)](library/stdtypes#bytes.maketrans) + [(str static method)](library/stdtypes#str.maketrans) * [malloc()](c-api/memory#index-0) * [mangle\_from\_ (email.policy.Compat32 attribute)](library/email.policy#email.policy.Compat32.mangle_from_) + [(email.policy.Policy attribute)](library/email.policy#email.policy.Policy.mangle_from_) * mangling + [name](reference/expressions#index-5), [[1]](tutorial/classes#index-1) * [map (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-map) * [map() (built-in function)](library/functions#map) + [(concurrent.futures.Executor method)](library/concurrent.futures#concurrent.futures.Executor.map) + [(multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.map) + [(tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.map) * [MAP\_ADD (opcode)](library/dis#opcode-MAP_ADD) * [map\_async() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.map_async) * [map\_table\_b2() (in module stringprep)](library/stringprep#stringprep.map_table_b2) * [map\_table\_b3() (in module stringprep)](library/stringprep#stringprep.map_table_b3) * [map\_to\_type() (email.headerregistry.HeaderRegistry method)](library/email.headerregistry#email.headerregistry.HeaderRegistry.map_to_type) * [mapLogRecord() (logging.handlers.HTTPHandler method)](library/logging.handlers#logging.handlers.HTTPHandler.mapLogRecord) * [**mapping**](glossary#term-mapping) + [object](c-api/concrete#index-2), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-29), [[3]](reference/datamodel#index-51), [[4]](reference/expressions#index-42), [[5]](reference/simple_stmts#index-11) + [types, operations on](library/stdtypes#index-50) * [Mapping (class in collections.abc)](library/collections.abc#collections.abc.Mapping) + [(class in typing)](library/typing#typing.Mapping) * [mapping() (msilib.Control method)](library/msilib#msilib.Control.mapping) * [MappingProxyType (class in types)](library/types#types.MappingProxyType) * [MappingView (class in collections.abc)](library/collections.abc#collections.abc.MappingView) + [(class in typing)](library/typing#typing.MappingView) * [mapPriority() (logging.handlers.SysLogHandler method)](library/logging.handlers#logging.handlers.SysLogHandler.mapPriority) * [maps (collections.ChainMap attribute)](library/collections#collections.ChainMap.maps) * [maps() (in module nis)](library/nis#nis.maps) * [marshal (module)](library/marshal#module-marshal) * marshalling + [objects](library/pickle#index-0) * masking + [operations](library/stdtypes#index-16) * [master (tkinter.Tk attribute)](library/tkinter#tkinter.Tk.master) * [Match (class in typing)](library/typing#typing.Match) * [match() (in module nis)](library/nis#nis.match) + [(in module re)](library/re#re.match) + [(pathlib.PurePath method)](library/pathlib#pathlib.PurePath.match) + [(re.Pattern method)](library/re#re.Pattern.match) * [match\_hostname() (in module ssl)](library/ssl#ssl.match_hostname) * [match\_test() (in module test.support)](library/test#test.support.match_test) * [match\_value() (test.support.Matcher method)](library/test#test.support.Matcher.match_value) * [Matcher (class in test.support)](library/test#test.support.Matcher) * [matches() (test.support.Matcher method)](library/test#test.support.Matcher.matches) * math + [module](library/cmath#index-1), [[1]](library/stdtypes#index-15) * [math (module)](library/math#module-math) * [matmul() (in module operator)](library/operator#operator.matmul) * [MatMult (class in ast)](library/ast#ast.MatMult) * [matrix multiplication](reference/expressions#index-66) * max + [built-in function](library/stdtypes#index-19) * [max (datetime.date attribute)](library/datetime#datetime.date.max) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.max) + [(datetime.time attribute)](library/datetime#datetime.time.max) + [(datetime.timedelta attribute)](library/datetime#datetime.timedelta.max) * [max() (built-in function)](library/functions#max) + [(decimal.Context method)](library/decimal#decimal.Context.max) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.max) + [(in module audioop)](library/audioop#audioop.max) * [max\_count (email.headerregistry.BaseHeader attribute)](library/email.headerregistry#email.headerregistry.BaseHeader.max_count) * [MAX\_EMAX (in module decimal)](library/decimal#decimal.MAX_EMAX) * [MAX\_INTERPOLATION\_DEPTH (in module configparser)](library/configparser#configparser.MAX_INTERPOLATION_DEPTH) * [max\_line\_length (email.policy.Policy attribute)](library/email.policy#email.policy.Policy.max_line_length) * [max\_lines (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.max_lines) * [max\_mag() (decimal.Context method)](library/decimal#decimal.Context.max_mag) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.max_mag) * [max\_memuse (in module test.support)](library/test#test.support.max_memuse) * [MAX\_PREC (in module decimal)](library/decimal#decimal.MAX_PREC) * [max\_prefixlen (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.max_prefixlen) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.max_prefixlen) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.max_prefixlen) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.max_prefixlen) * [MAX\_Py\_ssize\_t (in module test.support)](library/test#test.support.MAX_Py_ssize_t) * [maxarray (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxarray) * [maxdeque (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxdeque) * [maxdict (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxdict) * [maxDiff (unittest.TestCase attribute)](library/unittest#unittest.TestCase.maxDiff) * [maxfrozenset (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxfrozenset) * [MAXIMUM\_SUPPORTED (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.MAXIMUM_SUPPORTED) * [maximum\_version (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.maximum_version) * [maxlen (collections.deque attribute)](library/collections#collections.deque.maxlen) * [maxlevel (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxlevel) * [maxlist (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxlist) * [maxlong (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxlong) * [maxother (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxother) * [maxpp() (in module audioop)](library/audioop#audioop.maxpp) * [maxset (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxset) * [maxsize (asyncio.Queue attribute)](library/asyncio-queue#asyncio.Queue.maxsize) + [(in module sys)](library/sys#sys.maxsize) * [maxstring (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxstring) * [maxtuple (reprlib.Repr attribute)](library/reprlib#reprlib.Repr.maxtuple) * [maxunicode (in module sys)](library/sys#sys.maxunicode) * [MAXYEAR (in module datetime)](library/datetime#datetime.MAXYEAR) * [MB\_ICONASTERISK (in module winsound)](library/winsound#winsound.MB_ICONASTERISK) * [MB\_ICONEXCLAMATION (in module winsound)](library/winsound#winsound.MB_ICONEXCLAMATION) * [MB\_ICONHAND (in module winsound)](library/winsound#winsound.MB_ICONHAND) * [MB\_ICONQUESTION (in module winsound)](library/winsound#winsound.MB_ICONQUESTION) * [MB\_OK (in module winsound)](library/winsound#winsound.MB_OK) * [mbox (class in mailbox)](library/mailbox#mailbox.mbox) * [mboxMessage (class in mailbox)](library/mailbox#mailbox.mboxMessage) * [mean (statistics.NormalDist attribute)](library/statistics#statistics.NormalDist.mean) * [mean() (in module statistics)](library/statistics#statistics.mean) * [measure() (tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.measure) * [median (statistics.NormalDist attribute)](library/statistics#statistics.NormalDist.median) * [median() (in module statistics)](library/statistics#statistics.median) * [median\_grouped() (in module statistics)](library/statistics#statistics.median_grouped) * [median\_high() (in module statistics)](library/statistics#statistics.median_high) * [median\_low() (in module statistics)](library/statistics#statistics.median_low) * [MemberDescriptorType (in module types)](library/types#types.MemberDescriptorType) * membership + [test](reference/expressions#index-80) * [memfd\_create() (in module os)](library/os#os.memfd_create) * [memmove() (in module ctypes)](library/ctypes#ctypes.memmove) * [MemoryBIO (class in ssl)](library/ssl#ssl.MemoryBIO) * [MemoryError](library/exceptions#MemoryError) * [MemoryHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.MemoryHandler) * memoryview + [object](c-api/memoryview#index-0), [[1]](library/stdtypes#index-38) * [memoryview (built-in class)](library/stdtypes#memoryview) * [memset() (in module ctypes)](library/ctypes#ctypes.memset) * [merge() (in module heapq)](library/heapq#heapq.merge) * [Message (class in email.message)](library/email.compat32-message#email.message.Message) + [(class in mailbox)](library/mailbox#mailbox.Message) + [(class in tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.Message) * [message digest, MD5](library/hashlib#index-0) * [message\_factory (email.policy.Policy attribute)](library/email.policy#email.policy.Policy.message_factory) * [message\_from\_binary\_file() (in module email)](library/email.parser#email.message_from_binary_file) * [message\_from\_bytes() (in module email)](library/email.parser#email.message_from_bytes) * [message\_from\_file() (in module email)](library/email.parser#email.message_from_file) * [message\_from\_string() (in module email)](library/email.parser#email.message_from_string) * [MessageBeep() (in module winsound)](library/winsound#winsound.MessageBeep) * [MessageClass (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.MessageClass) * [MessageError](library/email.errors#email.errors.MessageError) * [MessageParseError](library/email.errors#email.errors.MessageParseError) * [messages (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.messages) * meta + [hooks](reference/import#index-9) * [meta hooks](reference/import#index-9) * [**meta path finder**](glossary#term-meta-path-finder) * [meta() (in module curses)](library/curses#curses.meta) * [meta\_path (in module sys)](library/sys#sys.meta_path) * [metaclass](reference/datamodel#index-82), [**[1]**](glossary#term-metaclass) + [(2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-metaclass) * [metaclass hint](reference/datamodel#index-84) * [MetaPathFinder (class in importlib.abc)](library/importlib#importlib.abc.MetaPathFinder) * [metavar (optparse.Option attribute)](library/optparse#optparse.Option.metavar) * [MetavarTypeHelpFormatter (class in argparse)](library/argparse#argparse.MetavarTypeHelpFormatter) * [Meter (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Meter) * [METH\_CLASS (built-in variable)](c-api/structures#METH_CLASS) * [METH\_COEXIST (built-in variable)](c-api/structures#METH_COEXIST) * [METH\_FASTCALL (built-in variable)](c-api/structures#METH_FASTCALL) * [METH\_NOARGS (built-in variable)](c-api/structures#METH_NOARGS) * [METH\_O (built-in variable)](c-api/structures#METH_O) * [METH\_STATIC (built-in variable)](c-api/structures#METH_STATIC) * [METH\_VARARGS (built-in variable)](c-api/structures#METH_VARARGS) * [**method**](glossary#term-method) + [built-in](reference/datamodel#index-41) + [call](reference/expressions#index-53) + [magic](glossary#index-26) + [object](c-api/method#index-1), [[1]](library/stdtypes#index-56), [[2]](reference/datamodel#index-35), [[3]](reference/datamodel#index-41), [[4]](reference/expressions#index-53), [[5]](tutorial/classes#index-0) + [special](glossary#index-34) + [user-defined](reference/datamodel#index-35) * [method (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.method) * [**method resolution order**](glossary#term-method-resolution-order) * [METHOD\_BLOWFISH (in module crypt)](library/crypt#crypt.METHOD_BLOWFISH) * [method\_calls (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.method_calls) * [METHOD\_CRYPT (in module crypt)](library/crypt#crypt.METHOD_CRYPT) * [METHOD\_MD5 (in module crypt)](library/crypt#crypt.METHOD_MD5) * [METHOD\_SHA256 (in module crypt)](library/crypt#crypt.METHOD_SHA256) * [METHOD\_SHA512 (in module crypt)](library/crypt#crypt.METHOD_SHA512) * [methodattrs (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-methodattrs) | * [methodcaller() (in module operator)](library/operator#operator.methodcaller) * [MethodDescriptorType (in module types)](library/types#types.MethodDescriptorType) * [methodHelp() (xmlrpc.client.ServerProxy.system method)](library/xmlrpc.client#xmlrpc.client.ServerProxy.system.methodHelp) * methods + [bytearray](library/stdtypes#index-41) + [bytes](library/stdtypes#index-41) + [string](library/stdtypes#index-30) * [methods (in module crypt)](library/crypt#crypt.methods) + [(pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.methods) * [methodSignature() (xmlrpc.client.ServerProxy.system method)](library/xmlrpc.client#xmlrpc.client.ServerProxy.system.methodSignature) * [MethodType (in module types)](c-api/function#index-1), [[1]](c-api/method#index-2), [[2]](library/types#types.MethodType) * [MethodWrapperType (in module types)](library/types#types.MethodWrapperType) * [metrics() (tkinter.font.Font method)](library/tkinter.font#tkinter.font.Font.metrics) * [MFD\_ALLOW\_SEALING (in module os)](library/os#os.MFD_ALLOW_SEALING) * [MFD\_CLOEXEC (in module os)](library/os#os.MFD_CLOEXEC) * [MFD\_HUGE\_16GB (in module os)](library/os#os.MFD_HUGE_16GB) * [MFD\_HUGE\_16MB (in module os)](library/os#os.MFD_HUGE_16MB) * [MFD\_HUGE\_1GB (in module os)](library/os#os.MFD_HUGE_1GB) * [MFD\_HUGE\_1MB (in module os)](library/os#os.MFD_HUGE_1MB) * [MFD\_HUGE\_256MB (in module os)](library/os#os.MFD_HUGE_256MB) * [MFD\_HUGE\_2GB (in module os)](library/os#os.MFD_HUGE_2GB) * [MFD\_HUGE\_2MB (in module os)](library/os#os.MFD_HUGE_2MB) * [MFD\_HUGE\_32MB (in module os)](library/os#os.MFD_HUGE_32MB) * [MFD\_HUGE\_512KB (in module os)](library/os#os.MFD_HUGE_512KB) * [MFD\_HUGE\_512MB (in module os)](library/os#os.MFD_HUGE_512MB) * [MFD\_HUGE\_64KB (in module os)](library/os#os.MFD_HUGE_64KB) * [MFD\_HUGE\_8MB (in module os)](library/os#os.MFD_HUGE_8MB) * [MFD\_HUGE\_MASK (in module os)](library/os#os.MFD_HUGE_MASK) * [MFD\_HUGE\_SHIFT (in module os)](library/os#os.MFD_HUGE_SHIFT) * [MFD\_HUGETLB (in module os)](library/os#os.MFD_HUGETLB) * [MH (class in mailbox)](library/mailbox#mailbox.MH) * [MHMessage (class in mailbox)](library/mailbox#mailbox.MHMessage) * [microsecond (datetime.datetime attribute)](library/datetime#datetime.datetime.microsecond) + [(datetime.time attribute)](library/datetime#datetime.time.microsecond) * MIME + [base64 encoding](library/base64#index-0) + [content type](library/mimetypes#index-0) + [headers](library/cgi#index-0), [[1]](library/mimetypes#index-1) + [quoted-printable encoding](library/quopri#index-0) * [MIMEApplication (class in email.mime.application)](library/email.mime#email.mime.application.MIMEApplication) * [MIMEAudio (class in email.mime.audio)](library/email.mime#email.mime.audio.MIMEAudio) * [MIMEBase (class in email.mime.base)](library/email.mime#email.mime.base.MIMEBase) * [MIMEImage (class in email.mime.image)](library/email.mime#email.mime.image.MIMEImage) * [MIMEMessage (class in email.mime.message)](library/email.mime#email.mime.message.MIMEMessage) * [MIMEMultipart (class in email.mime.multipart)](library/email.mime#email.mime.multipart.MIMEMultipart) * [MIMENonMultipart (class in email.mime.nonmultipart)](library/email.mime#email.mime.nonmultipart.MIMENonMultipart) * [MIMEPart (class in email.message)](library/email.message#email.message.MIMEPart) * [MIMEText (class in email.mime.text)](library/email.mime#email.mime.text.MIMEText) * [MimeTypes (class in mimetypes)](library/mimetypes#mimetypes.MimeTypes) * [mimetypes (module)](library/mimetypes#module-mimetypes) * [MIMEVersionHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.MIMEVersionHeader) * min + [built-in function](library/stdtypes#index-19) * [min (datetime.date attribute)](library/datetime#datetime.date.min) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.min) + [(datetime.time attribute)](library/datetime#datetime.time.min) + [(datetime.timedelta attribute)](library/datetime#datetime.timedelta.min) * [min() (built-in function)](library/functions#min) + [(decimal.Context method)](library/decimal#decimal.Context.min) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.min) * [MIN\_EMIN (in module decimal)](library/decimal#decimal.MIN_EMIN) * [MIN\_ETINY (in module decimal)](library/decimal#decimal.MIN_ETINY) * [min\_mag() (decimal.Context method)](library/decimal#decimal.Context.min_mag) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.min_mag) * [MINEQUAL (in module token)](library/token#token.MINEQUAL) * [MINIMUM\_SUPPORTED (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.MINIMUM_SUPPORTED) * [minimum\_version (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.minimum_version) * [minmax() (in module audioop)](library/audioop#audioop.minmax) * [minor (email.headerregistry.MIMEVersionHeader attribute)](library/email.headerregistry#email.headerregistry.MIMEVersionHeader.minor) * [minor() (in module os)](library/os#os.minor) * [minus](reference/expressions#index-60) * [MINUS (in module token)](library/token#token.MINUS) * [minus() (decimal.Context method)](library/decimal#decimal.Context.minus) * [minute (datetime.datetime attribute)](library/datetime#datetime.datetime.minute) + [(datetime.time attribute)](library/datetime#datetime.time.minute) * [MINYEAR (in module datetime)](library/datetime#datetime.MINYEAR) * [mirrored() (in module unicodedata)](library/unicodedata#unicodedata.mirrored) * [misc\_header (cmd.Cmd attribute)](library/cmd#cmd.Cmd.misc_header) * [MISSING (contextvars.Token attribute)](library/contextvars#contextvars.Token.MISSING) * [MISSING\_C\_DOCSTRINGS (in module test.support)](library/test#test.support.MISSING_C_DOCSTRINGS) * [missing\_compiler\_executable() (in module test.support)](library/test#test.support.missing_compiler_executable) * [MissingSectionHeaderError](library/configparser#configparser.MissingSectionHeaderError) * [MIXERDEV](library/ossaudiodev#index-2) * [mkd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.mkd) * [mkdir() (in module os)](library/os#os.mkdir) + [(pathlib.Path method)](library/pathlib#pathlib.Path.mkdir) * [mkdtemp() (in module tempfile)](library/tempfile#tempfile.mkdtemp) * [mkfifo() (in module os)](library/os#os.mkfifo) * [mknod() (in module os)](library/os#os.mknod) * [mkpath() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.mkpath) + [(in module distutils.dir\_util)](distutils/apiref#distutils.dir_util.mkpath) * [mksalt() (in module crypt)](library/crypt#crypt.mksalt) * [mkstemp() (in module tempfile)](library/tempfile#tempfile.mkstemp) * [mktemp() (in module tempfile)](library/tempfile#tempfile.mktemp) * [mktime() (in module time)](library/time#time.mktime) * [mktime\_tz() (in module email.utils)](library/email.utils#email.utils.mktime_tz) * [mlsd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.mlsd) * [mmap (class in mmap)](library/mmap#mmap.mmap) + [(module)](library/mmap#module-mmap) * [MMDF (class in mailbox)](library/mailbox#mailbox.MMDF) * [MMDFMessage (class in mailbox)](library/mailbox#mailbox.MMDFMessage) * [Mock (class in unittest.mock)](library/unittest.mock#unittest.mock.Mock) * [mock\_add\_spec() (unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.mock_add_spec) * [mock\_calls (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.mock_calls) * [mock\_open() (in module unittest.mock)](library/unittest.mock#unittest.mock.mock_open) * [Mod (class in ast)](library/ast#ast.Mod) * [mod() (in module operator)](library/operator#operator.mod) * [mode (io.FileIO attribute)](library/io#io.FileIO.mode) + [(ossaudiodev.oss\_audio\_device attribute)](library/ossaudiodev#ossaudiodev.oss_audio_device.mode) + [(statistics.NormalDist attribute)](library/statistics#statistics.NormalDist.mode) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.mode) * [mode() (in module statistics)](library/statistics#statistics.mode) + [(in module turtle)](library/turtle#turtle.mode) * modes + [file](library/functions#index-5) * [modf() (in module math)](library/math#math.modf) * [modified() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.modified) * [Modify() (msilib.View method)](library/msilib#msilib.View.Modify) * [modify() (select.devpoll method)](library/select#select.devpoll.modify) + [(select.epoll method)](library/select#select.epoll.modify) + [(select.poll method)](library/select#select.poll.modify) + [(selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.modify) * [**module**](glossary#term-module) + [\_\_main\_\_](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](library/runpy#index-0), [[4]](library/runpy#index-4), [[5]](reference/executionmodel#index-10), [[6]](reference/toplevel_components#index-2), [[7]](reference/toplevel_components#index-3) + [\_locale](library/locale#index-0) + [\_thread](c-api/init#index-39) + [array](library/stdtypes#index-38), [[1]](reference/datamodel#index-25) + [base64](library/binascii#index-0) + [bdb](library/pdb#index-1) + [binhex](library/binascii#index-0) + [builtins](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](reference/toplevel_components#index-2), [[4]](tutorial/modules#index-7) + [cmd](library/pdb#index-1) + [copy](library/copyreg#index-0) + [crypt](library/pwd#index-0) + [dbm.gnu](library/shelve#index-1), [[1]](reference/datamodel#index-31) + [dbm.ndbm](library/shelve#index-1), [[1]](reference/datamodel#index-31) + [errno](library/exceptions#index-3) + [extension](reference/datamodel#index-4) + [glob](library/fnmatch#index-3) + [imp](library/functions#index-12) + [importing](reference/simple_stmts#index-34) + [io](reference/datamodel#index-53) + [json](tutorial/inputoutput#index-1) + [math](library/cmath#index-1), [[1]](library/stdtypes#index-15) + [namespace](reference/datamodel#index-43) + [object](c-api/module#index-0), [[1]](reference/datamodel#index-42), [[2]](reference/expressions#index-40) + [os](library/posix#index-0) + [pickle](library/copy#index-0), [[1]](library/copyreg#index-0), [[2]](library/marshal#index-0), [[3]](library/shelve#index-0) + [pty](library/os#index-17) + [pwd](library/os.path#index-2) + [pyexpat](library/pyexpat#index-1) + [re](library/fnmatch#index-1), [[1]](library/stdtypes#index-31) + [search path](c-api/init#index-16), [[1]](c-api/init#index-23), [[2]](c-api/init#index-24), [[3]](c-api/intro#index-23), [[4]](library/linecache#index-0), [[5]](library/site#index-0), [[6]](library/sys#index-21), [[7]](tutorial/modules#index-0) + [shelve](library/marshal#index-0) + [signal](c-api/exceptions#index-1), [[1]](library/_thread#index-2) + [sitecustomize](library/site#index-5) + [socket](library/internet#index-1) + [stat](library/os#index-24) + [string](library/locale#index-6) + [struct](library/socket#index-14) + [sys](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](library/functions#index-7), [[4]](reference/compound_stmts#index-12), [[5]](reference/toplevel_components#index-2), [[6]](tutorial/modules#index-4) + [types](library/stdtypes#index-60) + [urllib.request](library/http.client#index-1) + [usercustomize](library/site#index-6) + [uu](library/binascii#index-0) * [module (pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.module) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.module) * [module spec](reference/import#index-8), [**[1]**](glossary#term-module-spec) * [module\_for\_loader() (in module importlib.util)](library/importlib#importlib.util.module_for_loader) * [module\_from\_spec() (in module importlib.util)](library/importlib#importlib.util.module_from_spec) * [module\_repr() (importlib.abc.Loader method)](library/importlib#importlib.abc.Loader.module_repr) * [ModuleFinder (class in modulefinder)](library/modulefinder#modulefinder.ModuleFinder) * [modulefinder (module)](library/modulefinder#module-modulefinder) * [ModuleInfo (class in pkgutil)](library/pkgutil#pkgutil.ModuleInfo) * [ModuleNotFoundError](library/exceptions#ModuleNotFoundError) * [modules (in module sys)](c-api/import#index-0), [[1]](c-api/init#index-16), [[2]](library/sys#sys.modules) + [(modulefinder.ModuleFinder attribute)](library/modulefinder#modulefinder.ModuleFinder.modules) * [modules\_cleanup() (in module test.support)](library/test#test.support.modules_cleanup) * [modules\_setup() (in module test.support)](library/test#test.support.modules_setup) * [ModuleSpec (class in importlib.machinery)](library/importlib#importlib.machinery.ModuleSpec) * [ModuleType (class in types)](library/types#types.ModuleType) + [(in module types)](c-api/module#index-1) * [modulo](reference/expressions#index-68) * [monotonic() (in module time)](library/time#time.monotonic) * [monotonic\_ns() (in module time)](library/time#time.monotonic_ns) * [month (datetime.date attribute)](library/datetime#datetime.date.month) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.month) * [month() (in module calendar)](library/calendar#calendar.month) * [month\_abbr (in module calendar)](library/calendar#calendar.month_abbr) * [month\_name (in module calendar)](library/calendar#calendar.month_name) * [monthcalendar() (in module calendar)](library/calendar#calendar.monthcalendar) * [monthdatescalendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.monthdatescalendar) * [monthdays2calendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.monthdays2calendar) * [monthdayscalendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.monthdayscalendar) * [monthrange() (in module calendar)](library/calendar#calendar.monthrange) * [Morsel (class in http.cookies)](library/http.cookies#http.cookies.Morsel) * [most\_common() (collections.Counter method)](library/collections#collections.Counter.most_common) * [mouseinterval() (in module curses)](library/curses#curses.mouseinterval) * [mousemask() (in module curses)](library/curses#curses.mousemask) * [move() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.move) + [(curses.window method)](library/curses#curses.window.move) + [(in module shutil)](library/shutil#shutil.move) + [(mmap.mmap method)](library/mmap#mmap.mmap.move) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.move) * [move\_file() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.move_file) + [(in module distutils.file\_util)](distutils/apiref#distutils.file_util.move_file) * [move\_to\_end() (collections.OrderedDict method)](library/collections#collections.OrderedDict.move_to_end) * [MozillaCookieJar (class in http.cookiejar)](library/http.cookiejar#http.cookiejar.MozillaCookieJar) * [**MRO**](glossary#term-mro) * [mro() (class method)](library/stdtypes#class.mro) * [msg (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.msg) + [(json.JSONDecodeError attribute)](library/json#json.JSONDecodeError.msg) + [(re.error attribute)](library/re#re.error.msg) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.msg) * [msg() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.msg) * [msi](library/msilib#index-0) * [msilib (module)](library/msilib#module-msilib) * [msvcrt (module)](library/msvcrt#module-msvcrt) * [mt\_interact() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.mt_interact) * [mtime (gzip.GzipFile attribute)](library/gzip#gzip.GzipFile.mtime) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.mtime) * [mtime() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.mtime) * [mul() (in module audioop)](library/audioop#audioop.mul) + [(in module operator)](library/operator#operator.mul) * [Mult (class in ast)](library/ast#ast.Mult) * [MultiCall (class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.MultiCall) * [MULTILINE (in module re)](library/re#re.MULTILINE) * [MultiLoopChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.MultiLoopChildWatcher) * [multimode() (in module statistics)](library/statistics#statistics.multimode) * [MultipartConversionError](library/email.errors#email.errors.MultipartConversionError) * [multiplication](reference/expressions#index-65) * [multiply() (decimal.Context method)](library/decimal#decimal.Context.multiply) * [multiprocessing (module)](library/multiprocessing#module-multiprocessing) * [multiprocessing.connection (module)](library/multiprocessing#module-multiprocessing.connection) * [multiprocessing.dummy (module)](library/multiprocessing#module-multiprocessing.dummy) * [multiprocessing.Manager() (built-in function)](library/multiprocessing#multiprocessing.Manager) * [multiprocessing.managers (module)](library/multiprocessing#module-multiprocessing.managers) * [multiprocessing.pool (module)](library/multiprocessing#module-multiprocessing.pool) * [multiprocessing.shared\_memory (module)](library/multiprocessing.shared_memory#module-multiprocessing.shared_memory) * [multiprocessing.sharedctypes (module)](library/multiprocessing#module-multiprocessing.sharedctypes) * [**mutable**](glossary#term-mutable) + [object](reference/datamodel#index-22), [[1]](reference/simple_stmts#index-4), [[2]](reference/simple_stmts#index-9) + [sequence types](library/stdtypes#index-21) * [mutable object](reference/datamodel#index-1) * mutable sequence + [loop over](reference/compound_stmts#index-9) + [object](reference/datamodel#index-22) * [MutableMapping (class in collections.abc)](library/collections.abc#collections.abc.MutableMapping) + [(class in typing)](library/typing#typing.MutableMapping) * [MutableSequence (class in collections.abc)](library/collections.abc#collections.abc.MutableSequence) + [(class in typing)](library/typing#typing.MutableSequence) * [MutableSet (class in collections.abc)](library/collections.abc#collections.abc.MutableSet) + [(class in typing)](library/typing#typing.MutableSet) * [mvderwin() (curses.window method)](library/curses#curses.window.mvderwin) * [mvwin() (curses.window method)](library/curses#curses.window.mvwin) * [myrights() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.myrights) | N - | | | | --- | --- | | * [N\_TOKENS (in module token)](library/token#token.N_TOKENS) * [n\_waiting (threading.Barrier attribute)](library/threading#threading.Barrier.n_waiting) * [name](reference/executionmodel#index-4), [[1]](reference/expressions#index-3), [[2]](reference/lexical_analysis#index-10) + [binding](reference/compound_stmts#index-19), [[1]](reference/compound_stmts#index-19), [[2]](reference/compound_stmts#index-31), [[3]](reference/executionmodel#index-4), [[4]](reference/simple_stmts#index-34), [[5]](reference/simple_stmts#index-36), [[6]](reference/simple_stmts#index-4) + [binding, global](reference/simple_stmts#index-43) + [class](reference/compound_stmts#index-31) + [function](reference/compound_stmts#index-19), [[1]](reference/compound_stmts#index-19) + [mangling](reference/expressions#index-5), [[1]](tutorial/classes#index-1) + [rebinding](reference/simple_stmts#index-4) + [unbinding](reference/simple_stmts#index-22) * [Name (class in ast)](library/ast#ast.Name) * [name (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.name) + [(contextvars.ContextVar attribute)](library/contextvars#contextvars.ContextVar.name) + [(doctest.DocTest attribute)](library/doctest#doctest.DocTest.name) + [(email.headerregistry.BaseHeader attribute)](library/email.headerregistry#email.headerregistry.BaseHeader.name) + [(hashlib.hash attribute)](library/hashlib#hashlib.hash.name) + [(hmac.HMAC attribute)](library/hmac#hmac.HMAC.name) + [(http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.name) + [(importlib.abc.FileLoader attribute)](library/importlib#importlib.abc.FileLoader.name) + [(importlib.machinery.ExtensionFileLoader attribute)](library/importlib#importlib.machinery.ExtensionFileLoader.name) + [(importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.name) + [(importlib.machinery.SourceFileLoader attribute)](library/importlib#importlib.machinery.SourceFileLoader.name) + [(importlib.machinery.SourcelessFileLoader attribute)](library/importlib#importlib.machinery.SourcelessFileLoader.name) + [(in module os)](library/os#os.name) * [NAME (in module token)](library/token#token.NAME) * [name (inspect.Parameter attribute)](library/inspect#inspect.Parameter.name) + [(io.FileIO attribute)](library/io#io.FileIO.name) + [(multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.name) + [(multiprocessing.shared\_memory.SharedMemory attribute)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory.name) + [(os.DirEntry attribute)](library/os#os.DirEntry.name) + [(ossaudiodev.oss\_audio\_device attribute)](library/ossaudiodev#ossaudiodev.oss_audio_device.name) + [(pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.name) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.name) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.name) + [(threading.Thread attribute)](library/threading#threading.Thread.name) + [(xml.dom.Attr attribute)](library/xml.dom#xml.dom.Attr.name) + [(xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.name) + [(zipfile.Path attribute)](library/zipfile#zipfile.Path.name) * [name() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.name) + [(in module unicodedata)](library/unicodedata#unicodedata.name) * [name2codepoint (in module html.entities)](library/html.entities#html.entities.name2codepoint) * [Named Shared Memory](library/multiprocessing.shared_memory#index-0) * [**named tuple**](glossary#term-named-tuple) * [NamedExpr (class in ast)](library/ast#ast.NamedExpr) * [NamedTemporaryFile() (in module tempfile)](library/tempfile#tempfile.NamedTemporaryFile) * [NamedTuple (class in typing)](library/typing#typing.NamedTuple) * [namedtuple() (in module collections)](library/collections#collections.namedtuple) * [NameError](library/exceptions#NameError) + [exception](reference/expressions#index-4) * [NameError (built-in exception)](reference/executionmodel#index-9) * [namelist() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.namelist) * [nameprep() (in module encodings.idna)](library/codecs#encodings.idna.nameprep) * [namer (logging.handlers.BaseRotatingHandler attribute)](library/logging.handlers#logging.handlers.BaseRotatingHandler.namer) * namereplace + [error handler's name](library/codecs#index-3) * [namereplace\_errors() (in module codecs)](library/codecs#codecs.namereplace_errors) * names + [private](reference/expressions#index-5) * [names() (in module tkinter.font)](library/tkinter.font#tkinter.font.names) * [namespace](reference/executionmodel#index-3), [**[1]**](glossary#term-namespace) + [global](reference/datamodel#index-34) + [module](reference/datamodel#index-43) + [package](reference/import#index-5) * [Namespace (class in argparse)](library/argparse#argparse.Namespace) + [(class in multiprocessing.managers)](library/multiprocessing#multiprocessing.managers.Namespace) * [**namespace package**](glossary#term-namespace-package) * [namespace() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.namespace) * [Namespace() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Namespace) * [NAMESPACE\_DNS (in module uuid)](library/uuid#uuid.NAMESPACE_DNS) * [NAMESPACE\_OID (in module uuid)](library/uuid#uuid.NAMESPACE_OID) * [NAMESPACE\_URL (in module uuid)](library/uuid#uuid.NAMESPACE_URL) * [NAMESPACE\_X500 (in module uuid)](library/uuid#uuid.NAMESPACE_X500) * [NamespaceErr](library/xml.dom#xml.dom.NamespaceErr) * [namespaceURI (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.namespaceURI) * [nametofont() (in module tkinter.font)](library/tkinter.font#tkinter.font.nametofont) * [NaN](library/functions#index-2) * [nan (in module cmath)](library/cmath#cmath.nan) + [(in module math)](library/math#math.nan) * [nanj (in module cmath)](library/cmath#cmath.nanj) * [NannyNag](library/tabnanny#tabnanny.NannyNag) * [napms() (in module curses)](library/curses#curses.napms) * [nargs (optparse.Option attribute)](library/optparse#optparse.Option.nargs) * [native\_id (threading.Thread attribute)](library/threading#threading.Thread.native_id) * [nbytes (memoryview attribute)](library/stdtypes#memoryview.nbytes) * [ncurses\_version (in module curses)](library/curses#curses.ncurses_version) * [ndiff() (in module difflib)](library/difflib#difflib.ndiff) * [ndim (memoryview attribute)](library/stdtypes#memoryview.ndim) * [ne (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-ne) * [ne() (in module operator)](library/operator#operator.ne) * [needs\_input (bz2.BZ2Decompressor attribute)](library/bz2#bz2.BZ2Decompressor.needs_input) + [(lzma.LZMADecompressor attribute)](library/lzma#lzma.LZMADecompressor.needs_input) * [neg() (in module operator)](library/operator#operator.neg) * [negation](reference/expressions#index-60) * [**nested scope**](glossary#term-nested-scope) * [netmask (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.netmask) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.netmask) * [NetmaskValueError](library/ipaddress#ipaddress.NetmaskValueError) * [netrc (class in netrc)](library/netrc#netrc.netrc) + [(module)](library/netrc#module-netrc) * [NetrcParseError](library/netrc#netrc.NetrcParseError) * [netscape (http.cookiejar.CookiePolicy attribute)](library/http.cookiejar#http.cookiejar.CookiePolicy.netscape) * [network (ipaddress.IPv4Interface attribute)](library/ipaddress#ipaddress.IPv4Interface.network) + [(ipaddress.IPv6Interface attribute)](library/ipaddress#ipaddress.IPv6Interface.network) * [Network News Transfer Protocol](library/nntplib#index-0) * [network\_address (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.network_address) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.network_address) * [NEVER\_EQ (in module test.support)](library/test#test.support.NEVER_EQ) * [new() (in module hashlib)](library/hashlib#hashlib.new) + [(in module hmac)](library/hmac#hmac.new) * [**new-style class**](glossary#term-new-style-class) * [new\_alignment() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.new_alignment) * [new\_child() (collections.ChainMap method)](library/collections#collections.ChainMap.new_child) * [new\_class() (in module types)](library/types#types.new_class) * [new\_compiler() (in module distutils.ccompiler)](distutils/apiref#distutils.ccompiler.new_compiler) * [new\_event\_loop() (asyncio.AbstractEventLoopPolicy method)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy.new_event_loop) + [(in module asyncio)](library/asyncio-eventloop#asyncio.new_event_loop) * [new\_font() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.new_font) * [new\_margin() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.new_margin) * [new\_module() (in module imp)](library/imp#imp.new_module) * [new\_panel() (in module curses.panel)](library/curses.panel#curses.panel.new_panel) * [new\_spacing() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.new_spacing) * [new\_styles() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.new_styles) * [newer() (in module distutils.dep\_util)](distutils/apiref#distutils.dep_util.newer) * [newer\_group() (in module distutils.dep\_util)](distutils/apiref#distutils.dep_util.newer_group) * [newer\_pairwise() (in module distutils.dep\_util)](distutils/apiref#distutils.dep_util.newer_pairwise) * [newfunc (C type)](c-api/typeobj#c.newfunc) * [newgroups() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.newgroups) * [NEWLINE (in module token)](library/token#token.NEWLINE) * [NEWLINE token](reference/compound_stmts#index-2), [[1]](reference/lexical_analysis#index-3) * [newlines (io.TextIOBase attribute)](library/io#io.TextIOBase.newlines) * [newnews() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.newnews) * [newpad() (in module curses)](library/curses#curses.newpad) * [NewType() (in module typing)](library/typing#typing.NewType) * [newwin() (in module curses)](library/curses#curses.newwin) * [next (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-next) + [(pdb command)](library/pdb#pdbcommand-next) * [next() (built-in function)](library/functions#next) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.next) + [(tarfile.TarFile method)](library/tarfile#tarfile.TarFile.next) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.next) * [next\_minus() (decimal.Context method)](library/decimal#decimal.Context.next_minus) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.next_minus) * [next\_plus() (decimal.Context method)](library/decimal#decimal.Context.next_plus) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.next_plus) * [next\_toward() (decimal.Context method)](library/decimal#decimal.Context.next_toward) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.next_toward) * [nextafter() (in module math)](library/math#math.nextafter) * [nextfile() (in module fileinput)](library/fileinput#fileinput.nextfile) | * [nextkey() (dbm.gnu.gdbm method)](library/dbm#dbm.gnu.gdbm.nextkey) * [nextSibling (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.nextSibling) * [ngettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.ngettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.ngettext) + [(in module gettext)](library/gettext#gettext.ngettext) * [nice() (in module os)](library/os#os.nice) * [nis (module)](library/nis#module-nis) * [NL (in module token)](library/token#token.NL) * [nl() (in module curses)](library/curses#curses.nl) * [nl\_langinfo() (in module locale)](library/locale#locale.nl_langinfo) * [nlargest() (in module heapq)](library/heapq#heapq.nlargest) * [nlst() (ftplib.FTP method)](library/ftplib#ftplib.FTP.nlst) * NNTP + [protocol](library/nntplib#index-0) * [NNTP (class in nntplib)](library/nntplib#nntplib.NNTP) * [nntp\_implementation (nntplib.NNTP attribute)](library/nntplib#nntplib.NNTP.nntp_implementation) * [NNTP\_SSL (class in nntplib)](library/nntplib#nntplib.NNTP_SSL) * [nntp\_version (nntplib.NNTP attribute)](library/nntplib#nntplib.NNTP.nntp_version) * [NNTPDataError](library/nntplib#nntplib.NNTPDataError) * [NNTPError](library/nntplib#nntplib.NNTPError) * [nntplib (module)](library/nntplib#module-nntplib) * [NNTPPermanentError](library/nntplib#nntplib.NNTPPermanentError) * [NNTPProtocolError](library/nntplib#nntplib.NNTPProtocolError) * [NNTPReplyError](library/nntplib#nntplib.NNTPReplyError) * [NNTPTemporaryError](library/nntplib#nntplib.NNTPTemporaryError) * [no\_cache() (zoneinfo.ZoneInfo class method)](library/zoneinfo#zoneinfo.ZoneInfo.no_cache) * [no\_proxy](library/urllib.request#index-4) * [no\_tracing() (in module test.support)](library/test#test.support.no_tracing) * [no\_type\_check() (in module typing)](library/typing#typing.no_type_check) * [no\_type\_check\_decorator() (in module typing)](library/typing#typing.no_type_check_decorator) * [nocbreak() (in module curses)](library/curses#curses.nocbreak) * [NoDataAllowedErr](library/xml.dom#xml.dom.NoDataAllowedErr) * [node() (in module platform)](library/platform#platform.node) * [nodelay() (curses.window method)](library/curses#curses.window.nodelay) * [nodeName (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.nodeName) * [NodeTransformer (class in ast)](library/ast#ast.NodeTransformer) * [nodeType (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.nodeType) * [nodeValue (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.nodeValue) * [NodeVisitor (class in ast)](library/ast#ast.NodeVisitor) * [noecho() (in module curses)](library/curses#curses.noecho) * [NOEXPR (in module locale)](library/locale#locale.NOEXPR) * [NoModificationAllowedErr](library/xml.dom#xml.dom.NoModificationAllowedErr) * [nonblock() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.nonblock) * [NonCallableMagicMock (class in unittest.mock)](library/unittest.mock#unittest.mock.NonCallableMagicMock) * [NonCallableMock (class in unittest.mock)](library/unittest.mock#unittest.mock.NonCallableMock) * None + [object](c-api/none#index-0), [[1]](reference/datamodel#index-6), [[2]](reference/simple_stmts#index-3) * [None (Built-in object)](library/stdtypes#index-3) + [(built-in variable)](library/constants#None) * [nonl() (in module curses)](library/curses#curses.nonl) * nonlocal + [statement](reference/simple_stmts#index-45) * [Nonlocal (class in ast)](library/ast#ast.Nonlocal) * [nonzero (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-nonzero) * [noop() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.noop) + [(poplib.POP3 method)](library/poplib#poplib.POP3.noop) * [NoOptionError](library/configparser#configparser.NoOptionError) * [NOP (opcode)](library/dis#opcode-NOP) * [noqiflush() (in module curses)](library/curses#curses.noqiflush) * [noraw() (in module curses)](library/curses#curses.noraw) * [NoReturn (in module typing)](library/typing#typing.NoReturn) * [NORMAL (in module tkinter.font)](library/tkinter.font#tkinter.font.NORMAL) * [NORMAL\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.NORMAL_PRIORITY_CLASS) * [NormalDist (class in statistics)](library/statistics#statistics.NormalDist) * [normalize() (decimal.Context method)](library/decimal#decimal.Context.normalize) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.normalize) + [(in module locale)](library/locale#locale.normalize) + [(in module unicodedata)](library/unicodedata#unicodedata.normalize) + [(xml.dom.Node method)](library/xml.dom#xml.dom.Node.normalize) * [NORMALIZE\_WHITESPACE (in module doctest)](library/doctest#doctest.NORMALIZE_WHITESPACE) * [normalvariate() (in module random)](library/random#random.normalvariate) * [normcase() (in module os.path)](library/os.path#os.path.normcase) * [normpath() (in module os.path)](library/os.path#os.path.normpath) * [NoSectionError](library/configparser#configparser.NoSectionError) * [NoSuchMailboxError](library/mailbox#mailbox.NoSuchMailboxError) * not + [operator](library/stdtypes#index-6), [[1]](reference/expressions#index-83) * [Not (class in ast)](library/ast#ast.Not) * not in + [operator](library/stdtypes#index-10), [[1]](library/stdtypes#index-19), [[2]](reference/expressions#index-80) * [not\_() (in module operator)](library/operator#operator.not_) * [NotADirectoryError](library/exceptions#NotADirectoryError) * [notation](reference/introduction#index-0) * [notationDecl() (xml.sax.handler.DTDHandler method)](library/xml.sax.handler#xml.sax.handler.DTDHandler.notationDecl) * [NotationDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.NotationDeclHandler) * [notations (xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.notations) * [NotConnected](library/http.client#http.client.NotConnected) * [NoteBook (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.NoteBook) * [Notebook (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Notebook) * [NotEmptyError](library/mailbox#mailbox.NotEmptyError) * [NotEq (class in ast)](library/ast#ast.NotEq) * [NOTEQUAL (in module token)](library/token#token.NOTEQUAL) * [NotFoundErr](library/xml.dom#xml.dom.NotFoundErr) * [notify() (asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.notify) + [(threading.Condition method)](library/threading#threading.Condition.notify) * [notify\_all() (asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.notify_all) + [(threading.Condition method)](library/threading#threading.Condition.notify_all) * [notimeout() (curses.window method)](library/curses#curses.window.notimeout) * NotImplemented + [object](reference/datamodel#index-7) * [NotImplemented (built-in variable)](library/constants#NotImplemented) * [NotImplementedError](library/exceptions#NotImplementedError) * [NotIn (class in ast)](library/ast#ast.NotIn) * [NotStandaloneHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.NotStandaloneHandler) * [NotSupportedErr](library/xml.dom#xml.dom.NotSupportedErr) * [NotSupportedError](library/sqlite3#sqlite3.NotSupportedError) * [noutrefresh() (curses.window method)](library/curses#curses.window.noutrefresh) * [now() (datetime.datetime class method)](library/datetime#datetime.datetime.now) * [npgettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.npgettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.npgettext) + [(in module gettext)](library/gettext#gettext.npgettext) * [NSIG (in module signal)](library/signal#signal.NSIG) * [nsmallest() (in module heapq)](library/heapq#heapq.nsmallest) * [NT\_OFFSET (in module token)](library/token#token.NT_OFFSET) * [NTEventLogHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.NTEventLogHandler) * [ntohl() (in module socket)](library/socket#socket.ntohl) * [ntohs() (in module socket)](library/socket#socket.ntohs) * [ntransfercmd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.ntransfercmd) * null + [operation](reference/simple_stmts#index-20), [[1]](reference/simple_stmts#index-20) * [nullcontext() (in module contextlib)](library/contextlib#contextlib.nullcontext) * [NullFormatter (class in formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.NullFormatter) * [NullHandler (class in logging)](library/logging.handlers#logging.NullHandler) * [NullImporter (class in imp)](library/imp#imp.NullImporter) * [NullTranslations (class in gettext)](library/gettext#gettext.NullTranslations) * [NullWriter (class in formatter)](https://docs.python.org/3.9/library/formatter.html#formatter.NullWriter) * [num\_addresses (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.num_addresses) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.num_addresses) * [num\_tickets (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.num_tickets) * [number](reference/lexical_analysis#index-26) + [complex](reference/datamodel#index-14) + [floating point](reference/datamodel#index-13) * [Number (class in numbers)](library/numbers#numbers.Number) * [NUMBER (in module token)](library/token#token.NUMBER) * [number\_class() (decimal.Context method)](library/decimal#decimal.Context.number_class) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.number_class) * [numbers (module)](library/numbers#module-numbers) * [numerator (fractions.Fraction attribute)](library/fractions#fractions.Fraction.numerator) + [(numbers.Rational attribute)](library/numbers#numbers.Rational.numerator) * numeric + [conversions](library/stdtypes#index-15) + [literals](library/stdtypes#index-12) + [object](c-api/concrete#index-0), [[1]](library/stdtypes#index-11), [[2]](library/stdtypes#index-8), [[3]](reference/datamodel#index-51), [[4]](reference/datamodel#index-9) + [types, operations on](library/stdtypes#index-14) * [numeric literal](reference/lexical_analysis#index-26) * [numeric() (in module unicodedata)](library/unicodedata#unicodedata.numeric) * [numinput() (in module turtle)](library/turtle#turtle.numinput) * [numliterals (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-numliterals) | O - | | | | --- | --- | | * [O\_APPEND (in module os)](library/os#os.O_APPEND) * [O\_ASYNC (in module os)](library/os#os.O_ASYNC) * [O\_BINARY (in module os)](library/os#os.O_BINARY) * [O\_CLOEXEC (in module os)](library/os#os.O_CLOEXEC) * [O\_CREAT (in module os)](library/os#os.O_CREAT) * [O\_DIRECT (in module os)](library/os#os.O_DIRECT) * [O\_DIRECTORY (in module os)](library/os#os.O_DIRECTORY) * [O\_DSYNC (in module os)](library/os#os.O_DSYNC) * [O\_EXCL (in module os)](library/os#os.O_EXCL) * [O\_EXLOCK (in module os)](library/os#os.O_EXLOCK) * [O\_NDELAY (in module os)](library/os#os.O_NDELAY) * [O\_NOATIME (in module os)](library/os#os.O_NOATIME) * [O\_NOCTTY (in module os)](library/os#os.O_NOCTTY) * [O\_NOFOLLOW (in module os)](library/os#os.O_NOFOLLOW) * [O\_NOINHERIT (in module os)](library/os#os.O_NOINHERIT) * [O\_NONBLOCK (in module os)](library/os#os.O_NONBLOCK) * [O\_PATH (in module os)](library/os#os.O_PATH) * [O\_RANDOM (in module os)](library/os#os.O_RANDOM) * [O\_RDONLY (in module os)](library/os#os.O_RDONLY) * [O\_RDWR (in module os)](library/os#os.O_RDWR) * [O\_RSYNC (in module os)](library/os#os.O_RSYNC) * [O\_SEQUENTIAL (in module os)](library/os#os.O_SEQUENTIAL) * [O\_SHLOCK (in module os)](library/os#os.O_SHLOCK) * [O\_SHORT\_LIVED (in module os)](library/os#os.O_SHORT_LIVED) * [O\_SYNC (in module os)](library/os#os.O_SYNC) * [O\_TEMPORARY (in module os)](library/os#os.O_TEMPORARY) * [O\_TEXT (in module os)](library/os#os.O_TEXT) * [O\_TMPFILE (in module os)](library/os#os.O_TMPFILE) * [O\_TRUNC (in module os)](library/os#os.O_TRUNC) * [O\_WRONLY (in module os)](library/os#os.O_WRONLY) * [obj (memoryview attribute)](library/stdtypes#memoryview.obj) * [object](reference/datamodel#index-0), [**[1]**](glossary#term-object) + [asynchronous-generator](reference/expressions#index-35) + [Boolean](library/stdtypes#index-11), [[1]](reference/datamodel#index-11) + [built-in function](reference/datamodel#index-40), [[1]](reference/expressions#index-53) + [built-in method](reference/datamodel#index-41), [[1]](reference/expressions#index-53) + [bytearray](c-api/bytearray#index-0), [[1]](library/stdtypes#index-21), [[2]](library/stdtypes#index-38), [[3]](library/stdtypes#index-40) + [bytes](c-api/bytes#index-0), [[1]](library/stdtypes#index-38), [[2]](library/stdtypes#index-39) + [callable](reference/datamodel#index-32), [[1]](reference/expressions#index-47) + [Capsule](c-api/capsule#index-0) + [class](reference/compound_stmts#index-31), [[1]](reference/datamodel#index-45), [[2]](reference/expressions#index-54) + [class instance](reference/datamodel#index-45), [[1]](reference/datamodel#index-49), [[2]](reference/expressions#index-55) + [code](c-api/code#index-0), [[1]](library/marshal#index-1), [[2]](library/stdtypes#index-57), [[3]](reference/datamodel#index-55) + [complex](reference/datamodel#index-14) + [complex number](c-api/complex#index-0), [[1]](library/stdtypes#index-11) + [deallocation](extending/newtypes#index-0) + [dictionary](c-api/dict#index-0), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-30), [[3]](reference/datamodel#index-45), [[4]](reference/datamodel#index-76), [[5]](reference/expressions#index-17), [[6]](reference/expressions#index-42), [[7]](reference/simple_stmts#index-11) + [Ellipsis](reference/datamodel#index-8) + [file](c-api/file#index-0), [[1]](tutorial/inputoutput#index-0) + [finalization](extending/newtypes#index-0) + [floating point](c-api/float#index-0), [[1]](library/stdtypes#index-11), [[2]](reference/datamodel#index-13) + [frame](reference/datamodel#index-59) + [frozenset](c-api/set#index-0), [[1]](reference/datamodel#index-28) + [function](c-api/function#index-0), [[1]](reference/compound_stmts#index-19), [[2]](reference/datamodel#index-33), [[3]](reference/datamodel#index-40), [[4]](reference/expressions#index-52), [[5]](reference/expressions#index-53) + [generator](reference/datamodel#index-57), [[1]](reference/expressions#index-22), [[2]](reference/expressions#index-31) + [GenericAlias](library/stdtypes#index-53) + [immutable](reference/datamodel#index-17), [[1]](reference/expressions#index-20), [[2]](reference/expressions#index-7) + [immutable sequence](reference/datamodel#index-17) + [instance](reference/datamodel#index-45), [[1]](reference/datamodel#index-49), [[2]](reference/expressions#index-55) + [instancemethod](c-api/method#index-0) + [integer](c-api/long#index-0), [[1]](library/stdtypes#index-11), [[2]](reference/datamodel#index-10) + [io.StringIO](library/stdtypes#index-27) + [list](c-api/list#index-0), [[1]](library/stdtypes#index-21), [[2]](library/stdtypes#index-23), [[3]](reference/datamodel#index-23), [[4]](reference/expressions#index-15), [[5]](reference/expressions#index-40), [[6]](reference/expressions#index-42), [[7]](reference/expressions#index-45), [[8]](reference/simple_stmts#index-10) + [long integer](c-api/long#index-0) + [mapping](c-api/concrete#index-2), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-29), [[3]](reference/datamodel#index-51), [[4]](reference/expressions#index-42), [[5]](reference/simple_stmts#index-11) + [memoryview](c-api/memoryview#index-0), [[1]](library/stdtypes#index-38) + [method](c-api/method#index-1), [[1]](library/stdtypes#index-56), [[2]](reference/datamodel#index-35), [[3]](reference/datamodel#index-41), [[4]](reference/expressions#index-53), [[5]](tutorial/classes#index-0) + [module](c-api/module#index-0), [[1]](reference/datamodel#index-42), [[2]](reference/expressions#index-40) + [mutable](reference/datamodel#index-22), [[1]](reference/simple_stmts#index-4), [[2]](reference/simple_stmts#index-9) + [mutable sequence](reference/datamodel#index-22) + [None](c-api/none#index-0), [[1]](reference/datamodel#index-6), [[2]](reference/simple_stmts#index-3) + [NotImplemented](reference/datamodel#index-7) + [numeric](c-api/concrete#index-0), [[1]](library/stdtypes#index-11), [[2]](library/stdtypes#index-8), [[3]](reference/datamodel#index-51), [[4]](reference/datamodel#index-9) + [range](library/stdtypes#index-25) + [sequence](c-api/concrete#index-1), [[1]](library/stdtypes#index-18), [[2]](reference/compound_stmts#index-6), [[3]](reference/datamodel#index-15), [[4]](reference/datamodel#index-51), [[5]](reference/expressions#index-42), [[6]](reference/expressions#index-45), [[7]](reference/expressions#index-80), [[8]](reference/simple_stmts#index-10) + [set](c-api/set#index-0), [[1]](library/stdtypes#index-49), [[2]](reference/datamodel#index-27), [[3]](reference/expressions#index-16) + [set type](reference/datamodel#index-26) + [slice](reference/datamodel#index-95) + [socket](library/socket#index-0) + [string](library/stdtypes#index-26), [[1]](reference/expressions#index-42), [[2]](reference/expressions#index-45) + [traceback](library/sys#index-8), [[1]](library/traceback#index-0), [[2]](reference/compound_stmts#index-12), [[3]](reference/datamodel#index-62), [[4]](reference/simple_stmts#index-28) + [tuple](c-api/tuple#index-0), [[1]](library/stdtypes#index-20), [[2]](library/stdtypes#index-24), [[3]](reference/datamodel#index-20), [[4]](reference/expressions#index-42), [[5]](reference/expressions#index-45), [[6]](reference/expressions#index-91) + [type](c-api/intro#index-8), [[1]](c-api/type#index-0), [[2]](library/functions#index-11) + [user-defined function](reference/compound_stmts#index-19), [[1]](reference/datamodel#index-33), [[2]](reference/expressions#index-52) + [user-defined method](reference/datamodel#index-35) * [object (built-in class)](library/functions#object) + [(UnicodeError attribute)](library/exceptions#UnicodeError.object) * [object.\_\_slots\_\_ (built-in variable)](reference/datamodel#object.__slots__) * [object\_filenames() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.object_filenames) * objects + [comparing](library/stdtypes#index-8) + [flattening](library/pickle#index-0) + [marshalling](library/pickle#index-0) + [persistent](library/pickle#index-0) + [pickling](library/pickle#index-0) + [serializing](library/pickle#index-0) * [objobjargproc (C type)](c-api/typeobj#c.objobjargproc) * [objobjproc (C type)](c-api/typeobj#c.objobjproc) * [obufcount() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.obufcount) * [obuffree() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.obuffree) * [oct() (built-in function)](library/functions#oct) * octal + [literals](library/stdtypes#index-12) * [octal literal](reference/lexical_analysis#index-26) * [octdigits (in module string)](library/string#string.octdigits) * [offset (SyntaxError attribute)](library/exceptions#SyntaxError.offset) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.offset) + [(xml.parsers.expat.ExpatError attribute)](library/pyexpat#xml.parsers.expat.ExpatError.offset) * [OK (in module curses)](library/curses#curses.OK) * [ok\_command() (tkinter.filedialog.LoadFileDialog method)](library/dialog#tkinter.filedialog.LoadFileDialog.ok_command) + [(tkinter.filedialog.SaveFileDialog method)](library/dialog#tkinter.filedialog.SaveFileDialog.ok_command) * [ok\_event() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.ok_event) * [old\_value (contextvars.Token attribute)](library/contextvars#contextvars.Token.old_value) * [OleDLL (class in ctypes)](library/ctypes#ctypes.OleDLL) * [on\_motion() (tkinter.dnd.DndHandler method)](library/tkinter.dnd#tkinter.dnd.DndHandler.on_motion) * [on\_release() (tkinter.dnd.DndHandler method)](library/tkinter.dnd#tkinter.dnd.DndHandler.on_release) * [onclick() (in module turtle)](library/turtle#turtle.onclick) * [ondrag() (in module turtle)](library/turtle#turtle.ondrag) * [onecmd() (cmd.Cmd method)](library/cmd#cmd.Cmd.onecmd) * [onkey() (in module turtle)](library/turtle#turtle.onkey) * [onkeypress() (in module turtle)](library/turtle#turtle.onkeypress) * [onkeyrelease() (in module turtle)](library/turtle#turtle.onkeyrelease) * [onrelease() (in module turtle)](library/turtle#turtle.onrelease) * [onscreenclick() (in module turtle)](library/turtle#turtle.onscreenclick) * [ontimer() (in module turtle)](library/turtle#turtle.ontimer) * [OP (in module token)](library/token#token.OP) * [OP\_ALL (in module ssl)](library/ssl#ssl.OP_ALL) * [OP\_CIPHER\_SERVER\_PREFERENCE (in module ssl)](library/ssl#ssl.OP_CIPHER_SERVER_PREFERENCE) * [OP\_ENABLE\_MIDDLEBOX\_COMPAT (in module ssl)](library/ssl#ssl.OP_ENABLE_MIDDLEBOX_COMPAT) * [OP\_IGNORE\_UNEXPECTED\_EOF (in module ssl)](library/ssl#ssl.OP_IGNORE_UNEXPECTED_EOF) * [OP\_NO\_COMPRESSION (in module ssl)](library/ssl#ssl.OP_NO_COMPRESSION) * [OP\_NO\_RENEGOTIATION (in module ssl)](library/ssl#ssl.OP_NO_RENEGOTIATION) * [OP\_NO\_SSLv2 (in module ssl)](library/ssl#ssl.OP_NO_SSLv2) * [OP\_NO\_SSLv3 (in module ssl)](library/ssl#ssl.OP_NO_SSLv3) * [OP\_NO\_TICKET (in module ssl)](library/ssl#ssl.OP_NO_TICKET) * [OP\_NO\_TLSv1 (in module ssl)](library/ssl#ssl.OP_NO_TLSv1) * [OP\_NO\_TLSv1\_1 (in module ssl)](library/ssl#ssl.OP_NO_TLSv1_1) * [OP\_NO\_TLSv1\_2 (in module ssl)](library/ssl#ssl.OP_NO_TLSv1_2) * [OP\_NO\_TLSv1\_3 (in module ssl)](library/ssl#ssl.OP_NO_TLSv1_3) * [OP\_SINGLE\_DH\_USE (in module ssl)](library/ssl#ssl.OP_SINGLE_DH_USE) * [OP\_SINGLE\_ECDH\_USE (in module ssl)](library/ssl#ssl.OP_SINGLE_ECDH_USE) * open + [built-in function](reference/datamodel#index-53), [[1]](tutorial/inputoutput#index-0) * [Open (class in tkinter.filedialog)](library/dialog#tkinter.filedialog.Open) * [open() (built-in function)](library/functions#open) + [(distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.open) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.open) + [(importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.open) + [(in module aifc)](library/aifc#aifc.open) + [(in module bz2)](library/bz2#bz2.open) + [(in module codecs)](library/codecs#codecs.open) + [(in module dbm)](library/dbm#dbm.open) + [(in module dbm.dumb)](library/dbm#dbm.dumb.open) + [(in module dbm.gnu)](library/dbm#dbm.gnu.open) + [(in module dbm.ndbm)](library/dbm#dbm.ndbm.open) + [(in module gzip)](library/gzip#gzip.open) + [(in module io)](library/io#io.open) + [(in module lzma)](library/lzma#lzma.open) + [(in module os)](library/os#os.open) + [(in module ossaudiodev)](library/ossaudiodev#ossaudiodev.open) + [(in module shelve)](library/shelve#shelve.open) + [(in module sunau)](https://docs.python.org/3.9/library/sunau.html#sunau.open) + [(in module tarfile)](library/tarfile#tarfile.open) + [(in module tokenize)](library/tokenize#tokenize.open) + [(in module wave)](library/wave#wave.open) + [(in module webbrowser)](library/webbrowser#webbrowser.open) + [(pathlib.Path method)](library/pathlib#pathlib.Path.open) + [(pipes.Template method)](library/pipes#pipes.Template.open) + [(tarfile.TarFile class method)](library/tarfile#tarfile.TarFile.open) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.open) + [(urllib.request.OpenerDirector method)](library/urllib.request#urllib.request.OpenerDirector.open) + [(urllib.request.URLopener method)](library/urllib.request#urllib.request.URLopener.open) + [(webbrowser.controller method)](library/webbrowser#webbrowser.controller.open) + [(zipfile.Path method)](library/zipfile#zipfile.Path.open) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.open) | * [open\_binary() (in module importlib.resources)](library/importlib#importlib.resources.open_binary) * [open\_code() (in module io)](library/io#io.open_code) * [open\_connection() (in module asyncio)](library/asyncio-stream#asyncio.open_connection) * [open\_new() (in module webbrowser)](library/webbrowser#webbrowser.open_new) + [(webbrowser.controller method)](library/webbrowser#webbrowser.controller.open_new) * [open\_new\_tab() (in module webbrowser)](library/webbrowser#webbrowser.open_new_tab) + [(webbrowser.controller method)](library/webbrowser#webbrowser.controller.open_new_tab) * [open\_osfhandle() (in module msvcrt)](library/msvcrt#msvcrt.open_osfhandle) * [open\_resource() (importlib.abc.ResourceReader method)](library/importlib#importlib.abc.ResourceReader.open_resource) * [open\_text() (in module importlib.resources)](library/importlib#importlib.resources.open_text) * [open\_unix\_connection() (in module asyncio)](library/asyncio-stream#asyncio.open_unix_connection) * [open\_unknown() (urllib.request.URLopener method)](library/urllib.request#urllib.request.URLopener.open_unknown) * [open\_urlresource() (in module test.support)](library/test#test.support.open_urlresource) * [OpenDatabase() (in module msilib)](library/msilib#msilib.OpenDatabase) * [OpenerDirector (class in urllib.request)](library/urllib.request#urllib.request.OpenerDirector) * [OpenKey() (in module winreg)](library/winreg#winreg.OpenKey) * [OpenKeyEx() (in module winreg)](library/winreg#winreg.OpenKeyEx) * [openlog() (in module syslog)](library/syslog#syslog.openlog) * [openmixer() (in module ossaudiodev)](library/ossaudiodev#ossaudiodev.openmixer) * [openpty() (in module os)](library/os#os.openpty) + [(in module pty)](library/pty#pty.openpty) * OpenSSL + [(use in module hashlib)](library/hashlib#index-2) + [(use in module ssl)](library/ssl#index-0) * [OPENSSL\_VERSION (in module ssl)](library/ssl#ssl.OPENSSL_VERSION) * [OPENSSL\_VERSION\_INFO (in module ssl)](library/ssl#ssl.OPENSSL_VERSION_INFO) * [OPENSSL\_VERSION\_NUMBER (in module ssl)](library/ssl#ssl.OPENSSL_VERSION_NUMBER) * [OpenView() (msilib.Database method)](library/msilib#msilib.Database.OpenView) * operation + [binary arithmetic](reference/expressions#index-64) + [binary bitwise](reference/expressions#index-73) + [Boolean](reference/expressions#index-82) + [concatenation](library/stdtypes#index-19) + [null](reference/simple_stmts#index-20), [[1]](reference/simple_stmts#index-20) + [power](reference/expressions#index-58) + [repetition](library/stdtypes#index-19) + [shifting](reference/expressions#index-71) + [slice](library/stdtypes#index-19) + [subscript](library/stdtypes#index-19) + [unary arithmetic](reference/expressions#index-59) + [unary bitwise](reference/expressions#index-59) * [OperationalError](library/sqlite3#sqlite3.OperationalError) * operations + [bitwise](library/stdtypes#index-16) + [Boolean](library/stdtypes#index-1), [[1]](library/stdtypes#index-5) + [masking](library/stdtypes#index-16) + [shifting](library/stdtypes#index-16) * operations on + [dictionary type](library/stdtypes#index-50) + [integer types](library/stdtypes#index-16) + [list type](library/stdtypes#index-22) + [mapping types](library/stdtypes#index-50) + [numeric types](library/stdtypes#index-14) + [sequence types](library/stdtypes#index-19), [[1]](library/stdtypes#index-22) * operator + [!=](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [% (percent)](library/stdtypes#index-13), [[1]](reference/expressions#index-68) + [& (ampersand)](library/stdtypes#index-16), [[1]](reference/expressions#index-74) + [\* (asterisk)](library/stdtypes#index-13), [[1]](reference/expressions#index-65) + [\*\*](library/stdtypes#index-13), [[1]](reference/expressions#index-58) + [+ (plus)](library/stdtypes#index-13), [[1]](reference/expressions#index-61), [[2]](reference/expressions#index-69) + [- (minus)](library/stdtypes#index-13), [[1]](reference/expressions#index-60), [[2]](reference/expressions#index-70) + [/ (slash)](library/stdtypes#index-13), [[1]](reference/expressions#index-67) + [//](library/stdtypes#index-13), [[1]](reference/expressions#index-67) + [< (less)](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [<<](library/stdtypes#index-16), [[1]](reference/expressions#index-71) + [<=](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [==](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [> (greater)](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [>=](library/stdtypes#index-7), [[1]](reference/expressions#index-77) + [>>](library/stdtypes#index-16), [[1]](reference/expressions#index-71) + [@ (at)](reference/expressions#index-66) + [^ (caret)](library/stdtypes#index-16), [[1]](reference/expressions#index-75) + [| (vertical bar)](library/stdtypes#index-16), [[1]](reference/expressions#index-76) + [~ (tilde)](library/stdtypes#index-16), [[1]](reference/expressions#index-62) + [and](library/stdtypes#index-4), [[1]](library/stdtypes#index-6), [[2]](reference/expressions#index-84) + [comparison](library/stdtypes#index-7) + [in](library/stdtypes#index-10), [[1]](library/stdtypes#index-19), [[2]](reference/expressions#index-80) + [is](library/stdtypes#index-7), [[1]](reference/expressions#index-81) + [is not](library/stdtypes#index-7), [[1]](reference/expressions#index-81) + [not](library/stdtypes#index-6), [[1]](reference/expressions#index-83) + [not in](library/stdtypes#index-10), [[1]](library/stdtypes#index-19), [[2]](reference/expressions#index-80) + [or](library/stdtypes#index-4), [[1]](library/stdtypes#index-6), [[2]](reference/expressions#index-85) + [overloading](reference/datamodel#index-67) + [precedence](reference/expressions#index-96) + [ternary](reference/expressions#index-87) * [operator (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-operator) + [(module)](library/operator#module-operator) * [operators](reference/lexical_analysis#index-30) * [opmap (in module dis)](library/dis#dis.opmap) * [opname (in module dis)](library/dis#dis.opname) * [optim\_args\_from\_interpreter\_flags() (in module test.support)](library/test#test.support.optim_args_from_interpreter_flags) * [optimize() (in module pickletools)](library/pickletools#pickletools.optimize) * [OPTIMIZED\_BYTECODE\_SUFFIXES (in module importlib.machinery)](library/importlib#importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES) * [Optional (in module typing)](library/typing#typing.Optional) * [OptionGroup (class in optparse)](library/optparse#optparse.OptionGroup) * [OptionMenu (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.OptionMenu) * [OptionParser (class in optparse)](library/optparse#optparse.OptionParser) * [Options (class in ssl)](library/ssl#ssl.Options) * [options (doctest.Example attribute)](library/doctest#doctest.Example.options) + [(ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.options) * [options() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.options) * [optionxform() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.optionxform) * [optparse (module)](library/optparse#module-optparse) * or + [bitwise](reference/expressions#index-76) + [exclusive](reference/expressions#index-75) + [inclusive](reference/expressions#index-76) + [operator](library/stdtypes#index-4), [[1]](library/stdtypes#index-6), [[2]](reference/expressions#index-85) * [Or (class in ast)](library/ast#ast.Or) * [or\_() (in module operator)](library/operator#operator.or_) * ord + [built-in function](reference/datamodel#index-19) * [ord() (built-in function)](library/functions#ord) * order + [evaluation](reference/expressions#index-95) * [ordered\_attributes (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.ordered_attributes) * [OrderedDict (class in collections)](library/collections#collections.OrderedDict) + [(class in typing)](library/typing#typing.OrderedDict) * [origin (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.origin) * [origin\_req\_host (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.origin_req_host) * [origin\_server (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.origin_server) * os + [module](library/posix#index-0) * [os (module)](library/os#module-os) * [os.path (module)](library/os.path#module-os.path) * [os\_environ (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.os_environ) * [OSError](library/exceptions#OSError) * [ossaudiodev (module)](library/ossaudiodev#module-ossaudiodev) * [OSSAudioError](library/ossaudiodev#ossaudiodev.OSSAudioError) * outfile + [json.tool command line option](library/json#cmdoption-json-tool-arg-outfile) * [output](reference/simple_stmts#index-3) + [standard](reference/simple_stmts#index-3) * [output (subprocess.CalledProcessError attribute)](library/subprocess#subprocess.CalledProcessError.output) + [(subprocess.TimeoutExpired attribute)](library/subprocess#subprocess.TimeoutExpired.output) + [(unittest.TestCase attribute)](library/unittest#unittest.TestCase.output) * [output() (http.cookies.BaseCookie method)](library/http.cookies#http.cookies.BaseCookie.output) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.output) * [output\_charset (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.output_charset) * [output\_charset() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.output_charset) * [output\_codec (email.charset.Charset attribute)](library/email.charset#email.charset.Charset.output_codec) * [output\_difference() (doctest.OutputChecker method)](library/doctest#doctest.OutputChecker.output_difference) * [OutputChecker (class in doctest)](library/doctest#doctest.OutputChecker) * [OutputString() (http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.OutputString) * [over() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.over) * [Overflow (class in decimal)](library/decimal#decimal.Overflow) * [OverflowError](library/exceptions#OverflowError) + [(built-in exception)](c-api/long#index-1), [[1]](c-api/long#index-2), [[2]](c-api/long#index-3), [[3]](c-api/long#index-4), [[4]](c-api/long#index-5), [[5]](c-api/long#index-6) * [overlap() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.overlap) * [overlaps() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.overlaps) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.overlaps) * [overlay() (curses.window method)](library/curses#curses.window.overlay) * [overload() (in module typing)](library/typing#typing.overload) * overloading + [operator](reference/datamodel#index-67) * [overwrite() (curses.window method)](library/curses#curses.window.overwrite) * [owner() (pathlib.Path method)](library/pathlib#pathlib.Path.owner) | P - | | | | --- | --- | | * [p (pdb command)](library/pdb#pdbcommand-p) * [P\_ALL (in module os)](library/os#os.P_ALL) * [P\_DETACH (in module os)](library/os#os.P_DETACH) * [P\_NOWAIT (in module os)](library/os#os.P_NOWAIT) * [P\_NOWAITO (in module os)](library/os#os.P_NOWAITO) * [P\_OVERLAY (in module os)](library/os#os.P_OVERLAY) * [P\_PGID (in module os)](library/os#os.P_PGID) * [P\_PID (in module os)](library/os#os.P_PID) * [P\_PIDFD (in module os)](library/os#os.P_PIDFD) * [P\_WAIT (in module os)](library/os#os.P_WAIT) * [pack() (in module struct)](library/struct#struct.pack) + [(mailbox.MH method)](library/mailbox#mailbox.MH.pack) + [(struct.Struct method)](library/struct#struct.Struct.pack) * [pack\_array() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_array) * [pack\_bytes() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_bytes) * [pack\_double() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_double) * [pack\_farray() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_farray) * [pack\_float() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_float) * [pack\_fopaque() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_fopaque) * [pack\_fstring() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_fstring) * [pack\_into() (in module struct)](library/struct#struct.pack_into) + [(struct.Struct method)](library/struct#struct.Struct.pack_into) * [pack\_list() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_list) * [pack\_opaque() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_opaque) * [pack\_string() (xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.pack_string) * [package](library/site#index-4), [[1]](reference/import#index-3), [**[2]**](glossary#term-package) + [namespace](reference/import#index-5) + [portion](reference/import#index-5) + [regular](reference/import#index-4) * [Package (in module importlib.resources)](library/importlib#importlib.resources.Package) * package variable + [\_\_all\_\_](c-api/import#index-0) * [packed (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.packed) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.packed) * [Packer (class in xdrlib)](library/xdrlib#xdrlib.Packer) * packing + [binary data](library/struct#index-0) * [packing (widgets)](library/tkinter#index-3) * [PAGER](library/pydoc#index-1) * [pair\_content() (in module curses)](library/curses#curses.pair_content) * [pair\_number() (in module curses)](library/curses#curses.pair_number) * [PanedWindow (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.PanedWindow) * [**parameter**](glossary#term-parameter) + [call semantics](reference/expressions#index-48) + [difference from argument](faq/programming#index-1) + [function definition](reference/compound_stmts#index-18) + [value, default](reference/compound_stmts#index-22) * [Parameter (class in inspect)](library/inspect#inspect.Parameter) * [ParameterizedMIMEHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.ParameterizedMIMEHeader) * [parameters (inspect.Signature attribute)](library/inspect#inspect.Signature.parameters) * [params (email.headerregistry.ParameterizedMIMEHeader attribute)](library/email.headerregistry#email.headerregistry.ParameterizedMIMEHeader.params) * [paramstyle (in module sqlite3)](library/sqlite3#sqlite3.paramstyle) * [pardir (in module os)](library/os#os.pardir) * [paren (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-paren) * [parent (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.parent) + [(pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.parent) + [(pyclbr.Function attribute)](library/pyclbr#pyclbr.Function.parent) + [(urllib.request.BaseHandler attribute)](library/urllib.request#urllib.request.BaseHandler.parent) * [parent() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.parent) * [parent\_process() (in module multiprocessing)](library/multiprocessing#multiprocessing.parent_process) * [parenthesized form](reference/expressions#index-8) * [parentNode (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.parentNode) * [parents (collections.ChainMap attribute)](library/collections#collections.ChainMap.parents) * [paretovariate() (in module random)](library/random#random.paretovariate) * [parse() (doctest.DocTestParser method)](library/doctest#doctest.DocTestParser.parse) + [(email.parser.BytesParser method)](library/email.parser#email.parser.BytesParser.parse) + [(email.parser.Parser method)](library/email.parser#email.parser.Parser.parse) + [(in module ast)](library/ast#ast.parse) + [(in module cgi)](library/cgi#cgi.parse) + [(in module xml.dom.minidom)](library/xml.dom.minidom#xml.dom.minidom.parse) + [(in module xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.parse) + [(in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.parse) + [(in module xml.sax)](library/xml.sax#xml.sax.parse) + [(string.Formatter method)](library/string#string.Formatter.parse) + [(urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.parse) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.parse) * [Parse() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.Parse) * [parse() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.parse) * [parse\_and\_bind() (in module readline)](library/readline#readline.parse_and_bind) * [parse\_args() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.parse_args) * [PARSE\_COLNAMES (in module sqlite3)](library/sqlite3#sqlite3.PARSE_COLNAMES) * [parse\_config\_h() (in module sysconfig)](library/sysconfig#sysconfig.parse_config_h) * [PARSE\_DECLTYPES (in module sqlite3)](library/sqlite3#sqlite3.PARSE_DECLTYPES) * [parse\_header() (in module cgi)](library/cgi#cgi.parse_header) * [parse\_headers() (in module http.client)](library/http.client#http.client.parse_headers) * [parse\_intermixed\_args() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.parse_intermixed_args) * [parse\_known\_args() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.parse_known_args) * [parse\_known\_intermixed\_args() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.parse_known_intermixed_args) * [parse\_multipart() (in module cgi)](library/cgi#cgi.parse_multipart) * [parse\_qs() (in module urllib.parse)](library/urllib.parse#urllib.parse.parse_qs) * [parse\_qsl() (in module urllib.parse)](library/urllib.parse#urllib.parse.parse_qsl) * [parseaddr() (in module email.utils)](library/email.utils#email.utils.parseaddr) * [parsebytes() (email.parser.BytesParser method)](library/email.parser#email.parser.BytesParser.parsebytes) * [parsedate() (in module email.utils)](library/email.utils#email.utils.parsedate) * [parsedate\_to\_datetime() (in module email.utils)](library/email.utils#email.utils.parsedate_to_datetime) * [parsedate\_tz() (in module email.utils)](library/email.utils#email.utils.parsedate_tz) * [ParseError (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.ParseError) * [ParseFile() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.ParseFile) * [ParseFlags() (in module imaplib)](library/imaplib#imaplib.ParseFlags) * [parser](reference/lexical_analysis#index-0) * [Parser (class in email.parser)](library/email.parser#email.parser.Parser) * [parser (module)](library/parser#module-parser) * [ParserCreate() (in module xml.parsers.expat)](library/pyexpat#xml.parsers.expat.ParserCreate) * [ParserError](library/parser#parser.ParserError) * [ParseResult (class in urllib.parse)](library/urllib.parse#urllib.parse.ParseResult) * [ParseResultBytes (class in urllib.parse)](library/urllib.parse#urllib.parse.ParseResultBytes) * [parsestr() (email.parser.Parser method)](library/email.parser#email.parser.Parser.parsestr) * [parseString() (in module xml.dom.minidom)](library/xml.dom.minidom#xml.dom.minidom.parseString) + [(in module xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.parseString) + [(in module xml.sax)](library/xml.sax#xml.sax.parseString) * parsing + [Python source code](library/parser#index-0) + [URL](library/urllib.parse#index-0) * [ParsingError](library/configparser#configparser.ParsingError) * [partial (asyncio.IncompleteReadError attribute)](library/asyncio-exceptions#asyncio.IncompleteReadError.partial) * [partial() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.partial) + [(in module functools)](library/functools#functools.partial) * [partialmethod (class in functools)](library/functools#functools.partialmethod) * [parties (threading.Barrier attribute)](library/threading#threading.Barrier.parties) * [partition() (bytearray method)](library/stdtypes#bytearray.partition) + [(bytes method)](library/stdtypes#bytes.partition) + [(str method)](library/stdtypes#str.partition) * pass + [statement](reference/simple_stmts#index-20) * [Pass (class in ast)](library/ast#ast.Pass) * [pass\_() (poplib.POP3 method)](library/poplib#poplib.POP3.pass_) * [Paste](library/idle#index-4) * [patch() (in module test.support)](library/test#test.support.patch) + [(in module unittest.mock)](library/unittest.mock#unittest.mock.patch) * [patch.dict() (in module unittest.mock)](library/unittest.mock#unittest.mock.patch.dict) * [patch.multiple() (in module unittest.mock)](library/unittest.mock#unittest.mock.patch.multiple) * [patch.object() (in module unittest.mock)](library/unittest.mock#unittest.mock.patch.object) * [patch.stopall() (in module unittest.mock)](library/unittest.mock#unittest.mock.patch.stopall) * [PATH](c-api/intro#index-25), [[1]](c-api/intro#index-26), [[2]](faq/library#index-0), [[3]](faq/library#index-1), [[4]](library/cgi#index-3), [[5]](library/cgi#index-6), [[6]](library/os#index-27), [[7]](library/os#index-28), [[8]](library/os#index-29), [[9]](library/os#index-30), [[10]](library/os#index-33), [[11]](library/os#index-34), [[12]](library/os#index-35), [[13]](library/os#index-36), [[14]](library/os#index-46), [[15]](library/site#index-3), [[16]](library/webbrowser#index-3), [[17]](tutorial/appendix#index-0), [[18]](tutorial/modules#index-2), [[19]](using/cmdline#index-30), [[20]](using/unix#index-2), [[21]](using/windows#index-1), [[22]](using/windows#index-10), [[23]](using/windows#index-14), [[24]](using/windows#index-16), [[25]](using/windows#index-17), [[26]](using/windows#index-18), [[27]](using/windows#index-19), [[28]](using/windows#index-2), [[29]](using/windows#index-3), [[30]](using/windows#index-5), [[31]](using/windows#index-6), [[32]](using/windows#index-8), [[33]](using/windows#index-9), [[34]](https://docs.python.org/3.9/whatsnew/3.4.html#index-55), [[35]](https://docs.python.org/3.9/whatsnew/3.4.html#index-58), [[36]](https://docs.python.org/3.9/whatsnew/3.4.html#index-59), [[37]](https://docs.python.org/3.9/whatsnew/3.8.html#index-22), [[38]](https://docs.python.org/3.9/whatsnew/changelog.html#index-65), [[39]](https://docs.python.org/3.9/whatsnew/changelog.html#index-66) * path + [configuration file](library/site#index-4) + [hooks](reference/import#index-9) + [module search](c-api/init#index-16), [[1]](c-api/init#index-23), [[2]](c-api/init#index-24), [[3]](c-api/intro#index-23), [[4]](library/linecache#index-0), [[5]](library/site#index-0), [[6]](library/sys#index-21), [[7]](tutorial/modules#index-0) + [operations](library/os.path#index-0), [[1]](library/pathlib#index-0) * [Path (class in pathlib)](library/pathlib#pathlib.Path) + [(class in zipfile)](library/zipfile#zipfile.Path) * [path (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.path) + [(http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.path) + [(importlib.abc.FileLoader attribute)](library/importlib#importlib.abc.FileLoader.path) + [(importlib.machinery.ExtensionFileLoader attribute)](library/importlib#importlib.machinery.ExtensionFileLoader.path) + [(importlib.machinery.FileFinder attribute)](library/importlib#importlib.machinery.FileFinder.path) + [(importlib.machinery.SourceFileLoader attribute)](library/importlib#importlib.machinery.SourceFileLoader.path) + [(importlib.machinery.SourcelessFileLoader attribute)](library/importlib#importlib.machinery.SourcelessFileLoader.path) + [(in module sys)](c-api/init#index-16), [[1]](c-api/init#index-23), [[2]](c-api/init#index-24), [[3]](c-api/intro#index-23), [[4]](library/sys#sys.path) + [(os.DirEntry attribute)](library/os#os.DirEntry.path) * [path based finder](reference/import#index-16), [**[1]**](glossary#term-path-based-finder) * [Path browser](library/idle#index-1) * [**path entry**](glossary#term-path-entry) * [**path entry finder**](glossary#term-path-entry-finder) * [**path entry hook**](glossary#term-path-entry-hook) * [path hooks](reference/import#index-9) * [path() (in module importlib.resources)](library/importlib#importlib.resources.path) * [**path-like object**](glossary#term-path-like-object) * [path\_hook() (importlib.machinery.FileFinder class method)](library/importlib#importlib.machinery.FileFinder.path_hook) * [path\_hooks (in module sys)](library/sys#sys.path_hooks) * [path\_importer\_cache (in module sys)](library/sys#sys.path_importer_cache) * [path\_mtime() (importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.path_mtime) * [path\_return\_ok() (http.cookiejar.CookiePolicy method)](library/http.cookiejar#http.cookiejar.CookiePolicy.path_return_ok) * [path\_stats() (importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.path_stats) + [(importlib.machinery.SourceFileLoader method)](library/importlib#importlib.machinery.SourceFileLoader.path_stats) * [pathconf() (in module os)](library/os#os.pathconf) * [pathconf\_names (in module os)](library/os#os.pathconf_names) * [PathEntryFinder (class in importlib.abc)](library/importlib#importlib.abc.PathEntryFinder) * [PATHEXT](using/windows#index-4), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-51), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-9) * [PathFinder (class in importlib.machinery)](library/importlib#importlib.machinery.PathFinder) * [pathlib (module)](library/pathlib#module-pathlib) * [PathLike (class in os)](library/os#os.PathLike) * [pathname2url() (in module urllib.request)](library/urllib.request#urllib.request.pathname2url) * [pathsep (in module os)](library/os#os.pathsep) * [Pattern (class in typing)](library/typing#typing.Pattern) * [pattern (re.error attribute)](library/re#re.error.pattern) + [(re.Pattern attribute)](library/re#re.Pattern.pattern) * [pause() (in module signal)](library/signal#signal.pause) * [pause\_reading() (asyncio.ReadTransport method)](library/asyncio-protocol#asyncio.ReadTransport.pause_reading) * [pause\_writing() (asyncio.BaseProtocol method)](library/asyncio-protocol#asyncio.BaseProtocol.pause_writing) * [PAX\_FORMAT (in module tarfile)](library/tarfile#tarfile.PAX_FORMAT) * [pax\_headers (tarfile.TarFile attribute)](library/tarfile#tarfile.TarFile.pax_headers) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.pax_headers) * [pbkdf2\_hmac() (in module hashlib)](library/hashlib#hashlib.pbkdf2_hmac) * [pd() (in module turtle)](library/turtle#turtle.pd) * [Pdb (class in pdb)](library/pdb#index-1), [[1]](library/pdb#pdb.Pdb) * [pdb (module)](library/pdb#module-pdb) * [pdf() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.pdf) * [peek() (bz2.BZ2File method)](library/bz2#bz2.BZ2File.peek) + [(gzip.GzipFile method)](library/gzip#gzip.GzipFile.peek) + [(io.BufferedReader method)](library/io#io.BufferedReader.peek) + [(lzma.LZMAFile method)](library/lzma#lzma.LZMAFile.peek) + [(weakref.finalize method)](library/weakref#weakref.finalize.peek) * [peer (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.peer) * [PEM\_cert\_to\_DER\_cert() (in module ssl)](library/ssl#ssl.PEM_cert_to_DER_cert) * [pen() (in module turtle)](library/turtle#turtle.pen) * [pencolor() (in module turtle)](library/turtle#turtle.pencolor) * [pending (ssl.MemoryBIO attribute)](library/ssl#ssl.MemoryBIO.pending) * [pending() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.pending) * [PendingDeprecationWarning](library/exceptions#PendingDeprecationWarning) * [pendown() (in module turtle)](library/turtle#turtle.pendown) * [pensize() (in module turtle)](library/turtle#turtle.pensize) * [penup() (in module turtle)](library/turtle#turtle.penup) * [**PEP**](glossary#term-pep) * [PERCENT (in module token)](library/token#token.PERCENT) * [PERCENTEQUAL (in module token)](library/token#token.PERCENTEQUAL) * [perf\_counter() (in module time)](library/time#time.perf_counter) * [perf\_counter\_ns() (in module time)](library/time#time.perf_counter_ns) * [Performance](library/timeit#index-0) * [perm() (in module math)](library/math#math.perm) * [PermissionError](library/exceptions#PermissionError) * [permutations() (in module itertools)](library/itertools#itertools.permutations) * [Persist() (msilib.SummaryInformation method)](library/msilib#msilib.SummaryInformation.Persist) * [persistence](library/pickle#index-0) * persistent + [objects](library/pickle#index-0) * [persistent\_id (pickle protocol)](library/pickle#index-6) * [persistent\_id() (pickle.Pickler method)](library/pickle#pickle.Pickler.persistent_id) * [persistent\_load (pickle protocol)](library/pickle#index-6) * [persistent\_load() (pickle.Unpickler method)](library/pickle#pickle.Unpickler.persistent_load) * [PF\_CAN (in module socket)](library/socket#socket.PF_CAN) * [PF\_PACKET (in module socket)](library/socket#socket.PF_PACKET) * [PF\_RDS (in module socket)](library/socket#socket.PF_RDS) * [pformat() (in module pprint)](library/pprint#pprint.pformat) + [(pprint.PrettyPrinter method)](library/pprint#pprint.PrettyPrinter.pformat) * [pgettext() (gettext.GNUTranslations method)](library/gettext#gettext.GNUTranslations.pgettext) + [(gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.pgettext) + [(in module gettext)](library/gettext#gettext.pgettext) * [PGO (in module test.support)](library/test#test.support.PGO) * [phase() (in module cmath)](library/cmath#cmath.phase) * [Philbrick, Geoff](extending/extending#index-4) * [physical line](reference/lexical_analysis#index-22), [[1]](reference/lexical_analysis#index-3), [[2]](reference/lexical_analysis#index-6) * [pi (in module cmath)](library/cmath#cmath.pi) + [(in module math)](library/math#math.pi) * [pi() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.pi) * pickle + [module](library/copy#index-0), [[1]](library/copyreg#index-0), [[2]](library/marshal#index-0), [[3]](library/shelve#index-0) * [pickle (module)](library/pickle#module-pickle) * [pickle() (in module copyreg)](library/copyreg#copyreg.pickle) * [PickleBuffer (class in pickle)](library/pickle#pickle.PickleBuffer) * [PickleError](library/pickle#pickle.PickleError) * [Pickler (class in pickle)](library/pickle#pickle.Pickler) * [pickletools (module)](library/pickletools#module-pickletools) * pickletools command line option + [--annotate](library/pickletools#cmdoption-pickletools-a) + [--indentlevel=<num>](library/pickletools#cmdoption-pickletools-l) + [--memo](library/pickletools#cmdoption-pickletools-m) + [--output=<file>](library/pickletools#cmdoption-pickletools-o) + [--preamble=<preamble>](library/pickletools#cmdoption-pickletools-p) + [-a](library/pickletools#cmdoption-pickletools-a) + [-l](library/pickletools#cmdoption-pickletools-l) + [-m](library/pickletools#cmdoption-pickletools-m) + [-o](library/pickletools#cmdoption-pickletools-o) + [-p](library/pickletools#cmdoption-pickletools-p) * pickling + [objects](library/pickle#index-0) * [PicklingError](library/pickle#pickle.PicklingError) * [pid (asyncio.subprocess.Process attribute)](library/asyncio-subprocess#asyncio.subprocess.Process.pid) + [(multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.pid) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.pid) * [pidfd\_open() (in module os)](library/os#os.pidfd_open) * [pidfd\_send\_signal() (in module signal)](library/signal#signal.pidfd_send_signal) * [PidfdChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.PidfdChildWatcher) * [PIP\_USER](https://docs.python.org/3.9/whatsnew/changelog.html#index-61) * [PIPE (in module subprocess)](library/subprocess#subprocess.PIPE) * [Pipe() (in module multiprocessing)](library/multiprocessing#multiprocessing.Pipe) * [pipe() (in module os)](library/os#os.pipe) * [pipe2() (in module os)](library/os#os.pipe2) * [PIPE\_BUF (in module select)](library/select#select.PIPE_BUF) * [pipe\_connection\_lost() (asyncio.SubprocessProtocol method)](library/asyncio-protocol#asyncio.SubprocessProtocol.pipe_connection_lost) * [pipe\_data\_received() (asyncio.SubprocessProtocol method)](library/asyncio-protocol#asyncio.SubprocessProtocol.pipe_data_received) * [PIPE\_MAX\_SIZE (in module test.support)](library/test#test.support.PIPE_MAX_SIZE) * [pipes (module)](library/pipes#module-pipes) * [PKG\_DIRECTORY (in module imp)](library/imp#imp.PKG_DIRECTORY) * [pkgutil (module)](library/pkgutil#module-pkgutil) * [placeholder (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.placeholder) * [PLAT](distutils/apiref#index-2) * [platform (in module sys)](c-api/init#index-26), [[1]](library/sys#sys.platform) + [(module)](library/platform#module-platform) * [platform() (in module platform)](library/platform#platform.platform) * [platlibdir (in module sys)](library/sys#sys.platlibdir) * [PlaySound() (in module winsound)](library/winsound#winsound.PlaySound) * plist + [file](library/plistlib#index-0) * [plistlib (module)](library/plistlib#module-plistlib) * [plock() (in module os)](library/os#os.plock) * [plus](reference/expressions#index-61) * [PLUS (in module token)](library/token#token.PLUS) * [plus() (decimal.Context method)](library/decimal#decimal.Context.plus) * [PLUSEQUAL (in module token)](library/token#token.PLUSEQUAL) * [pm() (in module pdb)](library/pdb#pdb.pm) * [POINTER() (in module ctypes)](library/ctypes#ctypes.POINTER) * [pointer() (in module ctypes)](library/ctypes#ctypes.pointer) * [polar() (in module cmath)](library/cmath#cmath.polar) * [Policy (class in email.policy)](library/email.policy#email.policy.Policy) * [poll() (in module select)](library/select#select.poll) + [(multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.poll) + [(select.devpoll method)](library/select#select.devpoll.poll) + [(select.epoll method)](library/select#select.epoll.poll) + [(select.poll method)](library/select#select.poll.poll) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.poll) * [PollSelector (class in selectors)](library/selectors#selectors.PollSelector) * [Pool (class in multiprocessing.pool)](library/multiprocessing#multiprocessing.pool.Pool) * [pop() (array.array method)](library/array#array.array.pop) + [(collections.deque method)](library/collections#collections.deque.pop) + [(dict method)](library/stdtypes#dict.pop) + [(frozenset method)](library/stdtypes#frozenset.pop) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.pop) + [(sequence method)](library/stdtypes#index-22) * POP3 + [protocol](library/poplib#index-0) * [POP3 (class in poplib)](library/poplib#poplib.POP3) * [POP3\_SSL (class in poplib)](library/poplib#poplib.POP3_SSL) * [pop\_alignment() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.pop_alignment) * [pop\_all() (contextlib.ExitStack method)](library/contextlib#contextlib.ExitStack.pop_all) * [POP\_BLOCK (opcode)](library/dis#opcode-POP_BLOCK) * [POP\_EXCEPT (opcode)](library/dis#opcode-POP_EXCEPT) * [pop\_font() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.pop_font) * [POP\_JUMP\_IF\_FALSE (opcode)](library/dis#opcode-POP_JUMP_IF_FALSE) * [POP\_JUMP\_IF\_TRUE (opcode)](library/dis#opcode-POP_JUMP_IF_TRUE) * [pop\_margin() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.pop_margin) * [pop\_source() (shlex.shlex method)](library/shlex#shlex.shlex.pop_source) * [pop\_style() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.pop_style) * [POP\_TOP (opcode)](library/dis#opcode-POP_TOP) * [Popen (class in subprocess)](library/subprocess#subprocess.Popen) * [popen() (in module os)](library/os#os.popen), [[1]](library/select#index-1), [[2]](reference/datamodel#index-53) * [popitem() (collections.OrderedDict method)](library/collections#collections.OrderedDict.popitem) + [(dict method)](library/stdtypes#dict.popitem) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.popitem) * [popleft() (collections.deque method)](library/collections#collections.deque.popleft) * [poplib (module)](library/poplib#module-poplib) * [PopupMenu (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.PopupMenu) * [port (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.port) * [port\_specified (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.port_specified) * [**portion**](glossary#term-portion) + [package](reference/import#index-5) * [pos (json.JSONDecodeError attribute)](library/json#json.JSONDecodeError.pos) + [(re.error attribute)](library/re#re.error.pos) + [(re.Match attribute)](library/re#re.Match.pos) * [pos() (in module operator)](library/operator#operator.pos) + [(in module turtle)](library/turtle#turtle.pos) * [position (xml.etree.ElementTree.ParseError attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.ParseError.position) * [position() (in module turtle)](library/turtle#turtle.position) * [**positional argument**](glossary#term-positional-argument) * POSIX + [I/O control](library/termios#index-0) + [threads](library/_thread#index-1) * [posix (module)](library/posix#module-posix) * [POSIX Shared Memory](library/multiprocessing.shared_memory#index-0) * [POSIX\_FADV\_DONTNEED (in module os)](library/os#os.POSIX_FADV_DONTNEED) * [POSIX\_FADV\_NOREUSE (in module os)](library/os#os.POSIX_FADV_NOREUSE) * [POSIX\_FADV\_NORMAL (in module os)](library/os#os.POSIX_FADV_NORMAL) * [POSIX\_FADV\_RANDOM (in module os)](library/os#os.POSIX_FADV_RANDOM) * [POSIX\_FADV\_SEQUENTIAL (in module os)](library/os#os.POSIX_FADV_SEQUENTIAL) * [POSIX\_FADV\_WILLNEED (in module os)](library/os#os.POSIX_FADV_WILLNEED) * [posix\_fadvise() (in module os)](library/os#os.posix_fadvise) * [posix\_fallocate() (in module os)](library/os#os.posix_fallocate) * [posix\_spawn() (in module os)](library/os#os.posix_spawn) * [POSIX\_SPAWN\_CLOSE (in module os)](library/os#os.POSIX_SPAWN_CLOSE) * [POSIX\_SPAWN\_DUP2 (in module os)](library/os#os.POSIX_SPAWN_DUP2) * [POSIX\_SPAWN\_OPEN (in module os)](library/os#os.POSIX_SPAWN_OPEN) * [posix\_spawnp() (in module os)](library/os#os.posix_spawnp) * [POSIXLY\_CORRECT](library/getopt#index-0) * [PosixPath (class in pathlib)](library/pathlib#pathlib.PosixPath) * [post() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.post) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.post) * [post\_handshake\_auth (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.post_handshake_auth) * [post\_mortem() (in module pdb)](library/pdb#pdb.post_mortem) * [post\_setup() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.post_setup) * [postcmd() (cmd.Cmd method)](library/cmd#cmd.Cmd.postcmd) * [postloop() (cmd.Cmd method)](library/cmd#cmd.Cmd.postloop) * pow + [built-in function](c-api/number#index-1), [[1]](c-api/number#index-3), [[2]](reference/datamodel#index-96), [[3]](reference/datamodel#index-96), [[4]](reference/datamodel#index-97), [[5]](reference/datamodel#index-98) * [Pow (class in ast)](library/ast#ast.Pow) * [pow() (built-in function)](library/functions#pow) + [(in module math)](library/math#math.pow) + [(in module operator)](library/operator#operator.pow) * power + [operation](reference/expressions#index-58) * [power() (decimal.Context method)](library/decimal#decimal.Context.power) * [pp (pdb command)](library/pdb#pdbcommand-pp) * [pp() (in module pprint)](library/pprint#pprint.pp) * [pprint (module)](library/pprint#module-pprint) * [pprint() (in module pprint)](library/pprint#pprint.pprint) + [(pprint.PrettyPrinter method)](library/pprint#pprint.PrettyPrinter.pprint) * [prcal() (in module calendar)](library/calendar#calendar.prcal) * [pread() (in module os)](library/os#os.pread) * [preadv() (in module os)](library/os#os.preadv) * [preamble (email.message.EmailMessage attribute)](library/email.message#email.message.EmailMessage.preamble) + [(email.message.Message attribute)](library/email.compat32-message#email.message.Message.preamble) * precedence + [operator](reference/expressions#index-96) * [precmd() (cmd.Cmd method)](library/cmd#cmd.Cmd.precmd) * [prefix](c-api/intro#index-1), [[1]](c-api/intro#index-3), [[2]](c-api/intro#index-4), [[3]](using/unix#index-0) * [PREFIX (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.PREFIX) * [prefix (in module sys)](library/sys#sys.prefix) + [(xml.dom.Attr attribute)](library/xml.dom#xml.dom.Attr.prefix) + [(xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.prefix) + [(zipimport.zipimporter attribute)](library/zipimport#zipimport.zipimporter.prefix) * [PREFIXES (in module site)](library/site#site.PREFIXES) * [prefixlen (ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.prefixlen) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.prefixlen) * [preloop() (cmd.Cmd method)](library/cmd#cmd.Cmd.preloop) * [prepare() (graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.prepare) + [(logging.handlers.QueueHandler method)](library/logging.handlers#logging.handlers.QueueHandler.prepare) + [(logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.prepare) * [prepare\_class() (in module types)](library/types#types.prepare_class) * [prepare\_input\_source() (in module xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.prepare_input_source) * [prepend() (pipes.Template method)](library/pipes#pipes.Template.prepend) * [preprocess() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.preprocess) * [PrettyPrinter (class in pprint)](library/pprint#pprint.PrettyPrinter) * [prev() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.prev) * [previousSibling (xml.dom.Node attribute)](library/xml.dom#xml.dom.Node.previousSibling) * [primary](reference/expressions#index-38) * print + [built-in function](reference/datamodel#index-74) * [print (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-print) * [print() (built-in function)](library/functions#print) + [\_\_str\_\_() (object method)](reference/datamodel#index-72) * [print\_callees() (pstats.Stats method)](library/profile#pstats.Stats.print_callees) * [print\_callers() (pstats.Stats method)](library/profile#pstats.Stats.print_callers) * [print\_directory() (in module cgi)](library/cgi#cgi.print_directory) * [print\_environ() (in module cgi)](library/cgi#cgi.print_environ) * [print\_environ\_usage() (in module cgi)](library/cgi#cgi.print_environ_usage) * [print\_exc() (in module traceback)](library/traceback#traceback.print_exc) + [(timeit.Timer method)](library/timeit#timeit.Timer.print_exc) * [print\_exception() (in module traceback)](library/traceback#traceback.print_exception) * [PRINT\_EXPR (opcode)](library/dis#opcode-PRINT_EXPR) * [print\_form() (in module cgi)](library/cgi#cgi.print_form) * [print\_help() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.print_help) * [print\_last() (in module traceback)](library/traceback#traceback.print_last) * [print\_stack() (asyncio.Task method)](library/asyncio-task#asyncio.Task.print_stack) + [(in module traceback)](library/traceback#traceback.print_stack) * [print\_stats() (profile.Profile method)](library/profile#profile.Profile.print_stats) + [(pstats.Stats method)](library/profile#pstats.Stats.print_stats) * [print\_tb() (in module traceback)](library/traceback#traceback.print_tb) * [print\_usage() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.print_usage) + [(optparse.OptionParser method)](library/optparse#optparse.OptionParser.print_usage) * [print\_version() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.print_version) * [print\_warning() (in module test.support)](library/test#test.support.print_warning) * [printable (in module string)](library/string#string.printable) * [printdir() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.printdir) * [printf-style formatting](library/stdtypes#index-33), [[1]](library/stdtypes#index-43) * [PRIO\_PGRP (in module os)](library/os#os.PRIO_PGRP) * [PRIO\_PROCESS (in module os)](library/os#os.PRIO_PROCESS) * [PRIO\_USER (in module os)](library/os#os.PRIO_USER) * [PriorityQueue (class in asyncio)](library/asyncio-queue#asyncio.PriorityQueue) + [(class in queue)](library/queue#queue.PriorityQueue) * private + [names](reference/expressions#index-5) * [prlimit() (in module resource)](library/resource#resource.prlimit) * [prmonth() (calendar.TextCalendar method)](library/calendar#calendar.TextCalendar.prmonth) + [(in module calendar)](library/calendar#calendar.prmonth) * [ProactorEventLoop (class in asyncio)](library/asyncio-eventloop#asyncio.ProactorEventLoop) * procedure + [call](reference/simple_stmts#index-3) * process + [group](library/os#index-3), [[1]](library/os#index-6) + [id](library/os#index-7) + [id of parent](library/os#index-8) + [killing](library/os#index-31), [[1]](library/os#index-32) + [scheduling priority](library/os#index-12), [[1]](library/os#index-9) + [signalling](library/os#index-31), [[1]](library/os#index-32) * [Process (class in multiprocessing)](library/multiprocessing#multiprocessing.Process) * [process() (logging.LoggerAdapter method)](library/logging#logging.LoggerAdapter.process) * [process\_exited() (asyncio.SubprocessProtocol method)](library/asyncio-protocol#asyncio.SubprocessProtocol.process_exited) * [process\_message() (smtpd.SMTPServer method)](library/smtpd#smtpd.SMTPServer.process_message) * [process\_request() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.process_request) * [process\_time() (in module time)](library/time#time.process_time) * [process\_time\_ns() (in module time)](library/time#time.process_time_ns) * [process\_tokens() (in module tabnanny)](library/tabnanny#tabnanny.process_tokens) * [ProcessError](library/multiprocessing#multiprocessing.ProcessError) * [processes, light-weight](library/_thread#index-0) * [ProcessingInstruction() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.ProcessingInstruction) * [processingInstruction() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.processingInstruction) * [ProcessingInstructionHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.ProcessingInstructionHandler) * [ProcessLookupError](library/exceptions#ProcessLookupError) * [processor time](library/time#index-12), [[1]](library/time#index-7) * [processor() (in module platform)](library/platform#platform.processor) * [ProcessPoolExecutor (class in concurrent.futures)](library/concurrent.futures#concurrent.futures.ProcessPoolExecutor) * [prod() (in module math)](library/math#math.prod) * [product() (in module itertools)](library/itertools#itertools.product) * [Profile (class in profile)](library/profile#profile.Profile) * [profile (module)](library/profile#module-profile) * [profile function](library/sys#index-10), [[1]](library/sys#index-27), [[2]](library/threading#index-1) * [profiler](library/sys#index-10), [[1]](library/sys#index-27) * [profiling, deterministic](library/profile#index-0) * [program](reference/toplevel_components#index-1) * [ProgrammingError](library/sqlite3#sqlite3.ProgrammingError) * [Progressbar (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Progressbar) * [prompt (cmd.Cmd attribute)](library/cmd#cmd.Cmd.prompt) * [prompt\_user\_passwd() (urllib.request.FancyURLopener method)](library/urllib.request#urllib.request.FancyURLopener.prompt_user_passwd) * [prompts, interpreter](library/sys#index-26) * [propagate (logging.Logger attribute)](library/logging#logging.Logger.propagate) * [property (built-in class)](library/functions#property) * [property list](library/plistlib#index-0) * [property\_declaration\_handler (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.property_declaration_handler) * [property\_dom\_node (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.property_dom_node) * [property\_lexical\_handler (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.property_lexical_handler) * [property\_xml\_string (in module xml.sax.handler)](library/xml.sax.handler#xml.sax.handler.property_xml_string) * [PropertyMock (class in unittest.mock)](library/unittest.mock#unittest.mock.PropertyMock) * [prot\_c() (ftplib.FTP\_TLS method)](library/ftplib#ftplib.FTP_TLS.prot_c) * [prot\_p() (ftplib.FTP\_TLS method)](library/ftplib#ftplib.FTP_TLS.prot_p) * [proto (socket.socket attribute)](library/socket#socket.socket.proto) * protocol + [CGI](library/cgi#index-0) + [context management](library/stdtypes#index-52) + [copy](library/pickle#index-5) + [FTP](library/ftplib#index-0), [[1]](library/urllib.request#index-11) + [HTTP](library/cgi#index-0), [[1]](library/http.client#index-0), [[2]](library/http#index-0), [[3]](library/http.server#index-0), [[4]](library/urllib.request#index-11), [[5]](library/urllib.request#index-12) + [IMAP4](library/imaplib#index-0) + [IMAP4\_SSL](library/imaplib#index-0) + [IMAP4\_stream](library/imaplib#index-0) + [iterator](library/stdtypes#index-17) + [NNTP](library/nntplib#index-0) + [POP3](library/poplib#index-0) + [SMTP](library/smtplib#index-0) + [Telnet](library/telnetlib#index-0) * [Protocol (class in asyncio)](library/asyncio-protocol#asyncio.Protocol) + [(class in typing)](library/typing#typing.Protocol) * [protocol (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.protocol) * [PROTOCOL\_SSLv2 (in module ssl)](library/ssl#ssl.PROTOCOL_SSLv2) * [PROTOCOL\_SSLv23 (in module ssl)](library/ssl#ssl.PROTOCOL_SSLv23) * [PROTOCOL\_SSLv3 (in module ssl)](library/ssl#ssl.PROTOCOL_SSLv3) * [PROTOCOL\_TLS (in module ssl)](library/ssl#ssl.PROTOCOL_TLS) * [PROTOCOL\_TLS\_CLIENT (in module ssl)](library/ssl#ssl.PROTOCOL_TLS_CLIENT) * [PROTOCOL\_TLS\_SERVER (in module ssl)](library/ssl#ssl.PROTOCOL_TLS_SERVER) * [PROTOCOL\_TLSv1 (in module ssl)](library/ssl#ssl.PROTOCOL_TLSv1) * [PROTOCOL\_TLSv1\_1 (in module ssl)](library/ssl#ssl.PROTOCOL_TLSv1_1) * [PROTOCOL\_TLSv1\_2 (in module ssl)](library/ssl#ssl.PROTOCOL_TLSv1_2) * [protocol\_version (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.protocol_version) * [PROTOCOL\_VERSION (imaplib.IMAP4 attribute)](library/imaplib#imaplib.IMAP4.PROTOCOL_VERSION) * [ProtocolError (class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.ProtocolError) * [**provisional API**](glossary#term-provisional-api) * [**provisional package**](glossary#term-provisional-package) * [proxy() (in module weakref)](library/weakref#weakref.proxy) * [proxyauth() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.proxyauth) * [ProxyBasicAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.ProxyBasicAuthHandler) * [ProxyDigestAuthHandler (class in urllib.request)](library/urllib.request#urllib.request.ProxyDigestAuthHandler) * [ProxyHandler (class in urllib.request)](library/urllib.request#urllib.request.ProxyHandler) * [ProxyType (in module weakref)](library/weakref#weakref.ProxyType) * [ProxyTypes (in module weakref)](library/weakref#weakref.ProxyTypes) * [pryear() (calendar.TextCalendar method)](library/calendar#calendar.TextCalendar.pryear) * [ps1 (in module sys)](library/sys#sys.ps1) * [ps2 (in module sys)](library/sys#sys.ps2) * [pstats (module)](library/profile#module-pstats) * [pstdev() (in module statistics)](library/statistics#statistics.pstdev) * [pthread\_getcpuclockid() (in module time)](library/time#time.pthread_getcpuclockid) * [pthread\_kill() (in module signal)](library/signal#signal.pthread_kill) * [pthread\_sigmask() (in module signal)](library/signal#signal.pthread_sigmask) * [pthreads](library/_thread#index-1) * pty + [module](library/os#index-17) * [pty (module)](library/pty#module-pty) * [pu() (in module turtle)](library/turtle#turtle.pu) * [publicId (xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.publicId) * [PullDom (class in xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.PullDom) * [punctuation (in module string)](library/string#string.punctuation) * [punctuation\_chars (shlex.shlex attribute)](library/shlex#shlex.shlex.punctuation_chars) * [PurePath (class in pathlib)](library/pathlib#pathlib.PurePath) * [PurePath.anchor (in module pathlib)](library/pathlib#pathlib.PurePath.anchor) * [PurePath.drive (in module pathlib)](library/pathlib#pathlib.PurePath.drive) * [PurePath.name (in module pathlib)](library/pathlib#pathlib.PurePath.name) * [PurePath.parent (in module pathlib)](library/pathlib#pathlib.PurePath.parent) * [PurePath.parents (in module pathlib)](library/pathlib#pathlib.PurePath.parents) * [PurePath.parts (in module pathlib)](library/pathlib#pathlib.PurePath.parts) * [PurePath.root (in module pathlib)](library/pathlib#pathlib.PurePath.root) * [PurePath.stem (in module pathlib)](library/pathlib#pathlib.PurePath.stem) * [PurePath.suffix (in module pathlib)](library/pathlib#pathlib.PurePath.suffix) * [PurePath.suffixes (in module pathlib)](library/pathlib#pathlib.PurePath.suffixes) * [PurePosixPath (class in pathlib)](library/pathlib#pathlib.PurePosixPath) * [PureProxy (class in smtpd)](library/smtpd#smtpd.PureProxy) * [PureWindowsPath (class in pathlib)](library/pathlib#pathlib.PureWindowsPath) * [purge() (in module re)](library/re#re.purge) * [Purpose.CLIENT\_AUTH (in module ssl)](library/ssl#ssl.Purpose.CLIENT_AUTH) * [Purpose.SERVER\_AUTH (in module ssl)](library/ssl#ssl.Purpose.SERVER_AUTH) * [push() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.push) + [(code.InteractiveConsole method)](library/code#code.InteractiveConsole.push) + [(contextlib.ExitStack method)](library/contextlib#contextlib.ExitStack.push) * [push\_alignment() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.push_alignment) * [push\_async\_callback() (contextlib.AsyncExitStack method)](library/contextlib#contextlib.AsyncExitStack.push_async_callback) * [push\_async\_exit() (contextlib.AsyncExitStack method)](library/contextlib#contextlib.AsyncExitStack.push_async_exit) * [push\_font() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.push_font) * [push\_margin() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.push_margin) * [push\_source() (shlex.shlex method)](library/shlex#shlex.shlex.push_source) * [push\_style() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.push_style) * [push\_token() (shlex.shlex method)](library/shlex#shlex.shlex.push_token) * [push\_with\_producer() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.push_with_producer) * [pushbutton() (msilib.Dialog method)](library/msilib#msilib.Dialog.pushbutton) * [put() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.put) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.put) + [(multiprocessing.SimpleQueue method)](library/multiprocessing#multiprocessing.SimpleQueue.put) + [(queue.Queue method)](library/queue#queue.Queue.put) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.put) * [put\_nowait() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.put_nowait) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.put_nowait) + [(queue.Queue method)](library/queue#queue.Queue.put_nowait) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.put_nowait) * [putch() (in module msvcrt)](library/msvcrt#msvcrt.putch) * [putenv() (in module os)](library/os#os.putenv) * [putheader() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.putheader) * [putp() (in module curses)](library/curses#curses.putp) * [putrequest() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.putrequest) * [putwch() (in module msvcrt)](library/msvcrt#msvcrt.putwch) * [putwin() (curses.window method)](library/curses#curses.window.putwin) * [pvariance() (in module statistics)](library/statistics#statistics.pvariance) * pwd + [module](library/os.path#index-2) * [pwd (module)](library/pwd#module-pwd) * [pwd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.pwd) * [pwrite() (in module os)](library/os#os.pwrite) * [pwritev() (in module os)](library/os#os.pwritev) * [Py\_ABS (C macro)](c-api/intro#c.Py_ABS) * [Py\_AddPendingCall (C function)](c-api/init#c.Py_AddPendingCall) * [Py\_AddPendingCall()](c-api/init#index-46) * [Py\_AtExit (C function)](c-api/sys#c.Py_AtExit) * [Py\_BEGIN\_ALLOW\_THREADS](c-api/init#index-36) + [(C macro)](c-api/init#c.Py_BEGIN_ALLOW_THREADS) * [Py\_BLOCK\_THREADS (C macro)](c-api/init#c.Py_BLOCK_THREADS) * [Py\_buffer (C type)](c-api/buffer#c.Py_buffer) * [Py\_buffer.buf (C member)](c-api/buffer#c.Py_buffer.buf) * [Py\_buffer.format (C member)](c-api/buffer#c.Py_buffer.format) * [Py\_buffer.internal (C member)](c-api/buffer#c.Py_buffer.internal) * [Py\_buffer.itemsize (C member)](c-api/buffer#c.Py_buffer.itemsize) * [Py\_buffer.len (C member)](c-api/buffer#c.Py_buffer.len) * [Py\_buffer.ndim (C member)](c-api/buffer#c.Py_buffer.ndim) * [Py\_buffer.obj (C member)](c-api/buffer#c.Py_buffer.obj) * [Py\_buffer.readonly (C member)](c-api/buffer#c.Py_buffer.readonly) * [Py\_buffer.shape (C member)](c-api/buffer#c.Py_buffer.shape) * [Py\_buffer.strides (C member)](c-api/buffer#c.Py_buffer.strides) * [Py\_buffer.suboffsets (C member)](c-api/buffer#c.Py_buffer.suboffsets) * [Py\_BuildValue (C function)](c-api/arg#c.Py_BuildValue) * [Py\_BytesMain (C function)](c-api/veryhigh#c.Py_BytesMain) * [Py\_BytesWarningFlag (C variable)](c-api/init#c.Py_BytesWarningFlag) * [Py\_CHARMASK (C macro)](c-api/intro#c.Py_CHARMASK) * [Py\_CLEAR (C function)](c-api/refcounting#c.Py_CLEAR) * [py\_compile (module)](library/py_compile#module-py_compile) * [PY\_COMPILED (in module imp)](library/imp#imp.PY_COMPILED) * [Py\_CompileString (C function)](c-api/veryhigh#c.Py_CompileString) * [Py\_CompileString()](c-api/veryhigh#index-0), [[1]](c-api/veryhigh#index-1), [[2]](c-api/veryhigh#index-2) * [Py\_CompileStringExFlags (C function)](c-api/veryhigh#c.Py_CompileStringExFlags) * [Py\_CompileStringFlags (C function)](c-api/veryhigh#c.Py_CompileStringFlags) * [Py\_CompileStringObject (C function)](c-api/veryhigh#c.Py_CompileStringObject) * [Py\_complex (C type)](c-api/complex#c.Py_complex) * [Py\_DebugFlag (C variable)](c-api/init#c.Py_DebugFlag) * [Py\_DecodeLocale (C function)](c-api/sys#c.Py_DecodeLocale) * [Py\_DECREF (C function)](c-api/refcounting#c.Py_DECREF) * [Py\_DECREF()](c-api/intro#index-9) * [Py\_DEPRECATED (C macro)](c-api/intro#c.Py_DEPRECATED) * [Py\_DontWriteBytecodeFlag (C variable)](c-api/init#c.Py_DontWriteBytecodeFlag) * [Py\_Ellipsis (C variable)](c-api/slice#c.Py_Ellipsis) * [Py\_EncodeLocale (C function)](c-api/sys#c.Py_EncodeLocale) * [Py\_END\_ALLOW\_THREADS](c-api/init#index-36) + [(C macro)](c-api/init#c.Py_END_ALLOW_THREADS) * [Py\_EndInterpreter (C function)](c-api/init#c.Py_EndInterpreter) * [Py\_EnterRecursiveCall (C function)](c-api/exceptions#c.Py_EnterRecursiveCall) * [Py\_eval\_input (C variable)](c-api/veryhigh#c.Py_eval_input) * [Py\_Exit (C function)](c-api/sys#c.Py_Exit) * [Py\_ExitStatusException (C function)](c-api/init_config#c.Py_ExitStatusException) * [Py\_False (C variable)](c-api/bool#c.Py_False) * [Py\_FatalError (C function)](c-api/sys#c.Py_FatalError) * [Py\_FatalError()](c-api/init#index-30) * [Py\_FdIsInteractive (C function)](c-api/sys#c.Py_FdIsInteractive) * [Py\_file\_input (C variable)](c-api/veryhigh#c.Py_file_input) * [Py\_Finalize (C function)](c-api/init#c.Py_Finalize) * [Py\_FinalizeEx (C function)](c-api/init#c.Py_FinalizeEx) * [Py\_FinalizeEx()](c-api/init#index-16), [[1]](c-api/init#index-43), [[2]](c-api/init#index-45), [[3]](c-api/sys#index-2), [[4]](c-api/sys#index-3) * [PY\_FROZEN (in module imp)](library/imp#imp.PY_FROZEN) * [Py\_FrozenFlag (C variable)](c-api/init#c.Py_FrozenFlag) * [Py\_GenericAlias (C function)](c-api/typehints#c.Py_GenericAlias) * [Py\_GenericAliasType (C variable)](c-api/typehints#c.Py_GenericAliasType) * [Py\_GetArgcArgv (C function)](c-api/init_config#c.Py_GetArgcArgv) * [Py\_GetBuildInfo (C function)](c-api/init#c.Py_GetBuildInfo) * [Py\_GetCompiler (C function)](c-api/init#c.Py_GetCompiler) * [Py\_GetCopyright (C function)](c-api/init#c.Py_GetCopyright) * [Py\_GETENV (C macro)](c-api/intro#c.Py_GETENV) * [Py\_GetExecPrefix (C function)](c-api/init#c.Py_GetExecPrefix) * [Py\_GetExecPrefix()](c-api/intro#index-29) * [Py\_GetPath (C function)](c-api/init#c.Py_GetPath) * [Py\_GetPath()](c-api/init#index-20), [[1]](c-api/init#index-24), [[2]](c-api/intro#index-29) * [Py\_GetPlatform (C function)](c-api/init#c.Py_GetPlatform) * [Py\_GetPrefix (C function)](c-api/init#c.Py_GetPrefix) * [Py\_GetPrefix()](c-api/intro#index-29) * [Py\_GetProgramFullPath (C function)](c-api/init#c.Py_GetProgramFullPath) * [Py\_GetProgramFullPath()](c-api/intro#index-29) * [Py\_GetProgramName (C function)](c-api/init#c.Py_GetProgramName) * [Py\_GetPythonHome (C function)](c-api/init#c.Py_GetPythonHome) * [Py\_GetVersion (C function)](c-api/init#c.Py_GetVersion) * [Py\_HashRandomizationFlag (C variable)](c-api/init#c.Py_HashRandomizationFlag) * [Py\_IgnoreEnvironmentFlag (C variable)](c-api/init#c.Py_IgnoreEnvironmentFlag) * [Py\_INCREF (C function)](c-api/refcounting#c.Py_INCREF) * [Py\_INCREF()](c-api/intro#index-9) * [Py\_Initialize (C function)](c-api/init#c.Py_Initialize) * [Py\_Initialize()](c-api/init#index-17), [[1]](c-api/init#index-20), [[2]](c-api/init#index-43), [[3]](c-api/intro#index-23) * [Py\_InitializeEx (C function)](c-api/init#c.Py_InitializeEx) * [Py\_InitializeFromConfig (C function)](c-api/init_config#c.Py_InitializeFromConfig) * [Py\_InspectFlag (C variable)](c-api/init#c.Py_InspectFlag) * [Py\_InteractiveFlag (C variable)](c-api/init#c.Py_InteractiveFlag) * [Py\_IS\_TYPE (C function)](c-api/structures#c.Py_IS_TYPE) * [Py\_IsInitialized (C function)](c-api/init#c.Py_IsInitialized) * [Py\_IsInitialized()](c-api/intro#index-32) * [Py\_IsolatedFlag (C variable)](c-api/init#c.Py_IsolatedFlag) * [Py\_LeaveRecursiveCall (C function)](c-api/exceptions#c.Py_LeaveRecursiveCall) * [Py\_LegacyWindowsFSEncodingFlag (C variable)](c-api/init#c.Py_LegacyWindowsFSEncodingFlag) * [Py\_LegacyWindowsStdioFlag (C variable)](c-api/init#c.Py_LegacyWindowsStdioFlag) * [Py\_Main (C function)](c-api/veryhigh#c.Py_Main) * [Py\_MAX (C macro)](c-api/intro#c.Py_MAX) * [Py\_MEMBER\_SIZE (C macro)](c-api/intro#c.Py_MEMBER_SIZE) * [Py\_MIN (C macro)](c-api/intro#c.Py_MIN) * [Py\_mod\_create (C macro)](c-api/module#c.Py_mod_create) * [Py\_mod\_exec (C macro)](c-api/module#c.Py_mod_exec) * [Py\_NewInterpreter (C function)](c-api/init#c.Py_NewInterpreter) * [Py\_None (C variable)](c-api/none#c.Py_None) * [Py\_NoSiteFlag (C variable)](c-api/init#c.Py_NoSiteFlag) * [Py\_NotImplemented (C variable)](c-api/object#c.Py_NotImplemented) * [Py\_NoUserSiteDirectory (C variable)](c-api/init#c.Py_NoUserSiteDirectory) * [py\_object (class in ctypes)](library/ctypes#ctypes.py_object) * [Py\_OptimizeFlag (C variable)](c-api/init#c.Py_OptimizeFlag) * [Py\_PreInitialize (C function)](c-api/init_config#c.Py_PreInitialize) * [Py\_PreInitializeFromArgs (C function)](c-api/init_config#c.Py_PreInitializeFromArgs) * [Py\_PreInitializeFromBytesArgs (C function)](c-api/init_config#c.Py_PreInitializeFromBytesArgs) * [Py\_PRINT\_RAW](c-api/file#index-2) * [PY\_PYTHON](using/windows#index-20) * [Py\_QuietFlag (C variable)](c-api/init#c.Py_QuietFlag) * [Py\_REFCNT (C macro)](c-api/structures#c.Py_REFCNT) * [Py\_ReprEnter (C function)](c-api/exceptions#c.Py_ReprEnter) * [Py\_ReprLeave (C function)](c-api/exceptions#c.Py_ReprLeave) * [Py\_RETURN\_FALSE (C macro)](c-api/bool#c.Py_RETURN_FALSE) * [Py\_RETURN\_NONE (C macro)](c-api/none#c.Py_RETURN_NONE) * [Py\_RETURN\_NOTIMPLEMENTED (C macro)](c-api/object#c.Py_RETURN_NOTIMPLEMENTED) * [Py\_RETURN\_RICHCOMPARE (C macro)](c-api/typeobj#c.Py_RETURN_RICHCOMPARE) * [Py\_RETURN\_TRUE (C macro)](c-api/bool#c.Py_RETURN_TRUE) * [Py\_RunMain (C function)](c-api/init_config#c.Py_RunMain) * [Py\_SET\_REFCNT (C function)](c-api/structures#c.Py_SET_REFCNT) * [Py\_SET\_SIZE (C function)](c-api/structures#c.Py_SET_SIZE) * [Py\_SET\_TYPE (C function)](c-api/structures#c.Py_SET_TYPE) * [Py\_SetPath (C function)](c-api/init#c.Py_SetPath) * [Py\_SetPath()](c-api/init#index-23) * [Py\_SetProgramName (C function)](c-api/init#c.Py_SetProgramName) * [Py\_SetProgramName()](c-api/init#index-16), [[1]](c-api/init#index-21), [[2]](c-api/init#index-22), [[3]](c-api/intro#index-29) * [Py\_SetPythonHome (C function)](c-api/init#c.Py_SetPythonHome) * [Py\_SetStandardStreamEncoding (C function)](c-api/init#c.Py_SetStandardStreamEncoding) * [Py\_single\_input (C variable)](c-api/veryhigh#c.Py_single_input) * [Py\_SIZE (C macro)](c-api/structures#c.Py_SIZE) * [PY\_SOURCE (in module imp)](library/imp#imp.PY_SOURCE) * [Py\_ssize\_t (C type)](c-api/intro#c.Py_ssize_t) * [PY\_SSIZE\_T\_MAX](c-api/long#index-3) * [Py\_STRINGIFY (C macro)](c-api/intro#c.Py_STRINGIFY) * [Py\_TPFLAGS\_BASE\_EXC\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_BASE_EXC_SUBCLASS) * [Py\_TPFLAGS\_BASETYPE (built-in variable)](c-api/typeobj#Py_TPFLAGS_BASETYPE) * [Py\_TPFLAGS\_BYTES\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_BYTES_SUBCLASS) * [Py\_TPFLAGS\_DEFAULT (built-in variable)](c-api/typeobj#Py_TPFLAGS_DEFAULT) * [Py\_TPFLAGS\_DICT\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_DICT_SUBCLASS) * [Py\_TPFLAGS\_HAVE\_FINALIZE (built-in variable)](c-api/typeobj#Py_TPFLAGS_HAVE_FINALIZE) * [Py\_TPFLAGS\_HAVE\_GC (built-in variable)](c-api/typeobj#Py_TPFLAGS_HAVE_GC) * [Py\_TPFLAGS\_HAVE\_VECTORCALL (built-in variable)](c-api/typeobj#Py_TPFLAGS_HAVE_VECTORCALL) * [Py\_TPFLAGS\_HEAPTYPE (built-in variable)](c-api/typeobj#Py_TPFLAGS_HEAPTYPE) * [Py\_TPFLAGS\_LIST\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_LIST_SUBCLASS) * [Py\_TPFLAGS\_LONG\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_LONG_SUBCLASS) * [Py\_TPFLAGS\_METHOD\_DESCRIPTOR (built-in variable)](c-api/typeobj#Py_TPFLAGS_METHOD_DESCRIPTOR) * [Py\_TPFLAGS\_READY (built-in variable)](c-api/typeobj#Py_TPFLAGS_READY) * [Py\_TPFLAGS\_READYING (built-in variable)](c-api/typeobj#Py_TPFLAGS_READYING) * [Py\_TPFLAGS\_TUPLE\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_TUPLE_SUBCLASS) * [Py\_TPFLAGS\_TYPE\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_TYPE_SUBCLASS) * [Py\_TPFLAGS\_UNICODE\_SUBCLASS (built-in variable)](c-api/typeobj#Py_TPFLAGS_UNICODE_SUBCLASS) * [Py\_tracefunc (C type)](c-api/init#c.Py_tracefunc) * [Py\_True (C variable)](c-api/bool#c.Py_True) * [Py\_tss\_NEEDS\_INIT (C macro)](c-api/init#c.Py_tss_NEEDS_INIT) * [Py\_tss\_t (C type)](c-api/init#c.Py_tss_t) * [Py\_TYPE (C macro)](c-api/structures#c.Py_TYPE) * [Py\_UCS1 (C type)](c-api/unicode#c.Py_UCS1) * [Py\_UCS2 (C type)](c-api/unicode#c.Py_UCS2) * [Py\_UCS4 (C type)](c-api/unicode#c.Py_UCS4) * [Py\_UNBLOCK\_THREADS (C macro)](c-api/init#c.Py_UNBLOCK_THREADS) * [Py\_UnbufferedStdioFlag (C variable)](c-api/init#c.Py_UnbufferedStdioFlag) * [Py\_UNICODE (C type)](c-api/unicode#c.Py_UNICODE) * [Py\_UNICODE\_IS\_HIGH\_SURROGATE (C macro)](c-api/unicode#c.Py_UNICODE_IS_HIGH_SURROGATE) * [Py\_UNICODE\_IS\_LOW\_SURROGATE (C macro)](c-api/unicode#c.Py_UNICODE_IS_LOW_SURROGATE) * [Py\_UNICODE\_IS\_SURROGATE (C macro)](c-api/unicode#c.Py_UNICODE_IS_SURROGATE) * [Py\_UNICODE\_ISALNUM (C function)](c-api/unicode#c.Py_UNICODE_ISALNUM) * [Py\_UNICODE\_ISALPHA (C function)](c-api/unicode#c.Py_UNICODE_ISALPHA) * [Py\_UNICODE\_ISDECIMAL (C function)](c-api/unicode#c.Py_UNICODE_ISDECIMAL) * [Py\_UNICODE\_ISDIGIT (C function)](c-api/unicode#c.Py_UNICODE_ISDIGIT) * [Py\_UNICODE\_ISLINEBREAK (C function)](c-api/unicode#c.Py_UNICODE_ISLINEBREAK) * [Py\_UNICODE\_ISLOWER (C function)](c-api/unicode#c.Py_UNICODE_ISLOWER) * [Py\_UNICODE\_ISNUMERIC (C function)](c-api/unicode#c.Py_UNICODE_ISNUMERIC) * [Py\_UNICODE\_ISPRINTABLE (C function)](c-api/unicode#c.Py_UNICODE_ISPRINTABLE) * [Py\_UNICODE\_ISSPACE (C function)](c-api/unicode#c.Py_UNICODE_ISSPACE) * [Py\_UNICODE\_ISTITLE (C function)](c-api/unicode#c.Py_UNICODE_ISTITLE) * [Py\_UNICODE\_ISUPPER (C function)](c-api/unicode#c.Py_UNICODE_ISUPPER) * [Py\_UNICODE\_JOIN\_SURROGATES (C macro)](c-api/unicode#c.Py_UNICODE_JOIN_SURROGATES) * [Py\_UNICODE\_TODECIMAL (C function)](c-api/unicode#c.Py_UNICODE_TODECIMAL) * [Py\_UNICODE\_TODIGIT (C function)](c-api/unicode#c.Py_UNICODE_TODIGIT) * [Py\_UNICODE\_TOLOWER (C function)](c-api/unicode#c.Py_UNICODE_TOLOWER) * [Py\_UNICODE\_TONUMERIC (C function)](c-api/unicode#c.Py_UNICODE_TONUMERIC) * [Py\_UNICODE\_TOTITLE (C function)](c-api/unicode#c.Py_UNICODE_TOTITLE) * [Py\_UNICODE\_TOUPPER (C function)](c-api/unicode#c.Py_UNICODE_TOUPPER) * [Py\_UNREACHABLE (C macro)](c-api/intro#c.Py_UNREACHABLE) * [Py\_UNUSED (C macro)](c-api/intro#c.Py_UNUSED) * [Py\_VaBuildValue (C function)](c-api/arg#c.Py_VaBuildValue) * [PY\_VECTORCALL\_ARGUMENTS\_OFFSET (C macro)](c-api/call#c.PY_VECTORCALL_ARGUMENTS_OFFSET) * [Py\_VerboseFlag (C variable)](c-api/init#c.Py_VerboseFlag) * [Py\_VISIT (C function)](c-api/gcsupport#c.Py_VISIT) * [Py\_XDECREF (C function)](c-api/refcounting#c.Py_XDECREF) * [Py\_XDECREF()](c-api/intro#index-22) * [Py\_XINCREF (C function)](c-api/refcounting#c.Py_XINCREF) * [PyAnySet\_Check (C function)](c-api/set#c.PyAnySet_Check) * [PyAnySet\_CheckExact (C function)](c-api/set#c.PyAnySet_CheckExact) * [PyArg\_Parse (C function)](c-api/arg#c.PyArg_Parse) * [PyArg\_ParseTuple (C function)](c-api/arg#c.PyArg_ParseTuple) * [PyArg\_ParseTuple()](extending/extending#index-2) * [PyArg\_ParseTupleAndKeywords (C function)](c-api/arg#c.PyArg_ParseTupleAndKeywords) * [PyArg\_ParseTupleAndKeywords()](extending/extending#index-3) * [PyArg\_UnpackTuple (C function)](c-api/arg#c.PyArg_UnpackTuple) * [PyArg\_ValidateKeywordArguments (C function)](c-api/arg#c.PyArg_ValidateKeywordArguments) * [PyArg\_VaParse (C function)](c-api/arg#c.PyArg_VaParse) * [PyArg\_VaParseTupleAndKeywords (C function)](c-api/arg#c.PyArg_VaParseTupleAndKeywords) * [PyASCIIObject (C type)](c-api/unicode#c.PyASCIIObject) * [PyAsyncMethods (C type)](c-api/typeobj#c.PyAsyncMethods) * [PyAsyncMethods.am\_aiter (C member)](c-api/typeobj#c.PyAsyncMethods.am_aiter) * [PyAsyncMethods.am\_anext (C member)](c-api/typeobj#c.PyAsyncMethods.am_anext) * [PyAsyncMethods.am\_await (C member)](c-api/typeobj#c.PyAsyncMethods.am_await) * [PyBool\_Check (C function)](c-api/bool#c.PyBool_Check) * [PyBool\_FromLong (C function)](c-api/bool#c.PyBool_FromLong) * [PyBUF\_ANY\_CONTIGUOUS (C macro)](c-api/buffer#c.PyBUF_ANY_CONTIGUOUS) * [PyBUF\_C\_CONTIGUOUS (C macro)](c-api/buffer#c.PyBUF_C_CONTIGUOUS) * [PyBUF\_CONTIG (C macro)](c-api/buffer#c.PyBUF_CONTIG) * [PyBUF\_CONTIG\_RO (C macro)](c-api/buffer#c.PyBUF_CONTIG_RO) * [PyBUF\_F\_CONTIGUOUS (C macro)](c-api/buffer#c.PyBUF_F_CONTIGUOUS) * [PyBUF\_FORMAT (C macro)](c-api/buffer#c.PyBUF_FORMAT) * [PyBUF\_FULL (C macro)](c-api/buffer#c.PyBUF_FULL) * [PyBUF\_FULL\_RO (C macro)](c-api/buffer#c.PyBUF_FULL_RO) * [PyBUF\_INDIRECT (C macro)](c-api/buffer#c.PyBUF_INDIRECT) * [PyBUF\_ND (C macro)](c-api/buffer#c.PyBUF_ND) * [PyBUF\_RECORDS (C macro)](c-api/buffer#c.PyBUF_RECORDS) * [PyBUF\_RECORDS\_RO (C macro)](c-api/buffer#c.PyBUF_RECORDS_RO) * [PyBUF\_SIMPLE (C macro)](c-api/buffer#c.PyBUF_SIMPLE) * [PyBUF\_STRIDED (C macro)](c-api/buffer#c.PyBUF_STRIDED) * [PyBUF\_STRIDED\_RO (C macro)](c-api/buffer#c.PyBUF_STRIDED_RO) * [PyBUF\_STRIDES (C macro)](c-api/buffer#c.PyBUF_STRIDES) * [PyBUF\_WRITABLE (C macro)](c-api/buffer#c.PyBUF_WRITABLE) * [PyBuffer\_FillContiguousStrides (C function)](c-api/buffer#c.PyBuffer_FillContiguousStrides) * [PyBuffer\_FillInfo (C function)](c-api/buffer#c.PyBuffer_FillInfo) * [PyBuffer\_FromContiguous (C function)](c-api/buffer#c.PyBuffer_FromContiguous) * [PyBuffer\_GetPointer (C function)](c-api/buffer#c.PyBuffer_GetPointer) * [PyBuffer\_IsContiguous (C function)](c-api/buffer#c.PyBuffer_IsContiguous) * [PyBuffer\_Release (C function)](c-api/buffer#c.PyBuffer_Release) * [PyBuffer\_SizeFromFormat (C function)](c-api/buffer#c.PyBuffer_SizeFromFormat) * [PyBuffer\_ToContiguous (C function)](c-api/buffer#c.PyBuffer_ToContiguous) * [PyBufferProcs](c-api/buffer#index-1) + [(C type)](c-api/typeobj#c.PyBufferProcs) * [PyBufferProcs.bf\_getbuffer (C member)](c-api/typeobj#c.PyBufferProcs.bf_getbuffer) * [PyBufferProcs.bf\_releasebuffer (C member)](c-api/typeobj#c.PyBufferProcs.bf_releasebuffer) * [PyByteArray\_AS\_STRING (C function)](c-api/bytearray#c.PyByteArray_AS_STRING) * [PyByteArray\_AsString (C function)](c-api/bytearray#c.PyByteArray_AsString) * [PyByteArray\_Check (C function)](c-api/bytearray#c.PyByteArray_Check) * [PyByteArray\_CheckExact (C function)](c-api/bytearray#c.PyByteArray_CheckExact) * [PyByteArray\_Concat (C function)](c-api/bytearray#c.PyByteArray_Concat) * [PyByteArray\_FromObject (C function)](c-api/bytearray#c.PyByteArray_FromObject) * [PyByteArray\_FromStringAndSize (C function)](c-api/bytearray#c.PyByteArray_FromStringAndSize) * [PyByteArray\_GET\_SIZE (C function)](c-api/bytearray#c.PyByteArray_GET_SIZE) * [PyByteArray\_Resize (C function)](c-api/bytearray#c.PyByteArray_Resize) * [PyByteArray\_Size (C function)](c-api/bytearray#c.PyByteArray_Size) * [PyByteArray\_Type (C variable)](c-api/bytearray#c.PyByteArray_Type) * [PyByteArrayObject (C type)](c-api/bytearray#c.PyByteArrayObject) * [PyBytes\_AS\_STRING (C function)](c-api/bytes#c.PyBytes_AS_STRING) * [PyBytes\_AsString (C function)](c-api/bytes#c.PyBytes_AsString) * [PyBytes\_AsStringAndSize (C function)](c-api/bytes#c.PyBytes_AsStringAndSize) * [PyBytes\_Check (C function)](c-api/bytes#c.PyBytes_Check) * [PyBytes\_CheckExact (C function)](c-api/bytes#c.PyBytes_CheckExact) * [PyBytes\_Concat (C function)](c-api/bytes#c.PyBytes_Concat) * [PyBytes\_ConcatAndDel (C function)](c-api/bytes#c.PyBytes_ConcatAndDel) * [PyBytes\_FromFormat (C function)](c-api/bytes#c.PyBytes_FromFormat) * [PyBytes\_FromFormatV (C function)](c-api/bytes#c.PyBytes_FromFormatV) * [PyBytes\_FromObject (C function)](c-api/bytes#c.PyBytes_FromObject) * [PyBytes\_FromString (C function)](c-api/bytes#c.PyBytes_FromString) * [PyBytes\_FromStringAndSize (C function)](c-api/bytes#c.PyBytes_FromStringAndSize) * [PyBytes\_GET\_SIZE (C function)](c-api/bytes#c.PyBytes_GET_SIZE) * [PyBytes\_Size (C function)](c-api/bytes#c.PyBytes_Size) * [PyBytes\_Type (C variable)](c-api/bytes#c.PyBytes_Type) * [PyBytesObject (C type)](c-api/bytes#c.PyBytesObject) * [pycache\_prefix (in module sys)](library/sys#sys.pycache_prefix) * [PyCallable\_Check (C function)](c-api/call#c.PyCallable_Check) * [PyCallIter\_Check (C function)](c-api/iterator#c.PyCallIter_Check) * [PyCallIter\_New (C function)](c-api/iterator#c.PyCallIter_New) * [PyCallIter\_Type (C variable)](c-api/iterator#c.PyCallIter_Type) * [PyCapsule (C type)](c-api/capsule#c.PyCapsule) * [PyCapsule\_CheckExact (C function)](c-api/capsule#c.PyCapsule_CheckExact) * [PyCapsule\_Destructor (C type)](c-api/capsule#c.PyCapsule_Destructor) * [PyCapsule\_GetContext (C function)](c-api/capsule#c.PyCapsule_GetContext) * [PyCapsule\_GetDestructor (C function)](c-api/capsule#c.PyCapsule_GetDestructor) * [PyCapsule\_GetName (C function)](c-api/capsule#c.PyCapsule_GetName) * [PyCapsule\_GetPointer (C function)](c-api/capsule#c.PyCapsule_GetPointer) * [PyCapsule\_Import (C function)](c-api/capsule#c.PyCapsule_Import) * [PyCapsule\_IsValid (C function)](c-api/capsule#c.PyCapsule_IsValid) * [PyCapsule\_New (C function)](c-api/capsule#c.PyCapsule_New) * [PyCapsule\_SetContext (C function)](c-api/capsule#c.PyCapsule_SetContext) * [PyCapsule\_SetDestructor (C function)](c-api/capsule#c.PyCapsule_SetDestructor) * [PyCapsule\_SetName (C function)](c-api/capsule#c.PyCapsule_SetName) * [PyCapsule\_SetPointer (C function)](c-api/capsule#c.PyCapsule_SetPointer) * [PyCell\_Check (C function)](c-api/cell#c.PyCell_Check) * [PyCell\_GET (C function)](c-api/cell#c.PyCell_GET) * [PyCell\_Get (C function)](c-api/cell#c.PyCell_Get) * [PyCell\_New (C function)](c-api/cell#c.PyCell_New) * [PyCell\_SET (C function)](c-api/cell#c.PyCell_SET) * [PyCell\_Set (C function)](c-api/cell#c.PyCell_Set) * [PyCell\_Type (C variable)](c-api/cell#c.PyCell_Type) * [PyCellObject (C type)](c-api/cell#c.PyCellObject) * [PyCF\_ALLOW\_TOP\_LEVEL\_AWAIT (in module ast)](library/ast#ast.PyCF_ALLOW_TOP_LEVEL_AWAIT) * [PyCF\_ONLY\_AST (in module ast)](library/ast#ast.PyCF_ONLY_AST) * [PyCF\_TYPE\_COMMENTS (in module ast)](library/ast#ast.PyCF_TYPE_COMMENTS) * [PyCFunction (C type)](c-api/structures#c.PyCFunction) * [PyCFunctionWithKeywords (C type)](c-api/structures#c.PyCFunctionWithKeywords) * [PycInvalidationMode (class in py\_compile)](library/py_compile#py_compile.PycInvalidationMode) * [pyclbr (module)](library/pyclbr#module-pyclbr) * [PyCMethod (C type)](c-api/structures#c.PyCMethod) * [PyCode\_Check (C function)](c-api/code#c.PyCode_Check) * [PyCode\_GetNumFree (C function)](c-api/code#c.PyCode_GetNumFree) * [PyCode\_New (C function)](c-api/code#c.PyCode_New) * [PyCode\_NewEmpty (C function)](c-api/code#c.PyCode_NewEmpty) * [PyCode\_NewWithPosOnlyArgs (C function)](c-api/code#c.PyCode_NewWithPosOnlyArgs) * [PyCode\_Type (C variable)](c-api/code#c.PyCode_Type) * [PyCodec\_BackslashReplaceErrors (C function)](c-api/codec#c.PyCodec_BackslashReplaceErrors) * [PyCodec\_Decode (C function)](c-api/codec#c.PyCodec_Decode) * [PyCodec\_Decoder (C function)](c-api/codec#c.PyCodec_Decoder) * [PyCodec\_Encode (C function)](c-api/codec#c.PyCodec_Encode) * [PyCodec\_Encoder (C function)](c-api/codec#c.PyCodec_Encoder) * [PyCodec\_IgnoreErrors (C function)](c-api/codec#c.PyCodec_IgnoreErrors) * [PyCodec\_IncrementalDecoder (C function)](c-api/codec#c.PyCodec_IncrementalDecoder) * [PyCodec\_IncrementalEncoder (C function)](c-api/codec#c.PyCodec_IncrementalEncoder) * [PyCodec\_KnownEncoding (C function)](c-api/codec#c.PyCodec_KnownEncoding) * [PyCodec\_LookupError (C function)](c-api/codec#c.PyCodec_LookupError) * [PyCodec\_NameReplaceErrors (C function)](c-api/codec#c.PyCodec_NameReplaceErrors) * [PyCodec\_Register (C function)](c-api/codec#c.PyCodec_Register) * [PyCodec\_RegisterError (C function)](c-api/codec#c.PyCodec_RegisterError) * [PyCodec\_ReplaceErrors (C function)](c-api/codec#c.PyCodec_ReplaceErrors) * [PyCodec\_StreamReader (C function)](c-api/codec#c.PyCodec_StreamReader) * [PyCodec\_StreamWriter (C function)](c-api/codec#c.PyCodec_StreamWriter) * [PyCodec\_StrictErrors (C function)](c-api/codec#c.PyCodec_StrictErrors) * [PyCodec\_XMLCharRefReplaceErrors (C function)](c-api/codec#c.PyCodec_XMLCharRefReplaceErrors) * [PyCodeObject (C type)](c-api/code#c.PyCodeObject) * [PyCompactUnicodeObject (C type)](c-api/unicode#c.PyCompactUnicodeObject) * [PyCompileError](library/py_compile#py_compile.PyCompileError) * [PyCompilerFlags (C type)](c-api/veryhigh#c.PyCompilerFlags) * [PyCompilerFlags.cf\_feature\_version (C member)](c-api/veryhigh#c.PyCompilerFlags.cf_feature_version) * [PyCompilerFlags.cf\_flags (C member)](c-api/veryhigh#c.PyCompilerFlags.cf_flags) * [PyComplex\_AsCComplex (C function)](c-api/complex#c.PyComplex_AsCComplex) * [PyComplex\_Check (C function)](c-api/complex#c.PyComplex_Check) * [PyComplex\_CheckExact (C function)](c-api/complex#c.PyComplex_CheckExact) * [PyComplex\_FromCComplex (C function)](c-api/complex#c.PyComplex_FromCComplex) * [PyComplex\_FromDoubles (C function)](c-api/complex#c.PyComplex_FromDoubles) * [PyComplex\_ImagAsDouble (C function)](c-api/complex#c.PyComplex_ImagAsDouble) * [PyComplex\_RealAsDouble (C function)](c-api/complex#c.PyComplex_RealAsDouble) * [PyComplex\_Type (C variable)](c-api/complex#c.PyComplex_Type) * [PyComplexObject (C type)](c-api/complex#c.PyComplexObject) * [PyConfig (C type)](c-api/init_config#c.PyConfig) * [PyConfig.\_use\_peg\_parser (C member)](c-api/init_config#c.PyConfig._use_peg_parser) * [PyConfig.argv (C member)](c-api/init_config#c.PyConfig.argv) * [PyConfig.base\_exec\_prefix (C member)](c-api/init_config#c.PyConfig.base_exec_prefix) * [PyConfig.base\_executable (C member)](c-api/init_config#c.PyConfig.base_executable) * [PyConfig.base\_prefix (C member)](c-api/init_config#c.PyConfig.base_prefix) * [PyConfig.buffered\_stdio (C member)](c-api/init_config#c.PyConfig.buffered_stdio) * [PyConfig.bytes\_warning (C member)](c-api/init_config#c.PyConfig.bytes_warning) * [PyConfig.check\_hash\_pycs\_mode (C member)](c-api/init_config#c.PyConfig.check_hash_pycs_mode) * [PyConfig.configure\_c\_stdio (C member)](c-api/init_config#c.PyConfig.configure_c_stdio) * [PyConfig.dev\_mode (C member)](c-api/init_config#c.PyConfig.dev_mode) * [PyConfig.dump\_refs (C member)](c-api/init_config#c.PyConfig.dump_refs) * [PyConfig.exec\_prefix (C member)](c-api/init_config#c.PyConfig.exec_prefix) * [PyConfig.executable (C member)](c-api/init_config#c.PyConfig.executable) * [PyConfig.faulthandler (C member)](c-api/init_config#c.PyConfig.faulthandler) * [PyConfig.filesystem\_encoding (C member)](c-api/init_config#c.PyConfig.filesystem_encoding) * [PyConfig.filesystem\_errors (C member)](c-api/init_config#c.PyConfig.filesystem_errors) * [PyConfig.hash\_seed (C member)](c-api/init_config#c.PyConfig.hash_seed) * [PyConfig.home (C member)](c-api/init_config#c.PyConfig.home) * [PyConfig.import\_time (C member)](c-api/init_config#c.PyConfig.import_time) * [PyConfig.inspect (C member)](c-api/init_config#c.PyConfig.inspect) * [PyConfig.install\_signal\_handlers (C member)](c-api/init_config#c.PyConfig.install_signal_handlers) * [PyConfig.interactive (C member)](c-api/init_config#c.PyConfig.interactive) * [PyConfig.isolated (C member)](c-api/init_config#c.PyConfig.isolated) * [PyConfig.legacy\_windows\_stdio (C member)](c-api/init_config#c.PyConfig.legacy_windows_stdio) * [PyConfig.malloc\_stats (C member)](c-api/init_config#c.PyConfig.malloc_stats) * [PyConfig.module\_search\_paths (C member)](c-api/init_config#c.PyConfig.module_search_paths) * [PyConfig.module\_search\_paths\_set (C member)](c-api/init_config#c.PyConfig.module_search_paths_set) * [PyConfig.optimization\_level (C member)](c-api/init_config#c.PyConfig.optimization_level) * [PyConfig.parse\_argv (C member)](c-api/init_config#c.PyConfig.parse_argv) * [PyConfig.parser\_debug (C member)](c-api/init_config#c.PyConfig.parser_debug) * [PyConfig.pathconfig\_warnings (C member)](c-api/init_config#c.PyConfig.pathconfig_warnings) * [PyConfig.platlibdir (C member)](c-api/init_config#c.PyConfig.platlibdir) * [PyConfig.prefix (C member)](c-api/init_config#c.PyConfig.prefix) * [PyConfig.program\_name (C member)](c-api/init_config#c.PyConfig.program_name) * [PyConfig.pycache\_prefix (C member)](c-api/init_config#c.PyConfig.pycache_prefix) * [PyConfig.pythonpath\_env (C member)](c-api/init_config#c.PyConfig.pythonpath_env) * [PyConfig.quiet (C member)](c-api/init_config#c.PyConfig.quiet) * [PyConfig.run\_command (C member)](c-api/init_config#c.PyConfig.run_command) * [PyConfig.run\_filename (C member)](c-api/init_config#c.PyConfig.run_filename) * [PyConfig.run\_module (C member)](c-api/init_config#c.PyConfig.run_module) * [PyConfig.show\_ref\_count (C member)](c-api/init_config#c.PyConfig.show_ref_count) * [PyConfig.site\_import (C member)](c-api/init_config#c.PyConfig.site_import) * [PyConfig.skip\_source\_first\_line (C member)](c-api/init_config#c.PyConfig.skip_source_first_line) * [PyConfig.stdio\_encoding (C member)](c-api/init_config#c.PyConfig.stdio_encoding) * [PyConfig.stdio\_errors (C member)](c-api/init_config#c.PyConfig.stdio_errors) * [PyConfig.tracemalloc (C member)](c-api/init_config#c.PyConfig.tracemalloc) * [PyConfig.use\_environment (C member)](c-api/init_config#c.PyConfig.use_environment) * [PyConfig.use\_hash\_seed (C member)](c-api/init_config#c.PyConfig.use_hash_seed) * [PyConfig.user\_site\_directory (C member)](c-api/init_config#c.PyConfig.user_site_directory) * [PyConfig.verbose (C member)](c-api/init_config#c.PyConfig.verbose) * [PyConfig.warnoptions (C member)](c-api/init_config#c.PyConfig.warnoptions) * [PyConfig.write\_bytecode (C member)](c-api/init_config#c.PyConfig.write_bytecode) * [PyConfig.xoptions (C member)](c-api/init_config#c.PyConfig.xoptions) * [PyConfig\_Clear (C function)](c-api/init_config#c.PyConfig_Clear) * [PyConfig\_InitIsolatedConfig (C function)](c-api/init_config#c.PyConfig_InitIsolatedConfig) * [PyConfig\_InitPythonConfig (C function)](c-api/init_config#c.PyConfig_InitPythonConfig) * [PyConfig\_Read (C function)](c-api/init_config#c.PyConfig_Read) * [PyConfig\_SetArgv (C function)](c-api/init_config#c.PyConfig_SetArgv) * [PyConfig\_SetBytesArgv (C function)](c-api/init_config#c.PyConfig_SetBytesArgv) * [PyConfig\_SetBytesString (C function)](c-api/init_config#c.PyConfig_SetBytesString) * [PyConfig\_SetString (C function)](c-api/init_config#c.PyConfig_SetString) * [PyConfig\_SetWideStringList (C function)](c-api/init_config#c.PyConfig_SetWideStringList) * [PyContext (C type)](c-api/contextvars#c.PyContext) * [PyContext\_CheckExact (C function)](c-api/contextvars#c.PyContext_CheckExact) * [PyContext\_Copy (C function)](c-api/contextvars#c.PyContext_Copy) * [PyContext\_CopyCurrent (C function)](c-api/contextvars#c.PyContext_CopyCurrent) * [PyContext\_Enter (C function)](c-api/contextvars#c.PyContext_Enter) * [PyContext\_Exit (C function)](c-api/contextvars#c.PyContext_Exit) * [PyContext\_New (C function)](c-api/contextvars#c.PyContext_New) * [PyContext\_Type (C variable)](c-api/contextvars#c.PyContext_Type) * [PyContextToken (C type)](c-api/contextvars#c.PyContextToken) * [PyContextToken\_CheckExact (C function)](c-api/contextvars#c.PyContextToken_CheckExact) * [PyContextToken\_Type (C variable)](c-api/contextvars#c.PyContextToken_Type) * [PyContextVar (C type)](c-api/contextvars#c.PyContextVar) * [PyContextVar\_CheckExact (C function)](c-api/contextvars#c.PyContextVar_CheckExact) * [PyContextVar\_Get (C function)](c-api/contextvars#c.PyContextVar_Get) * [PyContextVar\_New (C function)](c-api/contextvars#c.PyContextVar_New) * [PyContextVar\_Reset (C function)](c-api/contextvars#c.PyContextVar_Reset) * [PyContextVar\_Set (C function)](c-api/contextvars#c.PyContextVar_Set) * [PyContextVar\_Type (C variable)](c-api/contextvars#c.PyContextVar_Type) * [PyCoro\_CheckExact (C function)](c-api/coro#c.PyCoro_CheckExact) * [PyCoro\_New (C function)](c-api/coro#c.PyCoro_New) * [PyCoro\_Type (C variable)](c-api/coro#c.PyCoro_Type) * [PyCoroObject (C type)](c-api/coro#c.PyCoroObject) * [PyDate\_Check (C function)](c-api/datetime#c.PyDate_Check) * [PyDate\_CheckExact (C function)](c-api/datetime#c.PyDate_CheckExact) * [PyDate\_FromDate (C function)](c-api/datetime#c.PyDate_FromDate) * [PyDate\_FromTimestamp (C function)](c-api/datetime#c.PyDate_FromTimestamp) * [PyDateTime\_Check (C function)](c-api/datetime#c.PyDateTime_Check) * [PyDateTime\_CheckExact (C function)](c-api/datetime#c.PyDateTime_CheckExact) * [PyDateTime\_DATE\_GET\_FOLD (C function)](c-api/datetime#c.PyDateTime_DATE_GET_FOLD) * [PyDateTime\_DATE\_GET\_HOUR (C function)](c-api/datetime#c.PyDateTime_DATE_GET_HOUR) * [PyDateTime\_DATE\_GET\_MICROSECOND (C function)](c-api/datetime#c.PyDateTime_DATE_GET_MICROSECOND) * [PyDateTime\_DATE\_GET\_MINUTE (C function)](c-api/datetime#c.PyDateTime_DATE_GET_MINUTE) * [PyDateTime\_DATE\_GET\_SECOND (C function)](c-api/datetime#c.PyDateTime_DATE_GET_SECOND) * [PyDateTime\_DELTA\_GET\_DAYS (C function)](c-api/datetime#c.PyDateTime_DELTA_GET_DAYS) * [PyDateTime\_DELTA\_GET\_MICROSECONDS (C function)](c-api/datetime#c.PyDateTime_DELTA_GET_MICROSECONDS) * [PyDateTime\_DELTA\_GET\_SECONDS (C function)](c-api/datetime#c.PyDateTime_DELTA_GET_SECONDS) * [PyDateTime\_FromDateAndTime (C function)](c-api/datetime#c.PyDateTime_FromDateAndTime) * [PyDateTime\_FromDateAndTimeAndFold (C function)](c-api/datetime#c.PyDateTime_FromDateAndTimeAndFold) * [PyDateTime\_FromTimestamp (C function)](c-api/datetime#c.PyDateTime_FromTimestamp) * [PyDateTime\_GET\_DAY (C function)](c-api/datetime#c.PyDateTime_GET_DAY) * [PyDateTime\_GET\_MONTH (C function)](c-api/datetime#c.PyDateTime_GET_MONTH) * [PyDateTime\_GET\_YEAR (C function)](c-api/datetime#c.PyDateTime_GET_YEAR) * [PyDateTime\_TIME\_GET\_FOLD (C function)](c-api/datetime#c.PyDateTime_TIME_GET_FOLD) * [PyDateTime\_TIME\_GET\_HOUR (C function)](c-api/datetime#c.PyDateTime_TIME_GET_HOUR) * [PyDateTime\_TIME\_GET\_MICROSECOND (C function)](c-api/datetime#c.PyDateTime_TIME_GET_MICROSECOND) * [PyDateTime\_TIME\_GET\_MINUTE (C function)](c-api/datetime#c.PyDateTime_TIME_GET_MINUTE) * [PyDateTime\_TIME\_GET\_SECOND (C function)](c-api/datetime#c.PyDateTime_TIME_GET_SECOND) * [PyDateTime\_TimeZone\_UTC (C variable)](c-api/datetime#c.PyDateTime_TimeZone_UTC) * [PyDelta\_Check (C function)](c-api/datetime#c.PyDelta_Check) * [PyDelta\_CheckExact (C function)](c-api/datetime#c.PyDelta_CheckExact) * [PyDelta\_FromDSU (C function)](c-api/datetime#c.PyDelta_FromDSU) * [PyDescr\_IsData (C function)](c-api/descriptor#c.PyDescr_IsData) * [PyDescr\_NewClassMethod (C function)](c-api/descriptor#c.PyDescr_NewClassMethod) * [PyDescr\_NewGetSet (C function)](c-api/descriptor#c.PyDescr_NewGetSet) * [PyDescr\_NewMember (C function)](c-api/descriptor#c.PyDescr_NewMember) * [PyDescr\_NewMethod (C function)](c-api/descriptor#c.PyDescr_NewMethod) * [PyDescr\_NewWrapper (C function)](c-api/descriptor#c.PyDescr_NewWrapper) * [PyDict\_Check (C function)](c-api/dict#c.PyDict_Check) * [PyDict\_CheckExact (C function)](c-api/dict#c.PyDict_CheckExact) * [PyDict\_Clear (C function)](c-api/dict#c.PyDict_Clear) * [PyDict\_Contains (C function)](c-api/dict#c.PyDict_Contains) * [PyDict\_Copy (C function)](c-api/dict#c.PyDict_Copy) * [PyDict\_DelItem (C function)](c-api/dict#c.PyDict_DelItem) * [PyDict\_DelItemString (C function)](c-api/dict#c.PyDict_DelItemString) * [PyDict\_GetItem (C function)](c-api/dict#c.PyDict_GetItem) * [PyDict\_GetItemString (C function)](c-api/dict#c.PyDict_GetItemString) * [PyDict\_GetItemWithError (C function)](c-api/dict#c.PyDict_GetItemWithError) * [PyDict\_Items (C function)](c-api/dict#c.PyDict_Items) * [PyDict\_Keys (C function)](c-api/dict#c.PyDict_Keys) * [PyDict\_Merge (C function)](c-api/dict#c.PyDict_Merge) * [PyDict\_MergeFromSeq2 (C function)](c-api/dict#c.PyDict_MergeFromSeq2) * [PyDict\_New (C function)](c-api/dict#c.PyDict_New) * [PyDict\_Next (C function)](c-api/dict#c.PyDict_Next) * [PyDict\_SetDefault (C function)](c-api/dict#c.PyDict_SetDefault) * [PyDict\_SetItem (C function)](c-api/dict#c.PyDict_SetItem) * [PyDict\_SetItemString (C function)](c-api/dict#c.PyDict_SetItemString) * [PyDict\_Size (C function)](c-api/dict#c.PyDict_Size) * [PyDict\_Type (C variable)](c-api/dict#c.PyDict_Type) * [PyDict\_Update (C function)](c-api/dict#c.PyDict_Update) * [PyDict\_Values (C function)](c-api/dict#c.PyDict_Values) * [PyDictObject (C type)](c-api/dict#c.PyDictObject) * [PyDictProxy\_New (C function)](c-api/dict#c.PyDictProxy_New) * [PyDLL (class in ctypes)](library/ctypes#ctypes.PyDLL) * [pydoc (module)](library/pydoc#module-pydoc) * [PyDoc\_STR (C macro)](c-api/intro#c.PyDoc_STR) * [PyDoc\_STRVAR (C macro)](c-api/intro#c.PyDoc_STRVAR) * [PyErr\_BadArgument (C function)](c-api/exceptions#c.PyErr_BadArgument) * [PyErr\_BadInternalCall (C function)](c-api/exceptions#c.PyErr_BadInternalCall) * [PyErr\_CheckSignals (C function)](c-api/exceptions#c.PyErr_CheckSignals) * [PyErr\_Clear (C function)](c-api/exceptions#c.PyErr_Clear) * [PyErr\_Clear()](c-api/intro#index-17), [[1]](c-api/intro#index-22) * [PyErr\_ExceptionMatches (C function)](c-api/exceptions#c.PyErr_ExceptionMatches) * [PyErr\_ExceptionMatches()](c-api/intro#index-22) * [PyErr\_Fetch (C function)](c-api/exceptions#c.PyErr_Fetch) * [PyErr\_Fetch()](extending/newtypes#index-1) * [PyErr\_Format (C function)](c-api/exceptions#c.PyErr_Format) * [PyErr\_FormatV (C function)](c-api/exceptions#c.PyErr_FormatV) * [PyErr\_GetExcInfo (C function)](c-api/exceptions#c.PyErr_GetExcInfo) * [PyErr\_GivenExceptionMatches (C function)](c-api/exceptions#c.PyErr_GivenExceptionMatches) * [PyErr\_NewException (C function)](c-api/exceptions#c.PyErr_NewException) * [PyErr\_NewExceptionWithDoc (C function)](c-api/exceptions#c.PyErr_NewExceptionWithDoc) * [PyErr\_NoMemory (C function)](c-api/exceptions#c.PyErr_NoMemory) * [PyErr\_NormalizeException (C function)](c-api/exceptions#c.PyErr_NormalizeException) * [PyErr\_Occurred (C function)](c-api/exceptions#c.PyErr_Occurred) * [PyErr\_Occurred()](c-api/intro#index-16) * [PyErr\_Print (C function)](c-api/exceptions#c.PyErr_Print) * [PyErr\_PrintEx (C function)](c-api/exceptions#c.PyErr_PrintEx) * [PyErr\_ResourceWarning (C function)](c-api/exceptions#c.PyErr_ResourceWarning) * [PyErr\_Restore (C function)](c-api/exceptions#c.PyErr_Restore) * [PyErr\_Restore()](extending/newtypes#index-1) * [PyErr\_SetExcFromWindowsErr (C function)](c-api/exceptions#c.PyErr_SetExcFromWindowsErr) * [PyErr\_SetExcFromWindowsErrWithFilename (C function)](c-api/exceptions#c.PyErr_SetExcFromWindowsErrWithFilename) * [PyErr\_SetExcFromWindowsErrWithFilenameObject (C function)](c-api/exceptions#c.PyErr_SetExcFromWindowsErrWithFilenameObject) * [PyErr\_SetExcFromWindowsErrWithFilenameObjects (C function)](c-api/exceptions#c.PyErr_SetExcFromWindowsErrWithFilenameObjects) * [PyErr\_SetExcInfo (C function)](c-api/exceptions#c.PyErr_SetExcInfo) * [PyErr\_SetFromErrno (C function)](c-api/exceptions#c.PyErr_SetFromErrno) * [PyErr\_SetFromErrnoWithFilename (C function)](c-api/exceptions#c.PyErr_SetFromErrnoWithFilename) * [PyErr\_SetFromErrnoWithFilenameObject (C function)](c-api/exceptions#c.PyErr_SetFromErrnoWithFilenameObject) * [PyErr\_SetFromErrnoWithFilenameObjects (C function)](c-api/exceptions#c.PyErr_SetFromErrnoWithFilenameObjects) * [PyErr\_SetFromWindowsErr (C function)](c-api/exceptions#c.PyErr_SetFromWindowsErr) * [PyErr\_SetFromWindowsErrWithFilename (C function)](c-api/exceptions#c.PyErr_SetFromWindowsErrWithFilename) * [PyErr\_SetImportError (C function)](c-api/exceptions#c.PyErr_SetImportError) * [PyErr\_SetImportErrorSubclass (C function)](c-api/exceptions#c.PyErr_SetImportErrorSubclass) * [PyErr\_SetInterrupt (C function)](c-api/exceptions#c.PyErr_SetInterrupt) * [PyErr\_SetNone (C function)](c-api/exceptions#c.PyErr_SetNone) * [PyErr\_SetObject (C function)](c-api/exceptions#c.PyErr_SetObject) * [PyErr\_SetString (C function)](c-api/exceptions#c.PyErr_SetString) * [PyErr\_SetString()](c-api/intro#index-17) * [PyErr\_SyntaxLocation (C function)](c-api/exceptions#c.PyErr_SyntaxLocation) * [PyErr\_SyntaxLocationEx (C function)](c-api/exceptions#c.PyErr_SyntaxLocationEx) * [PyErr\_SyntaxLocationObject (C function)](c-api/exceptions#c.PyErr_SyntaxLocationObject) * [PyErr\_WarnEx (C function)](c-api/exceptions#c.PyErr_WarnEx) * [PyErr\_WarnExplicit (C function)](c-api/exceptions#c.PyErr_WarnExplicit) * [PyErr\_WarnExplicitObject (C function)](c-api/exceptions#c.PyErr_WarnExplicitObject) * [PyErr\_WarnFormat (C function)](c-api/exceptions#c.PyErr_WarnFormat) * [PyErr\_WriteUnraisable (C function)](c-api/exceptions#c.PyErr_WriteUnraisable) * [PyEval\_AcquireLock (C function)](c-api/init#c.PyEval_AcquireLock) * [PyEval\_AcquireThread (C function)](c-api/init#c.PyEval_AcquireThread) * [PyEval\_AcquireThread()](c-api/init#index-38) * [PyEval\_EvalCode (C function)](c-api/veryhigh#c.PyEval_EvalCode) * [PyEval\_EvalCodeEx (C function)](c-api/veryhigh#c.PyEval_EvalCodeEx) * [PyEval\_EvalFrame (C function)](c-api/veryhigh#c.PyEval_EvalFrame) * [PyEval\_EvalFrameEx (C function)](c-api/veryhigh#c.PyEval_EvalFrameEx) * [PyEval\_GetBuiltins (C function)](c-api/reflection#c.PyEval_GetBuiltins) * [PyEval\_GetFrame (C function)](c-api/reflection#c.PyEval_GetFrame) * [PyEval\_GetFuncDesc (C function)](c-api/reflection#c.PyEval_GetFuncDesc) * [PyEval\_GetFuncName (C function)](c-api/reflection#c.PyEval_GetFuncName) * [PyEval\_GetGlobals (C function)](c-api/reflection#c.PyEval_GetGlobals) * [PyEval\_GetLocals (C function)](c-api/reflection#c.PyEval_GetLocals) * [PyEval\_InitThreads (C function)](c-api/init#c.PyEval_InitThreads) * [PyEval\_InitThreads()](c-api/init#index-16) * [PyEval\_MergeCompilerFlags (C function)](c-api/veryhigh#c.PyEval_MergeCompilerFlags) * [PyEval\_ReleaseLock (C function)](c-api/init#c.PyEval_ReleaseLock) * [PyEval\_ReleaseThread (C function)](c-api/init#c.PyEval_ReleaseThread) * [PyEval\_ReleaseThread()](c-api/init#index-38) * [PyEval\_RestoreThread (C function)](c-api/init#c.PyEval_RestoreThread) * [PyEval\_RestoreThread()](c-api/init#index-37), [[1]](c-api/init#index-38) * [PyEval\_SaveThread (C function)](c-api/init#c.PyEval_SaveThread) * [PyEval\_SaveThread()](c-api/init#index-37), [[1]](c-api/init#index-38) * [PyEval\_SetProfile (C function)](c-api/init#c.PyEval_SetProfile) * [PyEval\_SetTrace (C function)](c-api/init#c.PyEval_SetTrace) * [PyEval\_ThreadsInitialized (C function)](c-api/init#c.PyEval_ThreadsInitialized) * [PyExc\_ArithmeticError](c-api/exceptions#index-3) * [PyExc\_AssertionError](c-api/exceptions#index-3) * [PyExc\_AttributeError](c-api/exceptions#index-3) * [PyExc\_BaseException](c-api/exceptions#index-3) * [PyExc\_BlockingIOError](c-api/exceptions#index-3) * [PyExc\_BrokenPipeError](c-api/exceptions#index-3) * [PyExc\_BufferError](c-api/exceptions#index-3) * [PyExc\_BytesWarning](c-api/exceptions#index-6) * [PyExc\_ChildProcessError](c-api/exceptions#index-3) * [PyExc\_ConnectionAbortedError](c-api/exceptions#index-3) * [PyExc\_ConnectionError](c-api/exceptions#index-3) * [PyExc\_ConnectionRefusedError](c-api/exceptions#index-3) * [PyExc\_ConnectionResetError](c-api/exceptions#index-3) * [PyExc\_DeprecationWarning](c-api/exceptions#index-6) * [PyExc\_EnvironmentError](c-api/exceptions#index-5) * [PyExc\_EOFError](c-api/exceptions#index-3) * [PyExc\_Exception](c-api/exceptions#index-3) * [PyExc\_FileExistsError](c-api/exceptions#index-3) * [PyExc\_FileNotFoundError](c-api/exceptions#index-3) * [PyExc\_FloatingPointError](c-api/exceptions#index-3) * [PyExc\_FutureWarning](c-api/exceptions#index-6) * [PyExc\_GeneratorExit](c-api/exceptions#index-3) * [PyExc\_ImportError](c-api/exceptions#index-3) * [PyExc\_ImportWarning](c-api/exceptions#index-6) * [PyExc\_IndentationError](c-api/exceptions#index-3) | * [PyExc\_IndexError](c-api/exceptions#index-3) * [PyExc\_InterruptedError](c-api/exceptions#index-3) * [PyExc\_IOError](c-api/exceptions#index-5) * [PyExc\_IsADirectoryError](c-api/exceptions#index-3) * [PyExc\_KeyboardInterrupt](c-api/exceptions#index-3) * [PyExc\_KeyError](c-api/exceptions#index-3) * [PyExc\_LookupError](c-api/exceptions#index-3) * [PyExc\_MemoryError](c-api/exceptions#index-3) * [PyExc\_ModuleNotFoundError](c-api/exceptions#index-3) * [PyExc\_NameError](c-api/exceptions#index-3) * [PyExc\_NotADirectoryError](c-api/exceptions#index-3) * [PyExc\_NotImplementedError](c-api/exceptions#index-3) * [PyExc\_OSError](c-api/exceptions#index-3) * [PyExc\_OverflowError](c-api/exceptions#index-3) * [PyExc\_PendingDeprecationWarning](c-api/exceptions#index-6) * [PyExc\_PermissionError](c-api/exceptions#index-3) * [PyExc\_ProcessLookupError](c-api/exceptions#index-3) * [PyExc\_RecursionError](c-api/exceptions#index-3) * [PyExc\_ReferenceError](c-api/exceptions#index-3) * [PyExc\_ResourceWarning](c-api/exceptions#index-6) * [PyExc\_RuntimeError](c-api/exceptions#index-3) * [PyExc\_RuntimeWarning](c-api/exceptions#index-6) * [PyExc\_StopAsyncIteration](c-api/exceptions#index-3) * [PyExc\_StopIteration](c-api/exceptions#index-3) * [PyExc\_SyntaxError](c-api/exceptions#index-3) * [PyExc\_SyntaxWarning](c-api/exceptions#index-6) * [PyExc\_SystemError](c-api/exceptions#index-3) * [PyExc\_SystemExit](c-api/exceptions#index-3) * [PyExc\_TabError](c-api/exceptions#index-3) * [PyExc\_TimeoutError](c-api/exceptions#index-3) * [PyExc\_TypeError](c-api/exceptions#index-3) * [PyExc\_UnboundLocalError](c-api/exceptions#index-3) * [PyExc\_UnicodeDecodeError](c-api/exceptions#index-3) * [PyExc\_UnicodeEncodeError](c-api/exceptions#index-3) * [PyExc\_UnicodeError](c-api/exceptions#index-3) * [PyExc\_UnicodeTranslateError](c-api/exceptions#index-3) * [PyExc\_UnicodeWarning](c-api/exceptions#index-6) * [PyExc\_UserWarning](c-api/exceptions#index-6) * [PyExc\_ValueError](c-api/exceptions#index-3) * [PyExc\_Warning](c-api/exceptions#index-6) * [PyExc\_WindowsError](c-api/exceptions#index-5) * [PyExc\_ZeroDivisionError](c-api/exceptions#index-3) * [PyException\_GetCause (C function)](c-api/exceptions#c.PyException_GetCause) * [PyException\_GetContext (C function)](c-api/exceptions#c.PyException_GetContext) * [PyException\_GetTraceback (C function)](c-api/exceptions#c.PyException_GetTraceback) * [PyException\_SetCause (C function)](c-api/exceptions#c.PyException_SetCause) * [PyException\_SetContext (C function)](c-api/exceptions#c.PyException_SetContext) * [PyException\_SetTraceback (C function)](c-api/exceptions#c.PyException_SetTraceback) * pyexpat + [module](library/pyexpat#index-1) * [PyFile\_FromFd (C function)](c-api/file#c.PyFile_FromFd) * [PyFile\_GetLine (C function)](c-api/file#c.PyFile_GetLine) * [PyFile\_SetOpenCodeHook (C function)](c-api/file#c.PyFile_SetOpenCodeHook) * [PyFile\_WriteObject (C function)](c-api/file#c.PyFile_WriteObject) * [PyFile\_WriteString (C function)](c-api/file#c.PyFile_WriteString) * [PyFloat\_AS\_DOUBLE (C function)](c-api/float#c.PyFloat_AS_DOUBLE) * [PyFloat\_AsDouble (C function)](c-api/float#c.PyFloat_AsDouble) * [PyFloat\_Check (C function)](c-api/float#c.PyFloat_Check) * [PyFloat\_CheckExact (C function)](c-api/float#c.PyFloat_CheckExact) * [PyFloat\_FromDouble (C function)](c-api/float#c.PyFloat_FromDouble) * [PyFloat\_FromString (C function)](c-api/float#c.PyFloat_FromString) * [PyFloat\_GetInfo (C function)](c-api/float#c.PyFloat_GetInfo) * [PyFloat\_GetMax (C function)](c-api/float#c.PyFloat_GetMax) * [PyFloat\_GetMin (C function)](c-api/float#c.PyFloat_GetMin) * [PyFloat\_Type (C variable)](c-api/float#c.PyFloat_Type) * [PyFloatObject (C type)](c-api/float#c.PyFloatObject) * [PyFrame\_GetBack (C function)](c-api/reflection#c.PyFrame_GetBack) * [PyFrame\_GetCode (C function)](c-api/reflection#c.PyFrame_GetCode) * [PyFrame\_GetLineNumber (C function)](c-api/reflection#c.PyFrame_GetLineNumber) * [PyFrameObject (C type)](c-api/veryhigh#c.PyFrameObject) * [PyFrozenSet\_Check (C function)](c-api/set#c.PyFrozenSet_Check) * [PyFrozenSet\_CheckExact (C function)](c-api/set#c.PyFrozenSet_CheckExact) * [PyFrozenSet\_New (C function)](c-api/set#c.PyFrozenSet_New) * [PyFrozenSet\_Type (C variable)](c-api/set#c.PyFrozenSet_Type) * [PyFunction\_Check (C function)](c-api/function#c.PyFunction_Check) * [PyFunction\_GetAnnotations (C function)](c-api/function#c.PyFunction_GetAnnotations) * [PyFunction\_GetClosure (C function)](c-api/function#c.PyFunction_GetClosure) * [PyFunction\_GetCode (C function)](c-api/function#c.PyFunction_GetCode) * [PyFunction\_GetDefaults (C function)](c-api/function#c.PyFunction_GetDefaults) * [PyFunction\_GetGlobals (C function)](c-api/function#c.PyFunction_GetGlobals) * [PyFunction\_GetModule (C function)](c-api/function#c.PyFunction_GetModule) * [PyFunction\_New (C function)](c-api/function#c.PyFunction_New) * [PyFunction\_NewWithQualName (C function)](c-api/function#c.PyFunction_NewWithQualName) * [PyFunction\_SetAnnotations (C function)](c-api/function#c.PyFunction_SetAnnotations) * [PyFunction\_SetClosure (C function)](c-api/function#c.PyFunction_SetClosure) * [PyFunction\_SetDefaults (C function)](c-api/function#c.PyFunction_SetDefaults) * [PyFunction\_Type (C variable)](c-api/function#c.PyFunction_Type) * [PyFunctionObject (C type)](c-api/function#c.PyFunctionObject) * [PYFUNCTYPE() (in module ctypes)](library/ctypes#ctypes.PYFUNCTYPE) * [PyGen\_Check (C function)](c-api/gen#c.PyGen_Check) * [PyGen\_CheckExact (C function)](c-api/gen#c.PyGen_CheckExact) * [PyGen\_New (C function)](c-api/gen#c.PyGen_New) * [PyGen\_NewWithQualName (C function)](c-api/gen#c.PyGen_NewWithQualName) * [PyGen\_Type (C variable)](c-api/gen#c.PyGen_Type) * [PyGenObject (C type)](c-api/gen#c.PyGenObject) * [PyGetSetDef (C type)](c-api/structures#c.PyGetSetDef) * [PyGILState\_Check (C function)](c-api/init#c.PyGILState_Check) * [PyGILState\_Ensure (C function)](c-api/init#c.PyGILState_Ensure) * [PyGILState\_GetThisThreadState (C function)](c-api/init#c.PyGILState_GetThisThreadState) * [PyGILState\_Release (C function)](c-api/init#c.PyGILState_Release) * [PyImport\_AddModule (C function)](c-api/import#c.PyImport_AddModule) * [PyImport\_AddModuleObject (C function)](c-api/import#c.PyImport_AddModuleObject) * [PyImport\_AppendInittab (C function)](c-api/import#c.PyImport_AppendInittab) * [PyImport\_ExecCodeModule (C function)](c-api/import#c.PyImport_ExecCodeModule) * [PyImport\_ExecCodeModuleEx (C function)](c-api/import#c.PyImport_ExecCodeModuleEx) * [PyImport\_ExecCodeModuleObject (C function)](c-api/import#c.PyImport_ExecCodeModuleObject) * [PyImport\_ExecCodeModuleWithPathnames (C function)](c-api/import#c.PyImport_ExecCodeModuleWithPathnames) * [PyImport\_ExtendInittab (C function)](c-api/import#c.PyImport_ExtendInittab) * [PyImport\_FrozenModules (C variable)](c-api/import#c.PyImport_FrozenModules) * [PyImport\_GetImporter (C function)](c-api/import#c.PyImport_GetImporter) * [PyImport\_GetMagicNumber (C function)](c-api/import#c.PyImport_GetMagicNumber) * [PyImport\_GetMagicTag (C function)](c-api/import#c.PyImport_GetMagicTag) * [PyImport\_GetModule (C function)](c-api/import#c.PyImport_GetModule) * [PyImport\_GetModuleDict (C function)](c-api/import#c.PyImport_GetModuleDict) * [PyImport\_Import (C function)](c-api/import#c.PyImport_Import) * [PyImport\_ImportFrozenModule (C function)](c-api/import#c.PyImport_ImportFrozenModule) * [PyImport\_ImportFrozenModuleObject (C function)](c-api/import#c.PyImport_ImportFrozenModuleObject) * [PyImport\_ImportModule (C function)](c-api/import#c.PyImport_ImportModule) * [PyImport\_ImportModuleEx (C function)](c-api/import#c.PyImport_ImportModuleEx) * [PyImport\_ImportModuleLevel (C function)](c-api/import#c.PyImport_ImportModuleLevel) * [PyImport\_ImportModuleLevelObject (C function)](c-api/import#c.PyImport_ImportModuleLevelObject) * [PyImport\_ImportModuleNoBlock (C function)](c-api/import#c.PyImport_ImportModuleNoBlock) * [PyImport\_ReloadModule (C function)](c-api/import#c.PyImport_ReloadModule) * [PyIndex\_Check (C function)](c-api/number#c.PyIndex_Check) * [PyInit\_modulename (C function)](extending/building#c.PyInit_modulename) * [PyInstanceMethod\_Check (C function)](c-api/method#c.PyInstanceMethod_Check) * [PyInstanceMethod\_Function (C function)](c-api/method#c.PyInstanceMethod_Function) * [PyInstanceMethod\_GET\_FUNCTION (C function)](c-api/method#c.PyInstanceMethod_GET_FUNCTION) * [PyInstanceMethod\_New (C function)](c-api/method#c.PyInstanceMethod_New) * [PyInstanceMethod\_Type (C variable)](c-api/method#c.PyInstanceMethod_Type) * [PyInterpreterState (C type)](c-api/init#c.PyInterpreterState) * [PyInterpreterState\_Clear (C function)](c-api/init#c.PyInterpreterState_Clear) * [PyInterpreterState\_Delete (C function)](c-api/init#c.PyInterpreterState_Delete) * [PyInterpreterState\_Get (C function)](c-api/init#c.PyInterpreterState_Get) * [PyInterpreterState\_GetDict (C function)](c-api/init#c.PyInterpreterState_GetDict) * [PyInterpreterState\_GetID (C function)](c-api/init#c.PyInterpreterState_GetID) * [PyInterpreterState\_Head (C function)](c-api/init#c.PyInterpreterState_Head) * [PyInterpreterState\_Main (C function)](c-api/init#c.PyInterpreterState_Main) * [PyInterpreterState\_New (C function)](c-api/init#c.PyInterpreterState_New) * [PyInterpreterState\_Next (C function)](c-api/init#c.PyInterpreterState_Next) * [PyInterpreterState\_ThreadHead (C function)](c-api/init#c.PyInterpreterState_ThreadHead) * [PyIter\_Check (C function)](c-api/iter#c.PyIter_Check) * [PyIter\_Next (C function)](c-api/iter#c.PyIter_Next) * [PyList\_Append (C function)](c-api/list#c.PyList_Append) * [PyList\_AsTuple (C function)](c-api/list#c.PyList_AsTuple) * [PyList\_Check (C function)](c-api/list#c.PyList_Check) * [PyList\_CheckExact (C function)](c-api/list#c.PyList_CheckExact) * [PyList\_GET\_ITEM (C function)](c-api/list#c.PyList_GET_ITEM) * [PyList\_GET\_SIZE (C function)](c-api/list#c.PyList_GET_SIZE) * [PyList\_GetItem (C function)](c-api/list#c.PyList_GetItem) * [PyList\_GetItem()](c-api/intro#index-12) * [PyList\_GetSlice (C function)](c-api/list#c.PyList_GetSlice) * [PyList\_Insert (C function)](c-api/list#c.PyList_Insert) * [PyList\_New (C function)](c-api/list#c.PyList_New) * [PyList\_Reverse (C function)](c-api/list#c.PyList_Reverse) * [PyList\_SET\_ITEM (C function)](c-api/list#c.PyList_SET_ITEM) * [PyList\_SetItem (C function)](c-api/list#c.PyList_SetItem) * [PyList\_SetItem()](c-api/intro#index-10) * [PyList\_SetSlice (C function)](c-api/list#c.PyList_SetSlice) * [PyList\_Size (C function)](c-api/list#c.PyList_Size) * [PyList\_Sort (C function)](c-api/list#c.PyList_Sort) * [PyList\_Type (C variable)](c-api/list#c.PyList_Type) * [PyListObject (C type)](c-api/list#c.PyListObject) * [PyLong\_AsDouble (C function)](c-api/long#c.PyLong_AsDouble) * [PyLong\_AsLong (C function)](c-api/long#c.PyLong_AsLong) * [PyLong\_AsLongAndOverflow (C function)](c-api/long#c.PyLong_AsLongAndOverflow) * [PyLong\_AsLongLong (C function)](c-api/long#c.PyLong_AsLongLong) * [PyLong\_AsLongLongAndOverflow (C function)](c-api/long#c.PyLong_AsLongLongAndOverflow) * [PyLong\_AsSize\_t (C function)](c-api/long#c.PyLong_AsSize_t) * [PyLong\_AsSsize\_t (C function)](c-api/long#c.PyLong_AsSsize_t) * [PyLong\_AsUnsignedLong (C function)](c-api/long#c.PyLong_AsUnsignedLong) * [PyLong\_AsUnsignedLongLong (C function)](c-api/long#c.PyLong_AsUnsignedLongLong) * [PyLong\_AsUnsignedLongLongMask (C function)](c-api/long#c.PyLong_AsUnsignedLongLongMask) * [PyLong\_AsUnsignedLongMask (C function)](c-api/long#c.PyLong_AsUnsignedLongMask) * [PyLong\_AsVoidPtr (C function)](c-api/long#c.PyLong_AsVoidPtr) * [PyLong\_Check (C function)](c-api/long#c.PyLong_Check) * [PyLong\_CheckExact (C function)](c-api/long#c.PyLong_CheckExact) * [PyLong\_FromDouble (C function)](c-api/long#c.PyLong_FromDouble) * [PyLong\_FromLong (C function)](c-api/long#c.PyLong_FromLong) * [PyLong\_FromLongLong (C function)](c-api/long#c.PyLong_FromLongLong) * [PyLong\_FromSize\_t (C function)](c-api/long#c.PyLong_FromSize_t) * [PyLong\_FromSsize\_t (C function)](c-api/long#c.PyLong_FromSsize_t) * [PyLong\_FromString (C function)](c-api/long#c.PyLong_FromString) * [PyLong\_FromUnicode (C function)](c-api/long#c.PyLong_FromUnicode) * [PyLong\_FromUnicodeObject (C function)](c-api/long#c.PyLong_FromUnicodeObject) * [PyLong\_FromUnsignedLong (C function)](c-api/long#c.PyLong_FromUnsignedLong) * [PyLong\_FromUnsignedLongLong (C function)](c-api/long#c.PyLong_FromUnsignedLongLong) * [PyLong\_FromVoidPtr (C function)](c-api/long#c.PyLong_FromVoidPtr) * [PyLong\_Type (C variable)](c-api/long#c.PyLong_Type) * [PyLongObject (C type)](c-api/long#c.PyLongObject) * [PyMapping\_Check (C function)](c-api/mapping#c.PyMapping_Check) * [PyMapping\_DelItem (C function)](c-api/mapping#c.PyMapping_DelItem) * [PyMapping\_DelItemString (C function)](c-api/mapping#c.PyMapping_DelItemString) * [PyMapping\_GetItemString (C function)](c-api/mapping#c.PyMapping_GetItemString) * [PyMapping\_HasKey (C function)](c-api/mapping#c.PyMapping_HasKey) * [PyMapping\_HasKeyString (C function)](c-api/mapping#c.PyMapping_HasKeyString) * [PyMapping\_Items (C function)](c-api/mapping#c.PyMapping_Items) * [PyMapping\_Keys (C function)](c-api/mapping#c.PyMapping_Keys) * [PyMapping\_Length (C function)](c-api/mapping#c.PyMapping_Length) * [PyMapping\_SetItemString (C function)](c-api/mapping#c.PyMapping_SetItemString) * [PyMapping\_Size (C function)](c-api/mapping#c.PyMapping_Size) * [PyMapping\_Values (C function)](c-api/mapping#c.PyMapping_Values) * [PyMappingMethods (C type)](c-api/typeobj#c.PyMappingMethods) * [PyMappingMethods.mp\_ass\_subscript (C member)](c-api/typeobj#c.PyMappingMethods.mp_ass_subscript) * [PyMappingMethods.mp\_length (C member)](c-api/typeobj#c.PyMappingMethods.mp_length) * [PyMappingMethods.mp\_subscript (C member)](c-api/typeobj#c.PyMappingMethods.mp_subscript) * [PyMarshal\_ReadLastObjectFromFile (C function)](c-api/marshal#c.PyMarshal_ReadLastObjectFromFile) * [PyMarshal\_ReadLongFromFile (C function)](c-api/marshal#c.PyMarshal_ReadLongFromFile) * [PyMarshal\_ReadObjectFromFile (C function)](c-api/marshal#c.PyMarshal_ReadObjectFromFile) * [PyMarshal\_ReadObjectFromString (C function)](c-api/marshal#c.PyMarshal_ReadObjectFromString) * [PyMarshal\_ReadShortFromFile (C function)](c-api/marshal#c.PyMarshal_ReadShortFromFile) * [PyMarshal\_WriteLongToFile (C function)](c-api/marshal#c.PyMarshal_WriteLongToFile) * [PyMarshal\_WriteObjectToFile (C function)](c-api/marshal#c.PyMarshal_WriteObjectToFile) * [PyMarshal\_WriteObjectToString (C function)](c-api/marshal#c.PyMarshal_WriteObjectToString) * [PyMem\_Calloc (C function)](c-api/memory#c.PyMem_Calloc) * [PyMem\_Del (C function)](c-api/memory#c.PyMem_Del) * [PYMEM\_DOMAIN\_MEM (C macro)](c-api/memory#c.PYMEM_DOMAIN_MEM) * [PYMEM\_DOMAIN\_OBJ (C macro)](c-api/memory#c.PYMEM_DOMAIN_OBJ) * [PYMEM\_DOMAIN\_RAW (C macro)](c-api/memory#c.PYMEM_DOMAIN_RAW) * [PyMem\_Free (C function)](c-api/memory#c.PyMem_Free) * [PyMem\_GetAllocator (C function)](c-api/memory#c.PyMem_GetAllocator) * [PyMem\_Malloc (C function)](c-api/memory#c.PyMem_Malloc) * [PyMem\_New (C function)](c-api/memory#c.PyMem_New) * [PyMem\_RawCalloc (C function)](c-api/memory#c.PyMem_RawCalloc) * [PyMem\_RawFree (C function)](c-api/memory#c.PyMem_RawFree) * [PyMem\_RawMalloc (C function)](c-api/memory#c.PyMem_RawMalloc) * [PyMem\_RawRealloc (C function)](c-api/memory#c.PyMem_RawRealloc) * [PyMem\_Realloc (C function)](c-api/memory#c.PyMem_Realloc) * [PyMem\_Resize (C function)](c-api/memory#c.PyMem_Resize) * [PyMem\_SetAllocator (C function)](c-api/memory#c.PyMem_SetAllocator) * [PyMem\_SetupDebugHooks (C function)](c-api/memory#c.PyMem_SetupDebugHooks) * [PyMemAllocatorDomain (C type)](c-api/memory#c.PyMemAllocatorDomain) * [PyMemAllocatorEx (C type)](c-api/memory#c.PyMemAllocatorEx) * [PyMember\_GetOne (C function)](c-api/structures#c.PyMember_GetOne) * [PyMember\_SetOne (C function)](c-api/structures#c.PyMember_SetOne) * [PyMemberDef (C type)](c-api/structures#c.PyMemberDef) * [PyMemoryView\_Check (C function)](c-api/memoryview#c.PyMemoryView_Check) * [PyMemoryView\_FromBuffer (C function)](c-api/memoryview#c.PyMemoryView_FromBuffer) * [PyMemoryView\_FromMemory (C function)](c-api/memoryview#c.PyMemoryView_FromMemory) * [PyMemoryView\_FromObject (C function)](c-api/memoryview#c.PyMemoryView_FromObject) * [PyMemoryView\_GET\_BASE (C function)](c-api/memoryview#c.PyMemoryView_GET_BASE) * [PyMemoryView\_GET\_BUFFER (C function)](c-api/memoryview#c.PyMemoryView_GET_BUFFER) * [PyMemoryView\_GetContiguous (C function)](c-api/memoryview#c.PyMemoryView_GetContiguous) * [PyMethod\_Check (C function)](c-api/method#c.PyMethod_Check) * [PyMethod\_Function (C function)](c-api/method#c.PyMethod_Function) * [PyMethod\_GET\_FUNCTION (C function)](c-api/method#c.PyMethod_GET_FUNCTION) * [PyMethod\_GET\_SELF (C function)](c-api/method#c.PyMethod_GET_SELF) * [PyMethod\_New (C function)](c-api/method#c.PyMethod_New) * [PyMethod\_Self (C function)](c-api/method#c.PyMethod_Self) * [PyMethod\_Type (C variable)](c-api/method#c.PyMethod_Type) * [PyMethodDef (C type)](c-api/structures#c.PyMethodDef) * [PyModule\_AddFunctions (C function)](c-api/module#c.PyModule_AddFunctions) * [PyModule\_AddIntConstant (C function)](c-api/module#c.PyModule_AddIntConstant) * [PyModule\_AddIntMacro (C function)](c-api/module#c.PyModule_AddIntMacro) * [PyModule\_AddObject (C function)](c-api/module#c.PyModule_AddObject) * [PyModule\_AddStringConstant (C function)](c-api/module#c.PyModule_AddStringConstant) * [PyModule\_AddStringMacro (C function)](c-api/module#c.PyModule_AddStringMacro) * [PyModule\_AddType (C function)](c-api/module#c.PyModule_AddType) * [PyModule\_Check (C function)](c-api/module#c.PyModule_Check) * [PyModule\_CheckExact (C function)](c-api/module#c.PyModule_CheckExact) * [PyModule\_Create (C function)](c-api/module#c.PyModule_Create) * [PyModule\_Create2 (C function)](c-api/module#c.PyModule_Create2) * [PyModule\_ExecDef (C function)](c-api/module#c.PyModule_ExecDef) * [PyModule\_FromDefAndSpec (C function)](c-api/module#c.PyModule_FromDefAndSpec) * [PyModule\_FromDefAndSpec2 (C function)](c-api/module#c.PyModule_FromDefAndSpec2) * [PyModule\_GetDef (C function)](c-api/module#c.PyModule_GetDef) * [PyModule\_GetDict (C function)](c-api/module#c.PyModule_GetDict) * [PyModule\_GetFilename (C function)](c-api/module#c.PyModule_GetFilename) * [PyModule\_GetFilenameObject (C function)](c-api/module#c.PyModule_GetFilenameObject) * [PyModule\_GetName (C function)](c-api/module#c.PyModule_GetName) * [PyModule\_GetNameObject (C function)](c-api/module#c.PyModule_GetNameObject) * [PyModule\_GetState (C function)](c-api/module#c.PyModule_GetState) * [PyModule\_New (C function)](c-api/module#c.PyModule_New) * [PyModule\_NewObject (C function)](c-api/module#c.PyModule_NewObject) * [PyModule\_SetDocString (C function)](c-api/module#c.PyModule_SetDocString) * [PyModule\_Type (C variable)](c-api/module#c.PyModule_Type) * [PyModuleDef (C type)](c-api/module#c.PyModuleDef) * [PyModuleDef.m\_base (C member)](c-api/module#c.PyModuleDef.m_base) * [PyModuleDef.m\_clear (C member)](c-api/module#c.PyModuleDef.m_clear) * [PyModuleDef.m\_doc (C member)](c-api/module#c.PyModuleDef.m_doc) * [PyModuleDef.m\_free (C member)](c-api/module#c.PyModuleDef.m_free) * [PyModuleDef.m\_methods (C member)](c-api/module#c.PyModuleDef.m_methods) * [PyModuleDef.m\_name (C member)](c-api/module#c.PyModuleDef.m_name) * [PyModuleDef.m\_reload (C member)](c-api/module#c.PyModuleDef.m_reload) * [PyModuleDef.m\_size (C member)](c-api/module#c.PyModuleDef.m_size) * [PyModuleDef.m\_slots (C member)](c-api/module#c.PyModuleDef.m_slots) * [PyModuleDef.m\_traverse (C member)](c-api/module#c.PyModuleDef.m_traverse) * [PyModuleDef\_Init (C function)](c-api/module#c.PyModuleDef_Init) * [PyModuleDef\_Slot (C type)](c-api/module#c.PyModuleDef_Slot) * [PyModuleDef\_Slot.slot (C member)](c-api/module#c.PyModuleDef_Slot.slot) * [PyModuleDef\_Slot.value (C member)](c-api/module#c.PyModuleDef_Slot.value) * [PyNumber\_Absolute (C function)](c-api/number#c.PyNumber_Absolute) * [PyNumber\_Add (C function)](c-api/number#c.PyNumber_Add) * [PyNumber\_And (C function)](c-api/number#c.PyNumber_And) * [PyNumber\_AsSsize\_t (C function)](c-api/number#c.PyNumber_AsSsize_t) * [PyNumber\_Check (C function)](c-api/number#c.PyNumber_Check) * [PyNumber\_Divmod (C function)](c-api/number#c.PyNumber_Divmod) * [PyNumber\_Float (C function)](c-api/number#c.PyNumber_Float) * [PyNumber\_FloorDivide (C function)](c-api/number#c.PyNumber_FloorDivide) * [PyNumber\_Index (C function)](c-api/number#c.PyNumber_Index) * [PyNumber\_InPlaceAdd (C function)](c-api/number#c.PyNumber_InPlaceAdd) * [PyNumber\_InPlaceAnd (C function)](c-api/number#c.PyNumber_InPlaceAnd) * [PyNumber\_InPlaceFloorDivide (C function)](c-api/number#c.PyNumber_InPlaceFloorDivide) * [PyNumber\_InPlaceLshift (C function)](c-api/number#c.PyNumber_InPlaceLshift) * [PyNumber\_InPlaceMatrixMultiply (C function)](c-api/number#c.PyNumber_InPlaceMatrixMultiply) * [PyNumber\_InPlaceMultiply (C function)](c-api/number#c.PyNumber_InPlaceMultiply) * [PyNumber\_InPlaceOr (C function)](c-api/number#c.PyNumber_InPlaceOr) * [PyNumber\_InPlacePower (C function)](c-api/number#c.PyNumber_InPlacePower) * [PyNumber\_InPlaceRemainder (C function)](c-api/number#c.PyNumber_InPlaceRemainder) * [PyNumber\_InPlaceRshift (C function)](c-api/number#c.PyNumber_InPlaceRshift) * [PyNumber\_InPlaceSubtract (C function)](c-api/number#c.PyNumber_InPlaceSubtract) * [PyNumber\_InPlaceTrueDivide (C function)](c-api/number#c.PyNumber_InPlaceTrueDivide) * [PyNumber\_InPlaceXor (C function)](c-api/number#c.PyNumber_InPlaceXor) * [PyNumber\_Invert (C function)](c-api/number#c.PyNumber_Invert) * [PyNumber\_Long (C function)](c-api/number#c.PyNumber_Long) * [PyNumber\_Lshift (C function)](c-api/number#c.PyNumber_Lshift) * [PyNumber\_MatrixMultiply (C function)](c-api/number#c.PyNumber_MatrixMultiply) * [PyNumber\_Multiply (C function)](c-api/number#c.PyNumber_Multiply) * [PyNumber\_Negative (C function)](c-api/number#c.PyNumber_Negative) * [PyNumber\_Or (C function)](c-api/number#c.PyNumber_Or) * [PyNumber\_Positive (C function)](c-api/number#c.PyNumber_Positive) * [PyNumber\_Power (C function)](c-api/number#c.PyNumber_Power) * [PyNumber\_Remainder (C function)](c-api/number#c.PyNumber_Remainder) * [PyNumber\_Rshift (C function)](c-api/number#c.PyNumber_Rshift) * [PyNumber\_Subtract (C function)](c-api/number#c.PyNumber_Subtract) * [PyNumber\_ToBase (C function)](c-api/number#c.PyNumber_ToBase) * [PyNumber\_TrueDivide (C function)](c-api/number#c.PyNumber_TrueDivide) * [PyNumber\_Xor (C function)](c-api/number#c.PyNumber_Xor) * [PyNumberMethods (C type)](c-api/typeobj#c.PyNumberMethods) * [PyNumberMethods.nb\_absolute (C member)](c-api/typeobj#c.PyNumberMethods.nb_absolute) * [PyNumberMethods.nb\_add (C member)](c-api/typeobj#c.PyNumberMethods.nb_add) * [PyNumberMethods.nb\_and (C member)](c-api/typeobj#c.PyNumberMethods.nb_and) * [PyNumberMethods.nb\_bool (C member)](c-api/typeobj#c.PyNumberMethods.nb_bool) * [PyNumberMethods.nb\_divmod (C member)](c-api/typeobj#c.PyNumberMethods.nb_divmod) * [PyNumberMethods.nb\_float (C member)](c-api/typeobj#c.PyNumberMethods.nb_float) * [PyNumberMethods.nb\_floor\_divide (C member)](c-api/typeobj#c.PyNumberMethods.nb_floor_divide) * [PyNumberMethods.nb\_index (C member)](c-api/typeobj#c.PyNumberMethods.nb_index) * [PyNumberMethods.nb\_inplace\_add (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_add) * [PyNumberMethods.nb\_inplace\_and (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_and) * [PyNumberMethods.nb\_inplace\_floor\_divide (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_floor_divide) * [PyNumberMethods.nb\_inplace\_lshift (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_lshift) * [PyNumberMethods.nb\_inplace\_matrix\_multiply (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_matrix_multiply) * [PyNumberMethods.nb\_inplace\_multiply (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_multiply) * [PyNumberMethods.nb\_inplace\_or (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_or) * [PyNumberMethods.nb\_inplace\_power (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_power) * [PyNumberMethods.nb\_inplace\_remainder (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_remainder) * [PyNumberMethods.nb\_inplace\_rshift (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_rshift) * [PyNumberMethods.nb\_inplace\_subtract (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_subtract) * [PyNumberMethods.nb\_inplace\_true\_divide (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_true_divide) * [PyNumberMethods.nb\_inplace\_xor (C member)](c-api/typeobj#c.PyNumberMethods.nb_inplace_xor) * [PyNumberMethods.nb\_int (C member)](c-api/typeobj#c.PyNumberMethods.nb_int) * [PyNumberMethods.nb\_invert (C member)](c-api/typeobj#c.PyNumberMethods.nb_invert) * [PyNumberMethods.nb\_lshift (C member)](c-api/typeobj#c.PyNumberMethods.nb_lshift) * [PyNumberMethods.nb\_matrix\_multiply (C member)](c-api/typeobj#c.PyNumberMethods.nb_matrix_multiply) * [PyNumberMethods.nb\_multiply (C member)](c-api/typeobj#c.PyNumberMethods.nb_multiply) * [PyNumberMethods.nb\_negative (C member)](c-api/typeobj#c.PyNumberMethods.nb_negative) * [PyNumberMethods.nb\_or (C member)](c-api/typeobj#c.PyNumberMethods.nb_or) * [PyNumberMethods.nb\_positive (C member)](c-api/typeobj#c.PyNumberMethods.nb_positive) * [PyNumberMethods.nb\_power (C member)](c-api/typeobj#c.PyNumberMethods.nb_power) * [PyNumberMethods.nb\_remainder (C member)](c-api/typeobj#c.PyNumberMethods.nb_remainder) * [PyNumberMethods.nb\_reserved (C member)](c-api/typeobj#c.PyNumberMethods.nb_reserved) * [PyNumberMethods.nb\_rshift (C member)](c-api/typeobj#c.PyNumberMethods.nb_rshift) * [PyNumberMethods.nb\_subtract (C member)](c-api/typeobj#c.PyNumberMethods.nb_subtract) * [PyNumberMethods.nb\_true\_divide (C member)](c-api/typeobj#c.PyNumberMethods.nb_true_divide) * [PyNumberMethods.nb\_xor (C member)](c-api/typeobj#c.PyNumberMethods.nb_xor) * [PyObject (C type)](c-api/structures#c.PyObject) * [PyObject.\_ob\_next (C member)](c-api/typeobj#c.PyObject._ob_next) * [PyObject.\_ob\_prev (C member)](c-api/typeobj#c.PyObject._ob_prev) * [PyObject.ob\_refcnt (C member)](c-api/typeobj#c.PyObject.ob_refcnt) * [PyObject.ob\_type (C member)](c-api/typeobj#c.PyObject.ob_type) * [PyObject\_AsCharBuffer (C function)](c-api/objbuffer#c.PyObject_AsCharBuffer) * [PyObject\_ASCII (C function)](c-api/object#c.PyObject_ASCII) * [PyObject\_AsFileDescriptor (C function)](c-api/file#c.PyObject_AsFileDescriptor) * [PyObject\_AsReadBuffer (C function)](c-api/objbuffer#c.PyObject_AsReadBuffer) * [PyObject\_AsWriteBuffer (C function)](c-api/objbuffer#c.PyObject_AsWriteBuffer) * [PyObject\_Bytes (C function)](c-api/object#c.PyObject_Bytes) * [PyObject\_Call (C function)](c-api/call#c.PyObject_Call) * [PyObject\_CallFunction (C function)](c-api/call#c.PyObject_CallFunction) * [PyObject\_CallFunctionObjArgs (C function)](c-api/call#c.PyObject_CallFunctionObjArgs) * [PyObject\_CallMethod (C function)](c-api/call#c.PyObject_CallMethod) * [PyObject\_CallMethodNoArgs (C function)](c-api/call#c.PyObject_CallMethodNoArgs) * [PyObject\_CallMethodObjArgs (C function)](c-api/call#c.PyObject_CallMethodObjArgs) * [PyObject\_CallMethodOneArg (C function)](c-api/call#c.PyObject_CallMethodOneArg) * [PyObject\_CallNoArgs (C function)](c-api/call#c.PyObject_CallNoArgs) * [PyObject\_CallObject (C function)](c-api/call#c.PyObject_CallObject) * [PyObject\_CallObject()](extending/extending#index-1) * [PyObject\_Calloc (C function)](c-api/memory#c.PyObject_Calloc) * [PyObject\_CallOneArg (C function)](c-api/call#c.PyObject_CallOneArg) * [PyObject\_CheckBuffer (C function)](c-api/buffer#c.PyObject_CheckBuffer) * [PyObject\_CheckReadBuffer (C function)](c-api/objbuffer#c.PyObject_CheckReadBuffer) * [PyObject\_Del (C function)](c-api/allocation#c.PyObject_Del) * [PyObject\_DelAttr (C function)](c-api/object#c.PyObject_DelAttr) * [PyObject\_DelAttrString (C function)](c-api/object#c.PyObject_DelAttrString) * [PyObject\_DelItem (C function)](c-api/object#c.PyObject_DelItem) * [PyObject\_Dir (C function)](c-api/object#c.PyObject_Dir) * [PyObject\_Free (C function)](c-api/memory#c.PyObject_Free) * [PyObject\_GC\_Del (C function)](c-api/gcsupport#c.PyObject_GC_Del) * [PyObject\_GC\_IsFinalized (C function)](c-api/gcsupport#c.PyObject_GC_IsFinalized) * [PyObject\_GC\_IsTracked (C function)](c-api/gcsupport#c.PyObject_GC_IsTracked) * [PyObject\_GC\_New (C function)](c-api/gcsupport#c.PyObject_GC_New) * [PyObject\_GC\_NewVar (C function)](c-api/gcsupport#c.PyObject_GC_NewVar) * [PyObject\_GC\_Resize (C function)](c-api/gcsupport#c.PyObject_GC_Resize) * [PyObject\_GC\_Track (C function)](c-api/gcsupport#c.PyObject_GC_Track) * [PyObject\_GC\_UnTrack (C function)](c-api/gcsupport#c.PyObject_GC_UnTrack) * [PyObject\_GenericGetAttr (C function)](c-api/object#c.PyObject_GenericGetAttr) * [PyObject\_GenericGetDict (C function)](c-api/object#c.PyObject_GenericGetDict) * [PyObject\_GenericSetAttr (C function)](c-api/object#c.PyObject_GenericSetAttr) * [PyObject\_GenericSetDict (C function)](c-api/object#c.PyObject_GenericSetDict) * [PyObject\_GetArenaAllocator (C function)](c-api/memory#c.PyObject_GetArenaAllocator) * [PyObject\_GetAttr (C function)](c-api/object#c.PyObject_GetAttr) * [PyObject\_GetAttrString (C function)](c-api/object#c.PyObject_GetAttrString) * [PyObject\_GetBuffer (C function)](c-api/buffer#c.PyObject_GetBuffer) * [PyObject\_GetItem (C function)](c-api/object#c.PyObject_GetItem) * [PyObject\_GetIter (C function)](c-api/object#c.PyObject_GetIter) * [PyObject\_HasAttr (C function)](c-api/object#c.PyObject_HasAttr) * [PyObject\_HasAttrString (C function)](c-api/object#c.PyObject_HasAttrString) * [PyObject\_Hash (C function)](c-api/object#c.PyObject_Hash) * [PyObject\_HashNotImplemented (C function)](c-api/object#c.PyObject_HashNotImplemented) * [PyObject\_HEAD (C macro)](c-api/structures#c.PyObject_HEAD) * [PyObject\_HEAD\_INIT (C macro)](c-api/structures#c.PyObject_HEAD_INIT) * [PyObject\_Init (C function)](c-api/allocation#c.PyObject_Init) * [PyObject\_InitVar (C function)](c-api/allocation#c.PyObject_InitVar) * [PyObject\_IS\_GC (C function)](c-api/gcsupport#c.PyObject_IS_GC) * [PyObject\_IsInstance (C function)](c-api/object#c.PyObject_IsInstance) * [PyObject\_IsSubclass (C function)](c-api/object#c.PyObject_IsSubclass) * [PyObject\_IsTrue (C function)](c-api/object#c.PyObject_IsTrue) * [PyObject\_Length (C function)](c-api/object#c.PyObject_Length) * [PyObject\_LengthHint (C function)](c-api/object#c.PyObject_LengthHint) * [PyObject\_Malloc (C function)](c-api/memory#c.PyObject_Malloc) * [PyObject\_New (C function)](c-api/allocation#c.PyObject_New) * [PyObject\_NewVar (C function)](c-api/allocation#c.PyObject_NewVar) * [PyObject\_Not (C function)](c-api/object#c.PyObject_Not) * [PyObject\_Print (C function)](c-api/object#c.PyObject_Print) * [PyObject\_Realloc (C function)](c-api/memory#c.PyObject_Realloc) * [PyObject\_Repr (C function)](c-api/object#c.PyObject_Repr) * [PyObject\_RichCompare (C function)](c-api/object#c.PyObject_RichCompare) * [PyObject\_RichCompareBool (C function)](c-api/object#c.PyObject_RichCompareBool) * [PyObject\_SetArenaAllocator (C function)](c-api/memory#c.PyObject_SetArenaAllocator) * [PyObject\_SetAttr (C function)](c-api/object#c.PyObject_SetAttr) * [PyObject\_SetAttrString (C function)](c-api/object#c.PyObject_SetAttrString) * [PyObject\_SetItem (C function)](c-api/object#c.PyObject_SetItem) * [PyObject\_Size (C function)](c-api/object#c.PyObject_Size) * [PyObject\_Str (C function)](c-api/object#c.PyObject_Str) * [PyObject\_Type (C function)](c-api/object#c.PyObject_Type) * [PyObject\_TypeCheck (C function)](c-api/object#c.PyObject_TypeCheck) * [PyObject\_VAR\_HEAD (C macro)](c-api/structures#c.PyObject_VAR_HEAD) * [PyObject\_Vectorcall (C function)](c-api/call#c.PyObject_Vectorcall) * [PyObject\_VectorcallDict (C function)](c-api/call#c.PyObject_VectorcallDict) * [PyObject\_VectorcallMethod (C function)](c-api/call#c.PyObject_VectorcallMethod) * [PyObjectArenaAllocator (C type)](c-api/memory#c.PyObjectArenaAllocator) * [PyOS\_AfterFork (C function)](c-api/sys#c.PyOS_AfterFork) * [PyOS\_AfterFork\_Child (C function)](c-api/sys#c.PyOS_AfterFork_Child) * [PyOS\_AfterFork\_Parent (C function)](c-api/sys#c.PyOS_AfterFork_Parent) * [PyOS\_BeforeFork (C function)](c-api/sys#c.PyOS_BeforeFork) * [PyOS\_CheckStack (C function)](c-api/sys#c.PyOS_CheckStack) * [PyOS\_double\_to\_string (C function)](c-api/conversion#c.PyOS_double_to_string) * [PyOS\_FSPath (C function)](c-api/sys#c.PyOS_FSPath) * [PyOS\_getsig (C function)](c-api/sys#c.PyOS_getsig) * [PyOS\_InputHook (C variable)](c-api/veryhigh#c.PyOS_InputHook) * [PyOS\_ReadlineFunctionPointer (C variable)](c-api/veryhigh#c.PyOS_ReadlineFunctionPointer) * [PyOS\_setsig (C function)](c-api/sys#c.PyOS_setsig) * [PyOS\_snprintf (C function)](c-api/conversion#c.PyOS_snprintf) * [PyOS\_stricmp (C function)](c-api/conversion#c.PyOS_stricmp) * [PyOS\_string\_to\_double (C function)](c-api/conversion#c.PyOS_string_to_double) * [PyOS\_strnicmp (C function)](c-api/conversion#c.PyOS_strnicmp) * [PyOS\_vsnprintf (C function)](c-api/conversion#c.PyOS_vsnprintf) * [PyParser\_SimpleParseFile (C function)](c-api/veryhigh#c.PyParser_SimpleParseFile) * [PyParser\_SimpleParseFileFlags (C function)](c-api/veryhigh#c.PyParser_SimpleParseFileFlags) * [PyParser\_SimpleParseString (C function)](c-api/veryhigh#c.PyParser_SimpleParseString) * [PyParser\_SimpleParseStringFlags (C function)](c-api/veryhigh#c.PyParser_SimpleParseStringFlags) * [PyParser\_SimpleParseStringFlagsFilename (C function)](c-api/veryhigh#c.PyParser_SimpleParseStringFlagsFilename) * PyPI + [(see Python Package Index (PyPI))](distributing/index#index-1) * [PyPreConfig (C type)](c-api/init_config#c.PyPreConfig) * [PyPreConfig.allocator (C member)](c-api/init_config#c.PyPreConfig.allocator) * [PyPreConfig.coerce\_c\_locale (C member)](c-api/init_config#c.PyPreConfig.coerce_c_locale) * [PyPreConfig.coerce\_c\_locale\_warn (C member)](c-api/init_config#c.PyPreConfig.coerce_c_locale_warn) * [PyPreConfig.configure\_locale (C member)](c-api/init_config#c.PyPreConfig.configure_locale) * [PyPreConfig.dev\_mode (C member)](c-api/init_config#c.PyPreConfig.dev_mode) * [PyPreConfig.isolated (C member)](c-api/init_config#c.PyPreConfig.isolated) * [PyPreConfig.legacy\_windows\_fs\_encoding (C member)](c-api/init_config#c.PyPreConfig.legacy_windows_fs_encoding) * [PyPreConfig.parse\_argv (C member)](c-api/init_config#c.PyPreConfig.parse_argv) * [PyPreConfig.use\_environment (C member)](c-api/init_config#c.PyPreConfig.use_environment) * [PyPreConfig.utf8\_mode (C member)](c-api/init_config#c.PyPreConfig.utf8_mode) * [PyPreConfig\_InitIsolatedConfig (C function)](c-api/init_config#c.PyPreConfig_InitIsolatedConfig) * [PyPreConfig\_InitPythonConfig (C function)](c-api/init_config#c.PyPreConfig_InitPythonConfig) * [PyProperty\_Type (C variable)](c-api/descriptor#c.PyProperty_Type) * [PyRun\_AnyFile (C function)](c-api/veryhigh#c.PyRun_AnyFile) * [PyRun\_AnyFileEx (C function)](c-api/veryhigh#c.PyRun_AnyFileEx) * [PyRun\_AnyFileExFlags (C function)](c-api/veryhigh#c.PyRun_AnyFileExFlags) * [PyRun\_AnyFileFlags (C function)](c-api/veryhigh#c.PyRun_AnyFileFlags) * [PyRun\_File (C function)](c-api/veryhigh#c.PyRun_File) * [PyRun\_FileEx (C function)](c-api/veryhigh#c.PyRun_FileEx) * [PyRun\_FileExFlags (C function)](c-api/veryhigh#c.PyRun_FileExFlags) * [PyRun\_FileFlags (C function)](c-api/veryhigh#c.PyRun_FileFlags) * [PyRun\_InteractiveLoop (C function)](c-api/veryhigh#c.PyRun_InteractiveLoop) * [PyRun\_InteractiveLoopFlags (C function)](c-api/veryhigh#c.PyRun_InteractiveLoopFlags) * [PyRun\_InteractiveOne (C function)](c-api/veryhigh#c.PyRun_InteractiveOne) * [PyRun\_InteractiveOneFlags (C function)](c-api/veryhigh#c.PyRun_InteractiveOneFlags) * [PyRun\_SimpleFile (C function)](c-api/veryhigh#c.PyRun_SimpleFile) * [PyRun\_SimpleFileEx (C function)](c-api/veryhigh#c.PyRun_SimpleFileEx) * [PyRun\_SimpleFileExFlags (C function)](c-api/veryhigh#c.PyRun_SimpleFileExFlags) * [PyRun\_SimpleString (C function)](c-api/veryhigh#c.PyRun_SimpleString) * [PyRun\_SimpleStringFlags (C function)](c-api/veryhigh#c.PyRun_SimpleStringFlags) * [PyRun\_String (C function)](c-api/veryhigh#c.PyRun_String) * [PyRun\_StringFlags (C function)](c-api/veryhigh#c.PyRun_StringFlags) * [PySeqIter\_Check (C function)](c-api/iterator#c.PySeqIter_Check) * [PySeqIter\_New (C function)](c-api/iterator#c.PySeqIter_New) * [PySeqIter\_Type (C variable)](c-api/iterator#c.PySeqIter_Type) * [PySequence\_Check (C function)](c-api/sequence#c.PySequence_Check) * [PySequence\_Concat (C function)](c-api/sequence#c.PySequence_Concat) * [PySequence\_Contains (C function)](c-api/sequence#c.PySequence_Contains) * [PySequence\_Count (C function)](c-api/sequence#c.PySequence_Count) * [PySequence\_DelItem (C function)](c-api/sequence#c.PySequence_DelItem) * [PySequence\_DelSlice (C function)](c-api/sequence#c.PySequence_DelSlice) * [PySequence\_Fast (C function)](c-api/sequence#c.PySequence_Fast) * [PySequence\_Fast\_GET\_ITEM (C function)](c-api/sequence#c.PySequence_Fast_GET_ITEM) * [PySequence\_Fast\_GET\_SIZE (C function)](c-api/sequence#c.PySequence_Fast_GET_SIZE) * [PySequence\_Fast\_ITEMS (C function)](c-api/sequence#c.PySequence_Fast_ITEMS) * [PySequence\_GetItem (C function)](c-api/sequence#c.PySequence_GetItem) * [PySequence\_GetItem()](c-api/intro#index-12) * [PySequence\_GetSlice (C function)](c-api/sequence#c.PySequence_GetSlice) * [PySequence\_Index (C function)](c-api/sequence#c.PySequence_Index) * [PySequence\_InPlaceConcat (C function)](c-api/sequence#c.PySequence_InPlaceConcat) * [PySequence\_InPlaceRepeat (C function)](c-api/sequence#c.PySequence_InPlaceRepeat) * [PySequence\_ITEM (C function)](c-api/sequence#c.PySequence_ITEM) * [PySequence\_Length (C function)](c-api/sequence#c.PySequence_Length) * [PySequence\_List (C function)](c-api/sequence#c.PySequence_List) * [PySequence\_Repeat (C function)](c-api/sequence#c.PySequence_Repeat) * [PySequence\_SetItem (C function)](c-api/sequence#c.PySequence_SetItem) * [PySequence\_SetSlice (C function)](c-api/sequence#c.PySequence_SetSlice) * [PySequence\_Size (C function)](c-api/sequence#c.PySequence_Size) * [PySequence\_Tuple (C function)](c-api/sequence#c.PySequence_Tuple) * [PySequenceMethods (C type)](c-api/typeobj#c.PySequenceMethods) * [PySequenceMethods.sq\_ass\_item (C member)](c-api/typeobj#c.PySequenceMethods.sq_ass_item) * [PySequenceMethods.sq\_concat (C member)](c-api/typeobj#c.PySequenceMethods.sq_concat) * [PySequenceMethods.sq\_contains (C member)](c-api/typeobj#c.PySequenceMethods.sq_contains) * [PySequenceMethods.sq\_inplace\_concat (C member)](c-api/typeobj#c.PySequenceMethods.sq_inplace_concat) * [PySequenceMethods.sq\_inplace\_repeat (C member)](c-api/typeobj#c.PySequenceMethods.sq_inplace_repeat) * [PySequenceMethods.sq\_item (C member)](c-api/typeobj#c.PySequenceMethods.sq_item) * [PySequenceMethods.sq\_length (C member)](c-api/typeobj#c.PySequenceMethods.sq_length) * [PySequenceMethods.sq\_repeat (C member)](c-api/typeobj#c.PySequenceMethods.sq_repeat) * [PySet\_Add (C function)](c-api/set#c.PySet_Add) * [PySet\_Check (C function)](c-api/set#c.PySet_Check) * [PySet\_Clear (C function)](c-api/set#c.PySet_Clear) * [PySet\_Contains (C function)](c-api/set#c.PySet_Contains) * [PySet\_Discard (C function)](c-api/set#c.PySet_Discard) * [PySet\_GET\_SIZE (C function)](c-api/set#c.PySet_GET_SIZE) * [PySet\_New (C function)](c-api/set#c.PySet_New) * [PySet\_Pop (C function)](c-api/set#c.PySet_Pop) * [PySet\_Size (C function)](c-api/set#c.PySet_Size) * [PySet\_Type (C variable)](c-api/set#c.PySet_Type) * [PySetObject (C type)](c-api/set#c.PySetObject) * [PySignal\_SetWakeupFd (C function)](c-api/exceptions#c.PySignal_SetWakeupFd) * [PySlice\_AdjustIndices (C function)](c-api/slice#c.PySlice_AdjustIndices) * [PySlice\_Check (C function)](c-api/slice#c.PySlice_Check) * [PySlice\_GetIndices (C function)](c-api/slice#c.PySlice_GetIndices) * [PySlice\_GetIndicesEx (C function)](c-api/slice#c.PySlice_GetIndicesEx) * [PySlice\_New (C function)](c-api/slice#c.PySlice_New) * [PySlice\_Type (C variable)](c-api/slice#c.PySlice_Type) * [PySlice\_Unpack (C function)](c-api/slice#c.PySlice_Unpack) * [PyState\_AddModule (C function)](c-api/module#c.PyState_AddModule) * [PyState\_FindModule (C function)](c-api/module#c.PyState_FindModule) * [PyState\_RemoveModule (C function)](c-api/module#c.PyState_RemoveModule) * [PyStatus (C type)](c-api/init_config#c.PyStatus) * [PyStatus.err\_msg (C member)](c-api/init_config#c.PyStatus.err_msg) * [PyStatus.exitcode (C member)](c-api/init_config#c.PyStatus.exitcode) * [PyStatus.func (C member)](c-api/init_config#c.PyStatus.func) * [PyStatus\_Error (C function)](c-api/init_config#c.PyStatus_Error) * [PyStatus\_Exception (C function)](c-api/init_config#c.PyStatus_Exception) * [PyStatus\_Exit (C function)](c-api/init_config#c.PyStatus_Exit) * [PyStatus\_IsError (C function)](c-api/init_config#c.PyStatus_IsError) * [PyStatus\_IsExit (C function)](c-api/init_config#c.PyStatus_IsExit) * [PyStatus\_NoMemory (C function)](c-api/init_config#c.PyStatus_NoMemory) * [PyStatus\_Ok (C function)](c-api/init_config#c.PyStatus_Ok) * [PyStructSequence\_Desc (C type)](c-api/tuple#c.PyStructSequence_Desc) * [PyStructSequence\_Field (C type)](c-api/tuple#c.PyStructSequence_Field) * [PyStructSequence\_GET\_ITEM (C function)](c-api/tuple#c.PyStructSequence_GET_ITEM) * [PyStructSequence\_GetItem (C function)](c-api/tuple#c.PyStructSequence_GetItem) * [PyStructSequence\_InitType (C function)](c-api/tuple#c.PyStructSequence_InitType) * [PyStructSequence\_InitType2 (C function)](c-api/tuple#c.PyStructSequence_InitType2) * [PyStructSequence\_New (C function)](c-api/tuple#c.PyStructSequence_New) * [PyStructSequence\_NewType (C function)](c-api/tuple#c.PyStructSequence_NewType) * [PyStructSequence\_SET\_ITEM (C function)](c-api/tuple#c.PyStructSequence_SET_ITEM) * [PyStructSequence\_SetItem (C function)](c-api/tuple#c.PyStructSequence_SetItem) * [PyStructSequence\_UnnamedField (C variable)](c-api/tuple#c.PyStructSequence_UnnamedField) * [PySys\_AddAuditHook (C function)](c-api/sys#c.PySys_AddAuditHook) * [PySys\_AddWarnOption (C function)](c-api/sys#c.PySys_AddWarnOption) * [PySys\_AddWarnOptionUnicode (C function)](c-api/sys#c.PySys_AddWarnOptionUnicode) * [PySys\_AddXOption (C function)](c-api/sys#c.PySys_AddXOption) * [PySys\_Audit (C function)](c-api/sys#c.PySys_Audit) * [PySys\_FormatStderr (C function)](c-api/sys#c.PySys_FormatStderr) * [PySys\_FormatStdout (C function)](c-api/sys#c.PySys_FormatStdout) * [PySys\_GetObject (C function)](c-api/sys#c.PySys_GetObject) * [PySys\_GetXOptions (C function)](c-api/sys#c.PySys_GetXOptions) * [PySys\_ResetWarnOptions (C function)](c-api/sys#c.PySys_ResetWarnOptions) * [PySys\_SetArgv (C function)](c-api/init#c.PySys_SetArgv) * [PySys\_SetArgv()](c-api/init#index-16) * [PySys\_SetArgvEx (C function)](c-api/init#c.PySys_SetArgvEx) * [PySys\_SetArgvEx()](c-api/init#index-16), [[1]](c-api/intro#index-24) * [PySys\_SetObject (C function)](c-api/sys#c.PySys_SetObject) * [PySys\_SetPath (C function)](c-api/sys#c.PySys_SetPath) * [PySys\_WriteStderr (C function)](c-api/sys#c.PySys_WriteStderr) * [PySys\_WriteStdout (C function)](c-api/sys#c.PySys_WriteStdout) * [**Python 3000**](glossary#term-python-3000) * [Python Editor](library/idle#index-0) * Python Enhancement Proposals + [PEP 1](glossary#index-30), [[1]](https://docs.python.org/3.9/whatsnew/2.0.html#index-0), [[2]](https://docs.python.org/3.9/whatsnew/2.0.html#index-1) + [PEP 100](https://docs.python.org/3.9/whatsnew/2.0.html#index-3) + [PEP 11](using/windows#index-0), [[1]](using/windows#index-27), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-19), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-50), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-5), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-105) + [PEP 201](https://docs.python.org/3.9/whatsnew/2.0.html#index-2) + [PEP 205](library/weakref#index-2), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-9) + [PEP 207](https://docs.python.org/3.9/whatsnew/2.1.html#index-4), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-5) + [PEP 208](https://docs.python.org/3.9/whatsnew/2.1.html#index-13) + [PEP 217](https://docs.python.org/3.9/whatsnew/2.1.html#index-12) + [PEP 218](https://docs.python.org/3.9/whatsnew/2.3.html#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-0), [[2]](https://docs.python.org/3.9/whatsnew/2.4.html#index-13) + [PEP 227](library/__future__#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-2), [[2]](https://docs.python.org/3.9/whatsnew/2.2.html#index-16) + [PEP 229](https://docs.python.org/3.9/whatsnew/2.1.html#index-8) + [PEP 230](https://docs.python.org/3.9/whatsnew/2.1.html#index-7) + [PEP 232](https://docs.python.org/3.9/whatsnew/2.1.html#index-10) + [PEP 234](https://docs.python.org/3.9/whatsnew/2.2.html#index-7) + [PEP 235](library/importlib#index-0) + [PEP 236](reference/simple_stmts#index-42), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-0), [[2]](https://docs.python.org/3.9/whatsnew/2.1.html#index-1), [[3]](https://docs.python.org/3.9/whatsnew/2.1.html#index-3) + [PEP 237](library/stdtypes#index-36), [[1]](library/stdtypes#index-46), [[2]](https://docs.python.org/3.9/whatsnew/2.2.html#index-10), [[3]](https://docs.python.org/3.9/whatsnew/2.4.html#index-1), [[4]](https://docs.python.org/3.9/whatsnew/2.4.html#index-16), [[5]](https://docs.python.org/3.9/whatsnew/3.0.html#index-1) + [PEP 238](c-api/veryhigh#index-3), [[1]](glossary#index-17), [[2]](library/__future__#index-2), [[3]](https://docs.python.org/3.9/whatsnew/2.2.html#index-11), [[4]](https://docs.python.org/3.9/whatsnew/2.2.html#index-12), [[5]](https://docs.python.org/3.9/whatsnew/2.2.html#index-13), [[6]](https://docs.python.org/3.9/whatsnew/3.0.html#index-2) + [PEP 241](https://docs.python.org/3.9/whatsnew/2.1.html#index-14), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-15), [[2]](https://docs.python.org/3.9/whatsnew/2.1.html#index-16) + [PEP 243](https://docs.python.org/3.9/whatsnew/2.1.html#index-17) + [PEP 247](https://docs.python.org/3.9/whatsnew/3.4.html#index-37) + [PEP 249](library/sqlite3#index-0), [[1]](library/sqlite3#index-1), [[2]](https://docs.python.org/3.9/whatsnew/2.5.html#index-24), [[3]](https://docs.python.org/3.9/whatsnew/2.5.html#index-25) + [PEP 252](reference/datamodel#index-81), [[1]](https://docs.python.org/3.9/whatsnew/2.2.html#index-2), [[2]](https://docs.python.org/3.9/whatsnew/2.2.html#index-4) + [PEP 253](https://docs.python.org/3.9/whatsnew/2.2.html#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.2.html#index-1), [[2]](https://docs.python.org/3.9/whatsnew/2.2.html#index-3), [[3]](https://docs.python.org/3.9/whatsnew/2.2.html#index-5), [[4]](https://docs.python.org/3.9/whatsnew/2.2.html#index-6) + [PEP 255](library/__future__#index-1), [[1]](reference/expressions#index-26), [[2]](https://docs.python.org/3.9/whatsnew/2.2.html#index-8), [[3]](https://docs.python.org/3.9/whatsnew/2.2.html#index-9), [[4]](https://docs.python.org/3.9/whatsnew/2.3.html#index-1), [[5]](https://docs.python.org/3.9/whatsnew/2.3.html#index-2) + [PEP 261](https://docs.python.org/3.9/whatsnew/2.2.html#index-14), [[1]](https://docs.python.org/3.9/whatsnew/2.2.html#index-15) + [PEP 263](howto/unicode#index-0), [[1]](library/importlib#index-1), [[2]](library/tokenize#index-0), [[3]](library/tokenize#index-1), [[4]](https://docs.python.org/3.9/whatsnew/2.3.html#index-3), [[5]](https://docs.python.org/3.9/whatsnew/2.5.html#index-19), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-4) + [PEP 264](https://docs.python.org/3.9/whatsnew/2.2.html#index-22) + [PEP 273](library/zipimport#index-0), [[1]](library/zipimport#index-1), [[2]](https://docs.python.org/3.9/whatsnew/2.3.html#index-4), [[3]](https://docs.python.org/3.9/whatsnew/2.3.html#index-5) + [PEP 274](https://docs.python.org/3.9/whatsnew/3.0.html#index-10) + [PEP 275](faq/design#index-1) + [PEP 277](https://docs.python.org/3.9/whatsnew/2.3.html#index-7) + [PEP 278](glossary#index-37), [[1]](https://docs.python.org/3.9/whatsnew/2.3.html#index-9) + [PEP 279](https://docs.python.org/3.9/whatsnew/2.3.html#index-10) + [PEP 282](distutils/apiref#index-7), [[1]](library/logging#index-1), [[2]](library/shutil#index-2), [[3]](https://docs.python.org/3.9/whatsnew/2.3.html#index-11), [[4]](https://docs.python.org/3.9/whatsnew/2.3.html#index-12) + [PEP 285](https://docs.python.org/3.9/whatsnew/2.3.html#index-13), [[1]](https://docs.python.org/3.9/whatsnew/2.3.html#index-14) + [PEP 288](https://docs.python.org/3.9/whatsnew/2.5.html#index-12) + [PEP 289](howto/functional#index-1), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-15), [[2]](https://docs.python.org/3.9/whatsnew/2.4.html#index-2) + [PEP 292](library/string#index-10), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-3) + [PEP 293](https://docs.python.org/3.9/whatsnew/2.3.html#index-15) + [PEP 3000](https://docs.python.org/3.9/whatsnew/2.6.html#index-1) + [PEP 301](distutils/apiref#index-8), [[1]](https://docs.python.org/3.9/whatsnew/2.3.html#index-16) + [PEP 302](glossary#index-14), [[1]](glossary#index-25), [[2]](library/functions#index-13), [[3]](library/imp#index-7), [[4]](library/importlib#index-12), [[5]](library/importlib#index-13), [[6]](library/importlib#index-14), [[7]](library/importlib#index-15), [[8]](library/importlib#index-17), [[9]](library/importlib#index-2), [[10]](library/linecache#index-1), [[11]](library/pkgutil#index-0), [[12]](library/pkgutil#index-1), [[13]](library/pkgutil#index-10), [[14]](library/pkgutil#index-11), [[15]](library/pkgutil#index-12), [[16]](library/pkgutil#index-2), [[17]](library/pkgutil#index-3), [[18]](library/pkgutil#index-4), [[19]](library/pkgutil#index-5), [[20]](library/pkgutil#index-7), [[21]](library/pkgutil#index-8), [[22]](library/runpy#index-1), [[23]](library/sys#index-24), [[24]](library/sys#index-25), [[25]](library/zipimport#index-2), [[26]](library/zipimport#index-3), [[27]](reference/import#index-1), [[28]](reference/import#index-19), [[29]](https://docs.python.org/3.9/whatsnew/2.3.html#index-17), [[30]](https://docs.python.org/3.9/whatsnew/2.3.html#index-18), [[31]](https://docs.python.org/3.9/whatsnew/2.3.html#index-19), [[32]](https://docs.python.org/3.9/whatsnew/2.3.html#index-6), [[33]](https://docs.python.org/3.9/whatsnew/2.5.html#index-21), [[34]](https://docs.python.org/3.9/whatsnew/3.1.html#index-2), [[35]](https://docs.python.org/3.9/whatsnew/3.3.html#index-20), [[36]](https://docs.python.org/3.9/whatsnew/3.3.html#index-21), [[37]](https://docs.python.org/3.9/whatsnew/3.3.html#index-37) + [PEP 305](library/csv#index-2), [[1]](https://docs.python.org/3.9/whatsnew/2.3.html#index-20) + [PEP 307](library/pickle#index-2), [[1]](https://docs.python.org/3.9/whatsnew/2.3.html#index-21), [[2]](https://docs.python.org/3.9/whatsnew/2.3.html#index-22), [[3]](https://docs.python.org/3.9/whatsnew/2.3.html#index-23) + [PEP 308](reference/expressions#index-88), [[1]](https://docs.python.org/3.9/whatsnew/2.5.html#index-1), [[2]](https://docs.python.org/3.9/whatsnew/2.5.html#index-2) + [PEP 309](https://docs.python.org/3.9/whatsnew/2.5.html#index-3) + [PEP 3100](https://docs.python.org/3.9/whatsnew/2.6.html#index-2) + [PEP 3101](library/string#index-0), [[1]](library/string#index-1), [[2]](https://docs.python.org/3.9/whatsnew/2.6.html#index-9), [[3]](https://docs.python.org/3.9/whatsnew/3.0.html#index-23), [[4]](https://docs.python.org/3.9/whatsnew/3.0.html#index-24) + [PEP 3102](https://docs.python.org/3.9/whatsnew/3.0.html#index-7) + [PEP 3104](reference/simple_stmts#index-46), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-8) + [PEP 3105](library/__future__#index-5), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-10), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-0) + [PEP 3106](https://docs.python.org/3.9/whatsnew/2.7.html#index-6) + [PEP 3107](reference/compound_stmts#index-27), [[1]](tutorial/controlflow#index-6), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-6), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-9), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-0) + [PEP 3108](https://docs.python.org/3.9/whatsnew/3.0.html#index-17), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-20), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-22) + [PEP 3109](https://docs.python.org/3.9/whatsnew/3.0.html#index-11), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-26) + [PEP 3110](https://docs.python.org/3.9/whatsnew/2.6.html#index-11), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-13), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-27) + [PEP 3111](https://docs.python.org/3.9/whatsnew/3.0.html#index-32) + [PEP 3112](library/__future__#index-6), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-12) + [PEP 3113](https://docs.python.org/3.9/whatsnew/3.0.html#index-15) + [PEP 3114](https://docs.python.org/3.9/whatsnew/3.0.html#index-30) + [PEP 3115](library/types#index-0), [[1]](reference/compound_stmts#index-34), [[2]](reference/datamodel#index-86), [[3]](https://docs.python.org/3.9/whatsnew/3.0.html#index-14), [[4]](https://docs.python.org/3.9/whatsnew/3.3.html#index-29) + [PEP 3116](glossary#index-38), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-14), [[2]](https://docs.python.org/3.9/whatsnew/3.1.html#index-3) + [PEP 3118](library/stdtypes#index-48), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-15), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-33), [[3]](https://docs.python.org/3.9/whatsnew/3.3.html#index-31), [[4]](https://docs.python.org/3.9/whatsnew/3.3.html#index-4), [[5]](https://docs.python.org/3.9/whatsnew/3.3.html#index-5), [[6]](https://docs.python.org/3.9/whatsnew/3.8.html#index-8), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-103), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-110), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-155) + [PEP 3119](c-api/object#index-4), [[1]](c-api/object#index-5), [[2]](library/abc#index-0), [[3]](library/collections.abc#index-4), [[4]](reference/datamodel#index-90), [[5]](https://docs.python.org/3.9/whatsnew/2.6.html#index-16) + [PEP 3120](library/importlib#index-10), [[1]](reference/lexical_analysis#index-1), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-4) + [PEP 3121](c-api/module#index-6), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-34) + [PEP 3123](https://docs.python.org/3.9/whatsnew/3.0.html#index-35) + [PEP 3127](https://docs.python.org/3.9/whatsnew/2.6.html#index-17) + [PEP 3129](reference/compound_stmts#index-35), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-18) + [PEP 3131](reference/lexical_analysis#index-11), [[1]](reference/lexical_analysis#index-12), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-5) + [PEP 3132](reference/simple_stmts#index-13), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-9) + [PEP 3134](https://docs.python.org/3.9/whatsnew/3.0.html#index-12), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-28), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-29) + [PEP 3135](reference/datamodel#index-89), [[1]](https://docs.python.org/3.9/whatsnew/3.0.html#index-31) + [PEP 3137](https://docs.python.org/3.9/whatsnew/2.7.html#index-7) + [PEP 3138](https://docs.python.org/3.9/whatsnew/3.0.html#index-3) + [PEP 314](distutils/apiref#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.5.html#index-4) + [PEP 3141](library/abc#index-1), [[1]](library/numbers#index-0), [[2]](https://docs.python.org/3.9/whatsnew/2.6.html#index-19) + [PEP 3144](https://docs.python.org/3.9/whatsnew/3.3.html#index-25) + [PEP 3147](c-api/import#index-3), [[1]](distutils/apiref#index-3), [[2]](faq/programming#index-3), [[3]](library/compileall#index-0), [[4]](library/compileall#index-2), [[5]](library/compileall#index-3), [[6]](library/imp#index-2), [[7]](library/imp#index-3), [[8]](library/imp#index-4), [[9]](library/imp#index-5), [[10]](library/imp#index-6), [[11]](library/importlib#index-11), [[12]](library/importlib#index-21), [[13]](library/importlib#index-23), [[14]](library/importlib#index-24), [[15]](library/py_compile#index-1), [[16]](library/py_compile#index-4), [[17]](library/runpy#index-2), [[18]](library/test#index-0), [[19]](reference/import#index-13), [[20]](tutorial/modules#index-3), [[21]](https://docs.python.org/3.9/whatsnew/3.2.html#index-5), [[22]](https://docs.python.org/3.9/whatsnew/3.3.html#index-18) + [PEP 3148](library/concurrent.futures#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-4) + [PEP 3149](library/sys#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-6), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-150) + [PEP 3151](c-api/exceptions#index-4), [[1]](library/exceptions#index-7), [[2]](library/resource#index-0), [[3]](library/select#index-0), [[4]](library/socket#index-2), [[5]](https://docs.python.org/3.9/whatsnew/3.3.html#index-10) + [PEP 3154](library/pickle#index-3), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-12), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-39), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-75) + [PEP 3155](glossary#index-33), [[1]](https://docs.python.org/3.9/whatsnew/3.3.html#index-15) + [PEP 3156](https://docs.python.org/3.9/whatsnew/3.4.html#index-25), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-26), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-31), [[3]](https://docs.python.org/3.9/whatsnew/3.4.html#index-4), [[4]](https://docs.python.org/3.9/whatsnew/3.4.html#index-8) + [PEP 318](reference/compound_stmts#index-36), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-12), [[2]](https://docs.python.org/3.9/whatsnew/2.4.html#index-4), [[3]](https://docs.python.org/3.9/whatsnew/2.4.html#index-5) + [PEP 322](https://docs.python.org/3.9/whatsnew/2.4.html#index-14), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-6) + [PEP 324](library/subprocess#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-8) + [PEP 325](https://docs.python.org/3.9/whatsnew/2.5.html#index-13) + [PEP 327](https://docs.python.org/3.9/whatsnew/2.4.html#index-9) + [PEP 328](library/__future__#index-3), [[1]](library/functions#index-14), [[2]](library/importlib#index-3), [[3]](reference/import#index-24), [[4]](https://docs.python.org/3.9/whatsnew/2.4.html#index-10), [[5]](https://docs.python.org/3.9/whatsnew/2.4.html#index-17), [[6]](https://docs.python.org/3.9/whatsnew/2.5.html#index-5), [[7]](https://docs.python.org/3.9/whatsnew/2.5.html#index-6), [[8]](https://docs.python.org/3.9/whatsnew/3.0.html#index-16), [[9]](https://docs.python.org/3.9/whatsnew/3.3.html#index-36) + [PEP 331](https://docs.python.org/3.9/whatsnew/2.4.html#index-11) + [PEP 333](https://docs.python.org/3.9/whatsnew/2.5.html#index-26), [[1]](https://docs.python.org/3.9/whatsnew/2.5.html#index-27) + [PEP 3333](library/wsgiref#index-0), [[1]](library/wsgiref#index-1), [[2]](library/wsgiref#index-11), [[3]](library/wsgiref#index-12), [[4]](library/wsgiref#index-13), [[5]](library/wsgiref#index-14), [[6]](library/wsgiref#index-15), [[7]](library/wsgiref#index-16), [[8]](library/wsgiref#index-2), [[9]](library/wsgiref#index-3), [[10]](library/wsgiref#index-4), [[11]](library/wsgiref#index-6), [[12]](library/wsgiref#index-7), [[13]](library/wsgiref#index-8), [[14]](library/wsgiref#index-9), [[15]](https://docs.python.org/3.9/whatsnew/3.2.html#index-9) + [PEP 338](library/runpy#index-6), [[1]](reference/import#index-26), [[2]](using/cmdline#index-1), [[3]](https://docs.python.org/3.9/whatsnew/2.5.html#index-7) + [PEP 339](https://docs.python.org/3.9/whatsnew/2.5.html#index-30) + [PEP 341](https://docs.python.org/3.9/whatsnew/2.5.html#index-8) + [PEP 342](howto/functional#index-0), [[1]](howto/functional#index-2), [[2]](library/collections.abc#index-1), [[3]](reference/expressions#index-27), [[4]](https://docs.python.org/3.9/whatsnew/2.5.html#index-11), [[5]](https://docs.python.org/3.9/whatsnew/2.5.html#index-31), [[6]](https://docs.python.org/3.9/whatsnew/2.5.html#index-9) + [PEP 343](glossary#index-9), [[1]](library/__future__#index-4), [[2]](library/contextlib#index-0), [[3]](reference/compound_stmts#index-17), [[4]](reference/datamodel#index-103), [[5]](https://docs.python.org/3.9/whatsnew/2.5.html#index-10), [[6]](https://docs.python.org/3.9/whatsnew/2.5.html#index-14), [[7]](https://docs.python.org/3.9/whatsnew/2.6.html#index-3) + [PEP 347](https://docs.python.org/3.9/whatsnew/2.5.html#index-28) + [PEP 352](https://docs.python.org/3.9/whatsnew/2.5.html#index-15), [[1]](https://docs.python.org/3.9/whatsnew/2.6.html#index-25), [[2]](https://docs.python.org/3.9/whatsnew/3.0.html#index-25) + [PEP 353](c-api/intro#index-15), [[1]](https://docs.python.org/3.9/whatsnew/2.5.html#index-16), [[2]](https://docs.python.org/3.9/whatsnew/2.5.html#index-17), [[3]](https://docs.python.org/3.9/whatsnew/2.5.html#index-29) + [PEP 356](https://docs.python.org/3.9/whatsnew/2.5.html#index-0) + [PEP 357](https://docs.python.org/3.9/whatsnew/2.5.html#index-18) + [PEP 361](https://docs.python.org/3.9/whatsnew/2.6.html#index-0) + [PEP 362](glossary#index-2), [[1]](glossary#index-28), [[2]](library/inspect#index-0), [[3]](https://docs.python.org/3.9/whatsnew/3.3.html#index-17) + [PEP 366](library/importlib#index-4), [[1]](library/runpy#index-7), [[2]](reference/import#index-11), [[3]](reference/import#index-12), [[4]](reference/import#index-23), [[5]](reference/import#index-25), [[6]](https://docs.python.org/3.9/whatsnew/3.3.html#index-22) + [PEP 370](library/site#index-11), [[1]](using/cmdline#index-18), [[2]](using/cmdline#index-38), [[3]](using/cmdline#index-39), [[4]](https://docs.python.org/3.9/whatsnew/2.6.html#index-7) + [PEP 371](https://docs.python.org/3.9/whatsnew/2.6.html#index-8) + [PEP 372](https://docs.python.org/3.9/whatsnew/2.7.html#index-2), [[1]](https://docs.python.org/3.9/whatsnew/3.1.html#index-0) + [PEP 373](https://docs.python.org/3.9/whatsnew/2.7.html#index-0) + [PEP 378](library/string#index-7), [[1]](https://docs.python.org/3.9/whatsnew/2.7.html#index-3), [[2]](https://docs.python.org/3.9/whatsnew/3.1.html#index-1) + [PEP 380](reference/expressions#index-28), [[1]](https://docs.python.org/3.9/whatsnew/3.3.html#index-12) + [PEP 383](c-api/unicode#index-3), [[1]](c-api/unicode#index-4), [[2]](c-api/unicode#index-5), [[3]](library/codecs#index-2), [[4]](library/socket#index-1), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-0) + [PEP 384](c-api/stable#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-1) + [PEP 385](https://docs.python.org/3.9/whatsnew/3.2.html#index-14) + [PEP 387](library/exceptions#index-10), [[1]](library/exceptions#index-9) + [PEP 389](https://docs.python.org/3.9/whatsnew/2.7.html#index-4), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-2) + [PEP 391](https://docs.python.org/3.9/whatsnew/2.7.html#index-5), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-3) + [PEP 392](https://docs.python.org/3.9/whatsnew/3.2.html#index-0) + [PEP 393](c-api/unicode#index-0), [[1]](c-api/unicode#index-2), [[2]](library/codecs#index-5), [[3]](library/sys#index-19), [[4]](https://docs.python.org/3.9/whatsnew/3.3.html#index-30), [[5]](https://docs.python.org/3.9/whatsnew/3.3.html#index-32), [[6]](https://docs.python.org/3.9/whatsnew/3.3.html#index-33), [[7]](https://docs.python.org/3.9/whatsnew/3.3.html#index-34), [[8]](https://docs.python.org/3.9/whatsnew/3.3.html#index-38), [[9]](https://docs.python.org/3.9/whatsnew/3.3.html#index-6), [[10]](https://docs.python.org/3.9/whatsnew/3.3.html#index-7), [[11]](https://docs.python.org/3.9/whatsnew/3.3.html#index-8), [[12]](https://docs.python.org/3.9/whatsnew/3.9.html#index-25), [[13]](https://docs.python.org/3.9/whatsnew/3.9.html#index-26) + [PEP 395](reference/import#index-18) + [PEP 397](library/venv#index-3), [[1]](using/windows#index-15), [[2]](https://docs.python.org/3.9/whatsnew/3.3.html#index-9), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-22) + [PEP 398](https://docs.python.org/3.9/whatsnew/3.3.html#index-0) + [PEP 4](https://docs.python.org/3.9/whatsnew/3.0.html#index-18) + [PEP 405](library/venv#index-1), [[1]](https://docs.python.org/3.9/whatsnew/3.3.html#index-1) + [PEP 409](https://docs.python.org/3.9/whatsnew/3.3.html#index-13) + [PEP 411](glossary#index-32), [[1]](library/sys#index-13), [[2]](library/sys#index-14), [[3]](library/sys#index-30), [[4]](library/sys#index-31) + [PEP 412](library/functools#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.3.html#index-16) + [PEP 414](reference/lexical_analysis#index-20), [[1]](https://docs.python.org/3.9/whatsnew/3.3.html#index-14) + [PEP 418](https://docs.python.org/3.9/whatsnew/3.3.html#index-28) + [PEP 420](glossary#index-15), [[1]](glossary#index-27), [[2]](glossary#index-31), [[3]](library/importlib#index-5), [[4]](reference/import#index-14), [[5]](reference/import#index-15), [[6]](reference/import#index-2), [[7]](reference/import#index-20), [[8]](reference/import#index-21), [[9]](reference/import#index-22), [[10]](reference/import#index-6), [[11]](https://docs.python.org/3.9/whatsnew/3.3.html#index-2), [[12]](https://docs.python.org/3.9/whatsnew/3.3.html#index-3), [[13]](https://docs.python.org/3.9/whatsnew/changelog.html#index-136), [[14]](https://docs.python.org/3.9/whatsnew/changelog.html#index-143) + [PEP 421](library/sys#index-15), [[1]](library/sys#index-16), [[2]](https://docs.python.org/3.9/whatsnew/3.3.html#index-19) + [PEP 424](https://docs.python.org/3.9/whatsnew/3.4.html#index-24), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-38) + [PEP 427](distributing/index#index-0) + [PEP 428](library/pathlib#index-1), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-30), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-7) + [PEP 429](https://docs.python.org/3.9/whatsnew/3.4.html#index-0) + [PEP 432](c-api/init_config#index-10), [[1]](c-api/init_config#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-38), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-102) + [PEP 434](https://docs.python.org/3.9/whatsnew/2.7.html#index-16) + [PEP 435](https://docs.python.org/3.9/whatsnew/3.4.html#index-28), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-29), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-6) + [PEP 436](https://docs.python.org/3.9/whatsnew/3.4.html#index-18), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-48), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-49) + [PEP 441](https://docs.python.org/3.9/whatsnew/3.5.html#index-29), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-30) + [PEP 442](c-api/typeobj#index-3), [[1]](extending/newtypes#index-2), [[2]](library/gc#index-0), [[3]](https://docs.python.org/3.9/whatsnew/3.4.html#index-15), [[4]](https://docs.python.org/3.9/whatsnew/3.4.html#index-16), [[5]](https://docs.python.org/3.9/whatsnew/3.4.html#index-45), [[6]](https://docs.python.org/3.9/whatsnew/3.4.html#index-46), [[7]](https://docs.python.org/3.9/whatsnew/3.9.html#index-20), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-62) + [PEP 443](glossary#index-21), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-36) + [PEP 445](https://docs.python.org/3.9/whatsnew/3.4.html#index-17), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-43), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-44), [[3]](https://docs.python.org/3.9/whatsnew/3.4.html#index-52) + [PEP 446](https://docs.python.org/3.9/whatsnew/3.4.html#index-14), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-2), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-21), [[3]](https://docs.python.org/3.9/whatsnew/3.4.html#index-22) + [PEP 448](reference/expressions#index-19), [[1]](reference/expressions#index-51), [[2]](reference/expressions#index-93), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-5), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-6), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-134), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-145), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-146), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-147) + [PEP 450](https://docs.python.org/3.9/whatsnew/3.4.html#index-32), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-33), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-9) + [PEP 451](c-api/module#index-7), [[1]](glossary#index-16), [[2]](library/importlib#index-6), [[3]](library/pkgutil#index-6), [[4]](library/pkgutil#index-9), [[5]](library/runpy#index-3), [[6]](library/runpy#index-5), [[7]](library/runpy#index-8), [[8]](library/sys#index-20), [[9]](reference/import#index-27), [[10]](https://docs.python.org/3.9/whatsnew/3.4.html#index-23), [[11]](https://docs.python.org/3.9/whatsnew/3.4.html#index-3), [[12]](https://docs.python.org/3.9/whatsnew/3.5.html#index-27), [[13]](https://docs.python.org/3.9/whatsnew/changelog.html#index-137) + [PEP 453](library/ensurepip#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.7.html#index-22), [[2]](https://docs.python.org/3.9/whatsnew/2.7.html#index-23), [[3]](https://docs.python.org/3.9/whatsnew/2.7.html#index-24), [[4]](https://docs.python.org/3.9/whatsnew/3.4.html#index-1), [[5]](https://docs.python.org/3.9/whatsnew/3.4.html#index-19), [[6]](https://docs.python.org/3.9/whatsnew/3.4.html#index-20), [[7]](https://docs.python.org/3.9/whatsnew/3.4.html#index-27), [[8]](https://docs.python.org/3.9/whatsnew/3.4.html#index-42), [[9]](https://docs.python.org/3.9/whatsnew/3.4.html#index-5), [[10]](https://docs.python.org/3.9/whatsnew/3.4.html#index-53) + [PEP 454](https://docs.python.org/3.9/whatsnew/3.4.html#index-10), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-34), [[2]](https://docs.python.org/3.9/whatsnew/3.4.html#index-35) + [PEP 456](https://docs.python.org/3.9/whatsnew/3.4.html#index-13), [[1]](https://docs.python.org/3.9/whatsnew/3.4.html#index-47) + [PEP 461](library/stdtypes#index-47), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-7), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-8) + [PEP 465](https://docs.python.org/3.9/whatsnew/3.5.html#index-3), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-4), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-48), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-157) + [PEP 466](https://docs.python.org/3.9/whatsnew/2.7.html#index-17), [[1]](https://docs.python.org/3.9/whatsnew/2.7.html#index-18), [[2]](https://docs.python.org/3.9/whatsnew/2.7.html#index-19), [[3]](https://docs.python.org/3.9/whatsnew/2.7.html#index-20) + [PEP 468](library/collections#index-2), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-24), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-112) + [PEP 471](https://docs.python.org/3.9/whatsnew/3.5.html#index-13), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-14), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-153) + [PEP 475](library/exceptions#index-6), [[1]](library/functions#index-8), [[2]](library/os#index-16), [[3]](library/os#index-18), [[4]](library/os#index-19), [[5]](library/os#index-38), [[6]](library/select#index-3), [[7]](library/select#index-4), [[8]](library/select#index-5), [[9]](library/select#index-6), [[10]](library/select#index-7), [[11]](library/selectors#index-0), [[12]](library/signal#index-0), [[13]](library/signal#index-1), [[14]](library/socket#index-10), [[15]](library/socket#index-11), [[16]](library/socket#index-12), [[17]](library/socket#index-13), [[18]](library/socket#index-4), [[19]](library/socket#index-5), [[20]](library/socket#index-7), [[21]](library/socket#index-8), [[22]](library/socket#index-9), [[23]](library/time#index-8), [[24]](https://docs.python.org/3.9/whatsnew/3.5.html#index-15), [[25]](https://docs.python.org/3.9/whatsnew/3.5.html#index-16), [[26]](https://docs.python.org/3.9/whatsnew/3.5.html#index-51), [[27]](https://docs.python.org/3.9/whatsnew/changelog.html#index-152), [[28]](https://docs.python.org/3.9/whatsnew/changelog.html#index-95) + [PEP 476](https://docs.python.org/3.9/whatsnew/2.7.html#index-25) + [PEP 477](https://docs.python.org/3.9/whatsnew/2.7.html#index-21) + [PEP 478](https://docs.python.org/3.9/whatsnew/3.5.html#index-0) + [PEP 479](library/__future__#index-7), [[1]](library/exceptions#index-4), [[2]](library/exceptions#index-5), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-17), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-18), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-37), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-107), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-128), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-142), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-74), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-82), [[11]](https://docs.python.org/3.9/whatsnew/changelog.html#index-85) + [PEP 483](glossary#index-22), [[1]](library/typing#index-1), [[2]](library/typing#index-3), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-12) + [PEP 484](glossary#index-0), [[1]](glossary#index-18), [[2]](glossary#index-23), [[3]](glossary#index-35), [[4]](glossary#index-36), [[5]](glossary#index-39), [[6]](library/ast#index-2), [[7]](library/ast#index-4), [[8]](library/ast#index-5), [[9]](library/stdtypes#index-54), [[10]](library/typing#index-0), [[11]](library/typing#index-11), [[12]](library/typing#index-12), [[13]](library/typing#index-13), [[14]](library/typing#index-18), [[15]](library/typing#index-2), [[16]](library/typing#index-24), [[17]](library/typing#index-63), [[18]](reference/compound_stmts#index-28), [[19]](reference/datamodel#index-91), [[20]](reference/simple_stmts#index-17), [[21]](tutorial/controlflow#index-7), [[22]](https://docs.python.org/3.9/whatsnew/3.5.html#index-10), [[23]](https://docs.python.org/3.9/whatsnew/3.5.html#index-11), [[24]](https://docs.python.org/3.9/whatsnew/3.6.html#index-5), [[25]](https://docs.python.org/3.9/whatsnew/3.7.html#index-20), [[26]](https://docs.python.org/3.9/whatsnew/3.8.html#index-10), [[27]](https://docs.python.org/3.9/whatsnew/3.8.html#index-12) + [PEP 485](library/cmath#index-0), [[1]](library/math#index-0), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-19), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-20), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-149) + [PEP 486](https://docs.python.org/3.9/whatsnew/3.5.html#index-21), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-23), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-154) + [PEP 487](https://docs.python.org/3.9/whatsnew/3.6.html#index-13), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-14), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-15), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-37), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-104), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-114), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-123) + [PEP 488](distutils/apiref#index-4), [[1]](distutils/apiref#index-5), [[2]](library/importlib#index-22), [[3]](library/importlib#index-25), [[4]](library/importlib#index-7), [[5]](library/py_compile#index-2), [[6]](library/test#index-1), [[7]](using/cmdline#index-11), [[8]](using/cmdline#index-13), [[9]](using/cmdline#index-14), [[10]](using/cmdline#index-15), [[11]](https://docs.python.org/3.9/whatsnew/3.5.html#index-24), [[12]](https://docs.python.org/3.9/whatsnew/3.5.html#index-25), [[13]](https://docs.python.org/3.9/whatsnew/3.5.html#index-52), [[14]](https://docs.python.org/3.9/whatsnew/changelog.html#index-151) + [PEP 489](c-api/module#index-8), [[1]](extending/building#index-1), [[2]](extending/extending#index-0), [[3]](library/importlib#index-18), [[4]](library/importlib#index-19), [[5]](library/importlib#index-20), [[6]](library/importlib#index-8), [[7]](https://docs.python.org/3.9/whatsnew/3.5.html#index-26), [[8]](https://docs.python.org/3.9/whatsnew/3.5.html#index-28), [[9]](https://docs.python.org/3.9/whatsnew/3.5.html#index-47), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-11), [[11]](https://docs.python.org/3.9/whatsnew/changelog.html#index-13), [[12]](https://docs.python.org/3.9/whatsnew/changelog.html#index-14), [[13]](https://docs.python.org/3.9/whatsnew/changelog.html#index-15), [[14]](https://docs.python.org/3.9/whatsnew/changelog.html#index-19), [[15]](https://docs.python.org/3.9/whatsnew/changelog.html#index-20), [[16]](https://docs.python.org/3.9/whatsnew/changelog.html#index-21), [[17]](https://docs.python.org/3.9/whatsnew/changelog.html#index-22), [[18]](https://docs.python.org/3.9/whatsnew/changelog.html#index-23), [[19]](https://docs.python.org/3.9/whatsnew/changelog.html#index-31), [[20]](https://docs.python.org/3.9/whatsnew/changelog.html#index-32), [[21]](https://docs.python.org/3.9/whatsnew/changelog.html#index-33), [[22]](https://docs.python.org/3.9/whatsnew/changelog.html#index-36), [[23]](https://docs.python.org/3.9/whatsnew/changelog.html#index-38), [[24]](https://docs.python.org/3.9/whatsnew/changelog.html#index-40), [[25]](https://docs.python.org/3.9/whatsnew/changelog.html#index-47), [[26]](https://docs.python.org/3.9/whatsnew/changelog.html#index-48), [[27]](https://docs.python.org/3.9/whatsnew/changelog.html#index-49), [[28]](https://docs.python.org/3.9/whatsnew/changelog.html#index-50), [[29]](https://docs.python.org/3.9/whatsnew/changelog.html#index-51), [[30]](https://docs.python.org/3.9/whatsnew/changelog.html#index-56) + [PEP 492](glossary#index-11), [[1]](glossary#index-12), [[2]](glossary#index-3), [[3]](glossary#index-4), [[4]](glossary#index-6), [[5]](glossary#index-7), [[6]](glossary#index-8), [[7]](library/collections.abc#index-3), [[8]](library/inspect#index-1), [[9]](library/inspect#index-2), [[10]](reference/compound_stmts#index-41), [[11]](reference/datamodel#index-105), [[12]](reference/expressions#index-30), [[13]](https://docs.python.org/3.9/whatsnew/3.5.html#index-1), [[14]](https://docs.python.org/3.9/whatsnew/3.5.html#index-2), [[15]](https://docs.python.org/3.9/whatsnew/3.5.html#index-49), [[16]](https://docs.python.org/3.9/whatsnew/3.5.html#index-54), [[17]](https://docs.python.org/3.9/whatsnew/3.6.html#index-35), [[18]](https://docs.python.org/3.9/whatsnew/3.6.html#index-9), [[19]](https://docs.python.org/3.9/whatsnew/changelog.html#index-133), [[20]](https://docs.python.org/3.9/whatsnew/changelog.html#index-144), [[21]](https://docs.python.org/3.9/whatsnew/changelog.html#index-148), [[22]](https://docs.python.org/3.9/whatsnew/changelog.html#index-99) + [PEP 493](https://docs.python.org/3.9/whatsnew/2.7.html#index-26) + [PEP 494](https://docs.python.org/3.9/whatsnew/3.6.html#index-0) + [PEP 495](library/zoneinfo#index-1), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-17), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-18), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-126) + [PEP 498](glossary#index-13), [[1]](reference/lexical_analysis#index-25), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-3), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-4), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-140) + [PEP 5](faq/general#index-2), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-6) + [PEP 506](library/secrets#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-28), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-141) + [PEP 511](https://docs.python.org/3.9/whatsnew/3.6.html#index-36) + [PEP 514](https://docs.python.org/3.9/whatsnew/changelog.html#index-127) + [PEP 515](library/string#index-9), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-7), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-8), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-115), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-116) + [PEP 519](glossary#index-29), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-16), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-124), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-129), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-130), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-131), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-132), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-135) + [PEP 520](https://docs.python.org/3.9/whatsnew/3.6.html#index-23) + [PEP 523](c-api/init#index-40), [[1]](c-api/init#index-41), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-25), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-26), [[4]](https://docs.python.org/3.9/whatsnew/3.9.html#index-24), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-106), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-111), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-119) + [PEP 524](library/os#index-47), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-1), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-31), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-32), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-121), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-122) + [PEP 525](glossary#index-5), [[1]](library/collections.abc#index-2), [[2]](library/inspect#index-3), [[3]](library/sys#index-12), [[4]](library/sys#index-29), [[5]](reference/expressions#index-29), [[6]](https://docs.python.org/3.9/whatsnew/3.6.html#index-10), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-117) + [PEP 526](glossary#index-1), [[1]](glossary#index-40), [[2]](library/ast#index-3), [[3]](library/ast#index-6), [[4]](library/dataclasses#index-1), [[5]](library/dataclasses#index-2), [[6]](library/typing#index-21), [[7]](library/typing#index-26), [[8]](library/typing#index-27), [[9]](library/typing#index-4), [[10]](reference/compound_stmts#index-29), [[11]](reference/simple_stmts#index-16), [[12]](https://docs.python.org/3.9/whatsnew/3.6.html#index-33), [[13]](https://docs.python.org/3.9/whatsnew/3.6.html#index-6), [[14]](https://docs.python.org/3.9/whatsnew/3.7.html#index-1), [[15]](https://docs.python.org/3.9/whatsnew/3.8.html#index-11), [[16]](https://docs.python.org/3.9/whatsnew/changelog.html#index-118) + [PEP 528](c-api/init#index-11), [[1]](using/windows#index-12), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-22) + [PEP 529](c-api/init#index-9), [[1]](c-api/unicode#index-6), [[2]](library/os#index-21), [[3]](library/sys#index-33), [[4]](library/sys#index-9), [[5]](using/cmdline#index-41), [[6]](using/windows#index-13), [[7]](https://docs.python.org/3.9/whatsnew/3.6.html#index-20), [[8]](https://docs.python.org/3.9/whatsnew/3.8.html#index-19), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-1), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-113), [[11]](https://docs.python.org/3.9/whatsnew/changelog.html#index-60) + [PEP 530](reference/expressions#index-14), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-12), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-120) + [PEP 538](c-api/init_config#index-6), [[1]](using/cmdline#index-44), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-10), [[3]](https://docs.python.org/3.9/whatsnew/3.7.html#index-3), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-6), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-7), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-101), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-76), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-80) + [PEP 539](c-api/init#index-47), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-14), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-15), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-100) + [PEP 540](c-api/init_config#index-7), [[1]](using/cmdline#index-47), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-11), [[3]](https://docs.python.org/3.9/whatsnew/3.7.html#index-9), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-90) + [PEP 544](library/typing#index-14), [[1]](library/typing#index-25), [[2]](library/typing#index-5), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-18) + [PEP 545](https://docs.python.org/3.9/whatsnew/3.7.html#index-24), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-25) + [PEP 552](c-api/init_config#index-1), [[1]](library/importlib#index-9), [[2]](library/py_compile#index-5), [[3]](https://docs.python.org/3.9/whatsnew/3.7.html#index-22), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-23), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-73), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-93) + [PEP 553](https://docs.python.org/3.9/whatsnew/3.7.html#index-13), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-98) + [PEP 557](library/dataclasses#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-29) + [PEP 560](library/types#index-1), [[1]](library/types#index-2), [[2]](reference/datamodel#index-83), [[3]](reference/datamodel#index-92), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-21), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-33), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-91) + [PEP 562](reference/datamodel#index-80), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-16), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-87), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-92) + [PEP 563](library/__future__#index-8), [[1]](library/__future__#index-9), [[2]](library/typing#index-67), [[3]](reference/compound_stmts#index-30), [[4]](reference/simple_stmts#index-41), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-2) + [PEP 564](https://docs.python.org/3.9/whatsnew/3.7.html#index-17), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-18), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-32), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-96) + [PEP 565](library/exceptions#index-8), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-19) + [PEP 566](library/importlib.metadata#index-0), [[1]](library/importlib.metadata#index-1) + [PEP 567](library/asyncio-eventloop#index-0), [[1]](library/asyncio-eventloop#index-1), [[2]](library/asyncio-eventloop#index-2), [[3]](library/asyncio-future#index-0), [[4]](library/contextvars#index-0), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-28), [[6]](https://docs.python.org/3.9/whatsnew/3.7.html#index-30), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-77), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-81), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-86) + [PEP 570](reference/compound_stmts#index-24), [[1]](https://docs.python.org/3.9/whatsnew/3.8.html#index-1), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-23), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-67) + [PEP 572](faq/design#index-0), [[1]](reference/expressions#index-21), [[2]](reference/expressions#index-86), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-0), [[4]](https://docs.python.org/3.9/whatsnew/3.8.html#index-24), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-46), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-59), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-69) + [PEP 573](https://docs.python.org/3.9/whatsnew/3.9.html#index-23), [[1]](https://docs.python.org/3.9/whatsnew/3.9.html#index-6), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-12), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-17) + [PEP 574](library/pickle#index-4), [[1]](library/pickle#index-8), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-9) + [PEP 578](c-api/sys#index-0), [[1]](library/audit_events#index-1), [[2]](library/sys#index-1), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-4) + [PEP 584](library/collections#index-0), [[1]](library/collections#index-1), [[2]](library/collections#index-3), [[3]](library/os#index-0), [[4]](library/os#index-1), [[5]](library/types#index-4), [[6]](library/weakref#index-0), [[7]](library/weakref#index-1), [[8]](https://docs.python.org/3.9/whatsnew/3.9.html#index-1), [[9]](https://docs.python.org/3.9/whatsnew/3.9.html#index-11), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-27), [[11]](https://docs.python.org/3.9/whatsnew/changelog.html#index-28), [[12]](https://docs.python.org/3.9/whatsnew/changelog.html#index-29), [[13]](https://docs.python.org/3.9/whatsnew/changelog.html#index-41), [[14]](https://docs.python.org/3.9/whatsnew/changelog.html#index-42), [[15]](https://docs.python.org/3.9/whatsnew/changelog.html#index-43), [[16]](https://docs.python.org/3.9/whatsnew/changelog.html#index-44) + [PEP 585](glossary#index-24), [[1]](library/collections.abc#index-0), [[2]](library/stdtypes#index-55), [[3]](library/typing#index-15), [[4]](library/typing#index-16), [[5]](library/typing#index-17), [[6]](library/typing#index-19), [[7]](library/typing#index-29), [[8]](library/typing#index-30), [[9]](library/typing#index-31), [[10]](library/typing#index-32), [[11]](library/typing#index-33), [[12]](library/typing#index-34), [[13]](library/typing#index-35), [[14]](library/typing#index-36), [[15]](library/typing#index-37), [[16]](library/typing#index-38), [[17]](library/typing#index-39), [[18]](library/typing#index-40), [[19]](library/typing#index-41), [[20]](library/typing#index-42), [[21]](library/typing#index-43), [[22]](library/typing#index-44), [[23]](library/typing#index-45), [[24]](library/typing#index-46), [[25]](library/typing#index-47), [[26]](library/typing#index-48), [[27]](library/typing#index-49), [[28]](library/typing#index-50), [[29]](library/typing#index-51), [[30]](library/typing#index-52), [[31]](library/typing#index-53), [[32]](library/typing#index-54), [[33]](library/typing#index-55), [[34]](library/typing#index-56), [[35]](library/typing#index-57), [[36]](library/typing#index-58), [[37]](library/typing#index-59), [[38]](library/typing#index-6), [[39]](library/typing#index-60), [[40]](library/typing#index-61), [[41]](library/typing#index-62), [[42]](library/typing#index-66), [[43]](https://docs.python.org/3.9/whatsnew/3.9.html#index-13), [[44]](https://docs.python.org/3.9/whatsnew/3.9.html#index-2), [[45]](https://docs.python.org/3.9/whatsnew/changelog.html#index-5) + [PEP 586](library/typing#index-20), [[1]](library/typing#index-7), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-16), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-27) + [PEP 587](c-api/init_config#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.8.html#index-5), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-6), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-58), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-63) + [PEP 589](library/typing#index-28), [[1]](library/typing#index-8), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-15) + [PEP 590](c-api/call#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.8.html#index-7), [[2]](https://docs.python.org/3.9/whatsnew/3.9.html#index-18), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-8), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-18), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-25), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-34), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-35), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-37), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-64) + [PEP 591](library/typing#index-22), [[1]](library/typing#index-64), [[2]](library/typing#index-9), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-17) + [PEP 593](library/typing#index-10), [[1]](library/typing#index-23), [[2]](library/typing#index-65), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-17), [[4]](https://docs.python.org/3.9/whatsnew/3.9.html#index-5), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-52) + [PEP 594](library/nntplib#index-1), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-2), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-3) + [PEP 594#aifc](library/aifc#index-1) + [PEP 594#asynchat](library/asynchat#index-0) + [PEP 594#asyncore](library/asyncore#index-0) + [PEP 594#audioop](library/audioop#index-0) + [PEP 594#cgi](library/cgi#index-1) + [PEP 594#cgitb](library/cgitb#index-1) + [PEP 594#chunk](library/chunk#index-1) + [PEP 594#crypt](library/crypt#index-1) + [PEP 594#imghdr](library/imghdr#index-0) + [PEP 594#mailcap](library/mailcap#index-0) + [PEP 594#msilib](library/msilib#index-1) + [PEP 594#nis](library/nis#index-0) + [PEP 594#ossaudiodev](library/ossaudiodev#index-0) + [PEP 594#pipes](library/pipes#index-0) + [PEP 594#smtpd](library/smtpd#index-0) + [PEP 594#sndhdr](library/sndhdr#index-1) + [PEP 594#spwd](library/spwd#index-0) + [PEP 594#sunau](https://docs.python.org/3.9/library/sunau.html#index-0) + [PEP 594#telnetlib](library/telnetlib#index-1) + [PEP 594#uu-and-the-uu-encoding](library/uu#index-0) + [PEP 594#xdrlib](library/xdrlib#index-1) + [PEP 596](https://docs.python.org/3.9/whatsnew/3.9.html#index-0) + [PEP 6](faq/general#index-0) + [PEP 602](faq/general#index-1), [[1]](https://docs.python.org/3.9/whatsnew/3.9.html#index-10) + [PEP 612](https://docs.python.org/3.9/whatsnew/changelog.html#index-8) + [PEP 614](reference/compound_stmts#index-21), [[1]](reference/compound_stmts#index-33), [[2]](https://docs.python.org/3.9/whatsnew/3.9.html#index-15), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-3), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-39) + [PEP 615](library/zoneinfo#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.9.html#index-16), [[2]](https://docs.python.org/3.9/whatsnew/3.9.html#index-9), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-16) + [PEP 616](https://docs.python.org/3.9/whatsnew/3.9.html#index-12), [[1]](https://docs.python.org/3.9/whatsnew/3.9.html#index-4), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-24) + [PEP 617](c-api/init_config#index-5), [[1]](https://docs.python.org/3.9/library/2to3.html#index-0), [[2]](using/cmdline#index-23), [[3]](using/cmdline#index-35), [[4]](https://docs.python.org/3.9/whatsnew/3.9.html#index-14), [[5]](https://docs.python.org/3.9/whatsnew/3.9.html#index-19), [[6]](https://docs.python.org/3.9/whatsnew/3.9.html#index-7), [[7]](https://docs.python.org/3.9/whatsnew/changelog.html#index-26) + [PEP 623](c-api/unicode#index-1), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-7) + [PEP 628](https://docs.python.org/3.9/whatsnew/3.6.html#index-29), [[1]](https://docs.python.org/3.9/whatsnew/3.6.html#index-30), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-125) + [PEP 649](library/__future__#index-10) + [PEP 7](c-api/intro#index-0), [[1]](c-api/intro#index-6), [[2]](c-api/intro#index-7), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-34) + [PEP 8](faq/programming#index-0), [[1]](faq/programming#index-2), [[2]](faq/windows#index-0), [[3]](howto/clinic#index-0), [[4]](library/functions#index-9), [[5]](reference/expressions#index-79), [[6]](tutorial/controlflow#index-9), [[7]](using/editors#index-0), [[8]](https://docs.python.org/3.9/whatsnew/3.0.html#index-21), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-156), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-94) * [Python Package Index (PyPI)](distributing/index#index-1) * [PYTHON\*](c-api/init#index-4), [[1]](using/cmdline#index-0), [[2]](using/cmdline#index-10), [[3]](using/cmdline#index-2), [[4]](using/cmdline#index-5), [[5]](https://docs.python.org/3.9/whatsnew/3.4.html#index-50) * [python\_branch() (in module platform)](library/platform#platform.python_branch) * [python\_build() (in module platform)](library/platform#platform.python_build) * [python\_compiler() (in module platform)](library/platform#platform.python_compiler) * [PYTHON\_DOM](library/xml.dom#index-0) * [python\_implementation() (in module platform)](library/platform#platform.python_implementation) * [python\_is\_optimized() (in module test.support)](library/test#test.support.python_is_optimized) * [python\_revision() (in module platform)](library/platform#platform.python_revision) * [python\_version() (in module platform)](library/platform#platform.python_version) * [python\_version\_tuple() (in module platform)](library/platform#platform.python_version_tuple) * [PYTHONASYNCIODEBUG](library/asyncio-dev#index-0), [[1]](library/asyncio-eventloop#index-5), [[2]](library/devmode#index-5) * [PYTHONBREAKPOINT](library/sys#index-3), [[1]](library/sys#index-4), [[2]](library/sys#index-5), [[3]](https://docs.python.org/3.9/whatsnew/3.7.html#index-12) * [PYTHONCASEOK](library/functions#index-15), [[1]](https://docs.python.org/3.9/whatsnew/2.1.html#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.9.html#index-21), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-45) * [PYTHONCOERCECLOCALE](c-api/init_config#index-9), [[1]](using/cmdline#index-46), [[2]](https://docs.python.org/3.9/whatsnew/3.7.html#index-4) * [PYTHONDEBUG](c-api/init#index-0), [[1]](using/cmdline#index-4) * [PYTHONDEVMODE](library/devmode#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-26) * [PYTHONDOCS](library/pydoc#index-2) * [PYTHONDONTWRITEBYTECODE](c-api/init#index-1), [[1]](faq/programming#index-4), [[2]](library/sys#index-6), [[3]](using/cmdline#index-3), [[4]](https://docs.python.org/3.9/whatsnew/2.6.html#index-20), [[5]](https://docs.python.org/3.9/whatsnew/2.6.html#index-24) * [PYTHONDUMPREFS](c-api/typeobj#index-0), [[1]](https://docs.python.org/3.9/whatsnew/3.8.html#index-3), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-68) * [PYTHONFAULTHANDLER](library/devmode#index-4), [[1]](library/faulthandler#index-0), [[2]](https://docs.python.org/3.9/whatsnew/3.3.html#index-24) * [PYTHONHASHSEED](c-api/init#index-2), [[1]](c-api/init#index-3), [[2]](reference/datamodel#index-77), [[3]](using/cmdline#index-16), [[4]](using/cmdline#index-17), [[5]](using/cmdline#index-36), [[6]](https://docs.python.org/3.9/whatsnew/3.3.html#index-23), [[7]](https://docs.python.org/3.9/whatsnew/3.3.html#index-35), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-89) * [PYTHONHOME](c-api/init#index-31), [[1]](c-api/init#index-32), [[2]](c-api/init#index-6), [[3]](c-api/init_config#index-2), [[4]](c-api/intro#index-27), [[5]](c-api/intro#index-30), [[6]](install/index#index-0), [[7]](install/index#index-1), [[8]](library/test#index-2), [[9]](using/cmdline#index-28), [[10]](using/cmdline#index-29), [[11]](using/cmdline#index-32), [[12]](using/cmdline#index-7), [[13]](using/windows#index-22), [[14]](using/windows#index-24), [[15]](using/windows#index-26), [[16]](https://docs.python.org/3.9/whatsnew/3.6.html#index-2) * [**Pythonic**](glossary#term-pythonic) * [PYTHONINSPECT](c-api/init#index-7), [[1]](using/cmdline#index-9), [[2]](https://docs.python.org/3.9/whatsnew/2.3.html#index-29) * [PYTHONINTMAXSTRDIGITS](library/stdtypes#index-63), [[1]](library/stdtypes#index-64), [[2]](library/sys#index-17), [[3]](using/cmdline#index-24) * [PYTHONIOENCODING](c-api/init#index-18), [[1]](c-api/init#index-19), [[2]](library/sys#index-34), [[3]](using/cmdline#index-42), [[4]](using/cmdline#index-45), [[5]](https://docs.python.org/3.9/whatsnew/2.6.html#index-21), [[6]](https://docs.python.org/3.9/whatsnew/3.4.html#index-54) * [PYTHONLEGACYWINDOWSFSENCODING](c-api/init#index-8), [[1]](library/sys#index-32), [[2]](https://docs.python.org/3.9/whatsnew/3.6.html#index-19) * [PYTHONLEGACYWINDOWSSTDIO](c-api/init#index-10), [[1]](library/sys#index-36), [[2]](using/cmdline#index-37), [[3]](https://docs.python.org/3.9/whatsnew/3.6.html#index-21) * [PYTHONMALLOC](c-api/memory#index-1), [[1]](c-api/memory#index-3), [[2]](c-api/memory#index-4), [[3]](library/devmode#index-2), [[4]](library/devmode#index-3), [[5]](using/cmdline#index-40), [[6]](https://docs.python.org/3.9/whatsnew/3.6.html#index-27), [[7]](https://docs.python.org/3.9/whatsnew/3.6.html#index-38), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-138) * [PYTHONMALLOCSTATS](c-api/memory#index-2), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-139) * [PYTHONNOUSERSITE](c-api/init#index-12), [[1]](library/site#index-8), [[2]](https://docs.python.org/3.9/whatsnew/2.6.html#index-6) * [PYTHONOLDPARSER](c-api/init_config#index-4), [[1]](using/cmdline#index-22) * [PYTHONOPTIMIZE](c-api/init#index-13), [[1]](using/cmdline#index-12) * [PYTHONPATH](c-api/init#index-5), [[1]](c-api/init_config#index-3), [[2]](c-api/intro#index-28), [[3]](c-api/intro#index-31), [[4]](extending/building#index-0), [[5]](install/index#index-2), [[6]](install/index#index-3), [[7]](library/cgi#index-4), [[8]](library/sys#index-22), [[9]](library/sys#index-23), [[10]](library/test#index-3), [[11]](reference/import#index-17), [[12]](tutorial/modules#index-1), [[13]](tutorial/modules#index-5), [[14]](tutorial/modules#index-6), [[15]](using/cmdline#index-31), [[16]](using/cmdline#index-33), [[17]](using/cmdline#index-34), [[18]](using/cmdline#index-6), [[19]](using/mac#index-0), [[20]](using/windows#index-21), [[21]](using/windows#index-23), [[22]](using/windows#index-25), [[23]](using/windows#index-7), [[24]](https://docs.python.org/3.9/whatsnew/3.4.html#index-56), [[25]](https://docs.python.org/3.9/whatsnew/3.4.html#index-57) * [PYTHONPLATLIBDIR](https://docs.python.org/3.9/whatsnew/changelog.html#index-10) * [PYTHONPROFILEIMPORTTIME](using/cmdline#index-25), [[1]](https://docs.python.org/3.9/whatsnew/3.7.html#index-27), [[2]](https://docs.python.org/3.9/whatsnew/changelog.html#index-97) * [PYTHONPYCACHEPREFIX](library/sys#index-7), [[1]](using/cmdline#index-27), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-2), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-70) * [PYTHONSHOWALLOCCOUNT](https://docs.python.org/3.9/whatsnew/2.7.html#index-15) * [PYTHONSHOWREFCOUNT](https://docs.python.org/3.9/whatsnew/2.7.html#index-14) * [PYTHONSTARTUP](library/idle#index-6), [[1]](library/readline#index-0), [[2]](library/site#index-7), [[3]](library/sys#index-18), [[4]](tutorial/appendix#index-1), [[5]](using/cmdline#index-8), [[6]](https://docs.python.org/3.9/whatsnew/3.4.html#index-40), [[7]](https://docs.python.org/3.9/whatsnew/3.4.html#index-41), [[8]](https://docs.python.org/3.9/whatsnew/changelog.html#index-109), [[9]](https://docs.python.org/3.9/whatsnew/changelog.html#index-79), [[10]](https://docs.python.org/3.9/whatsnew/changelog.html#index-84) * [PYTHONTRACEMALLOC](library/tracemalloc#index-0), [[1]](library/tracemalloc#index-1), [[2]](library/tracemalloc#index-2) * [PYTHONTZPATH](library/zoneinfo#index-2) * [PYTHONUNBUFFERED](c-api/init#index-14), [[1]](library/sys#index-37), [[2]](using/cmdline#index-19), [[3]](https://docs.python.org/3.9/whatsnew/changelog.html#index-57) * [PYTHONUSERBASE](library/site#index-10), [[1]](library/site#index-9), [[2]](https://docs.python.org/3.9/whatsnew/2.6.html#index-4) * [PYTHONUSERSITE](library/test#index-4) * [PYTHONUTF8](c-api/init_config#index-8), [[1]](library/sys#index-35), [[2]](using/cmdline#index-26), [[3]](using/cmdline#index-43), [[4]](using/windows#index-11), [[5]](https://docs.python.org/3.9/whatsnew/3.7.html#index-8) * [PYTHONVERBOSE](c-api/init#index-15), [[1]](using/cmdline#index-20) * [PYTHONWARNINGS](library/devmode#index-1), [[1]](library/warnings#index-1), [[2]](library/warnings#index-2), [[3]](library/warnings#index-3), [[4]](using/cmdline#index-21), [[5]](https://docs.python.org/3.9/whatsnew/2.7.html#index-1), [[6]](https://docs.python.org/3.9/whatsnew/2.7.html#index-8), [[7]](https://docs.python.org/3.9/whatsnew/3.2.html#index-10), [[8]](https://docs.python.org/3.9/whatsnew/3.7.html#index-36) * [PyThread\_create\_key (C function)](c-api/init#c.PyThread_create_key) * [PyThread\_delete\_key (C function)](c-api/init#c.PyThread_delete_key) * [PyThread\_delete\_key\_value (C function)](c-api/init#c.PyThread_delete_key_value) * [PyThread\_get\_key\_value (C function)](c-api/init#c.PyThread_get_key_value) * [PyThread\_ReInitTLS (C function)](c-api/init#c.PyThread_ReInitTLS) * [PyThread\_set\_key\_value (C function)](c-api/init#c.PyThread_set_key_value) * [PyThread\_tss\_alloc (C function)](c-api/init#c.PyThread_tss_alloc) * [PyThread\_tss\_create (C function)](c-api/init#c.PyThread_tss_create) * [PyThread\_tss\_delete (C function)](c-api/init#c.PyThread_tss_delete) * [PyThread\_tss\_free (C function)](c-api/init#c.PyThread_tss_free) * [PyThread\_tss\_get (C function)](c-api/init#c.PyThread_tss_get) * [PyThread\_tss\_is\_created (C function)](c-api/init#c.PyThread_tss_is_created) * [PyThread\_tss\_set (C function)](c-api/init#c.PyThread_tss_set) * [PyThreadState](c-api/init#index-35), [[1]](c-api/init#index-35) + [(C type)](c-api/init#c.PyThreadState) * [PyThreadState\_Clear (C function)](c-api/init#c.PyThreadState_Clear) * [PyThreadState\_Delete (C function)](c-api/init#c.PyThreadState_Delete) * [PyThreadState\_DeleteCurrent (C function)](c-api/init#c.PyThreadState_DeleteCurrent) * [PyThreadState\_Get (C function)](c-api/init#c.PyThreadState_Get) * [PyThreadState\_GetDict (C function)](c-api/init#c.PyThreadState_GetDict) * [PyThreadState\_GetFrame (C function)](c-api/init#c.PyThreadState_GetFrame) * [PyThreadState\_GetID (C function)](c-api/init#c.PyThreadState_GetID) * [PyThreadState\_GetInterpreter (C function)](c-api/init#c.PyThreadState_GetInterpreter) * [PyThreadState\_New (C function)](c-api/init#c.PyThreadState_New) * [PyThreadState\_Next (C function)](c-api/init#c.PyThreadState_Next) * [PyThreadState\_SetAsyncExc (C function)](c-api/init#c.PyThreadState_SetAsyncExc) * [PyThreadState\_Swap (C function)](c-api/init#c.PyThreadState_Swap) * [PyTime\_Check (C function)](c-api/datetime#c.PyTime_Check) * [PyTime\_CheckExact (C function)](c-api/datetime#c.PyTime_CheckExact) * [PyTime\_FromTime (C function)](c-api/datetime#c.PyTime_FromTime) * [PyTime\_FromTimeAndFold (C function)](c-api/datetime#c.PyTime_FromTimeAndFold) * [PyTimeZone\_FromOffset (C function)](c-api/datetime#c.PyTimeZone_FromOffset) * [PyTimeZone\_FromOffsetAndName (C function)](c-api/datetime#c.PyTimeZone_FromOffsetAndName) * [PyTrace\_C\_CALL (C variable)](c-api/init#c.PyTrace_C_CALL) * [PyTrace\_C\_EXCEPTION (C variable)](c-api/init#c.PyTrace_C_EXCEPTION) * [PyTrace\_C\_RETURN (C variable)](c-api/init#c.PyTrace_C_RETURN) * [PyTrace\_CALL (C variable)](c-api/init#c.PyTrace_CALL) * [PyTrace\_EXCEPTION (C variable)](c-api/init#c.PyTrace_EXCEPTION) * [PyTrace\_LINE (C variable)](c-api/init#c.PyTrace_LINE) * [PyTrace\_OPCODE (C variable)](c-api/init#c.PyTrace_OPCODE) * [PyTrace\_RETURN (C variable)](c-api/init#c.PyTrace_RETURN) * [PyTraceMalloc\_Track (C function)](c-api/memory#c.PyTraceMalloc_Track) * [PyTraceMalloc\_Untrack (C function)](c-api/memory#c.PyTraceMalloc_Untrack) * [PyTuple\_Check (C function)](c-api/tuple#c.PyTuple_Check) * [PyTuple\_CheckExact (C function)](c-api/tuple#c.PyTuple_CheckExact) * [PyTuple\_GET\_ITEM (C function)](c-api/tuple#c.PyTuple_GET_ITEM) * [PyTuple\_GET\_SIZE (C function)](c-api/tuple#c.PyTuple_GET_SIZE) * [PyTuple\_GetItem (C function)](c-api/tuple#c.PyTuple_GetItem) * [PyTuple\_GetSlice (C function)](c-api/tuple#c.PyTuple_GetSlice) * [PyTuple\_New (C function)](c-api/tuple#c.PyTuple_New) * [PyTuple\_Pack (C function)](c-api/tuple#c.PyTuple_Pack) * [PyTuple\_SET\_ITEM (C function)](c-api/tuple#c.PyTuple_SET_ITEM) * [PyTuple\_SetItem (C function)](c-api/tuple#c.PyTuple_SetItem) * [PyTuple\_SetItem()](c-api/intro#index-10) * [PyTuple\_Size (C function)](c-api/tuple#c.PyTuple_Size) * [PyTuple\_Type (C variable)](c-api/tuple#c.PyTuple_Type) * [PyTupleObject (C type)](c-api/tuple#c.PyTupleObject) * [PyType\_Check (C function)](c-api/type#c.PyType_Check) * [PyType\_CheckExact (C function)](c-api/type#c.PyType_CheckExact) * [PyType\_ClearCache (C function)](c-api/type#c.PyType_ClearCache) * [PyType\_FromModuleAndSpec (C function)](c-api/type#c.PyType_FromModuleAndSpec) * [PyType\_FromSpec (C function)](c-api/type#c.PyType_FromSpec) * [PyType\_FromSpecWithBases (C function)](c-api/type#c.PyType_FromSpecWithBases) * [PyType\_GenericAlloc (C function)](c-api/type#c.PyType_GenericAlloc) * [PyType\_GenericNew (C function)](c-api/type#c.PyType_GenericNew) * [PyType\_GetFlags (C function)](c-api/type#c.PyType_GetFlags) * [PyType\_GetModule (C function)](c-api/type#c.PyType_GetModule) * [PyType\_GetModuleState (C function)](c-api/type#c.PyType_GetModuleState) * [PyType\_GetSlot (C function)](c-api/type#c.PyType_GetSlot) * [PyType\_HasFeature (C function)](c-api/type#c.PyType_HasFeature) * [PyType\_IS\_GC (C function)](c-api/type#c.PyType_IS_GC) * [PyType\_IsSubtype (C function)](c-api/type#c.PyType_IsSubtype) * [PyType\_Modified (C function)](c-api/type#c.PyType_Modified) * [PyType\_Ready (C function)](c-api/type#c.PyType_Ready) * [PyType\_Slot (C type)](c-api/type#c.PyType_Slot) * [PyType\_Slot.PyType\_Slot.pfunc (C member)](c-api/type#c.PyType_Slot.PyType_Slot.pfunc) * [PyType\_Slot.PyType\_Slot.slot (C member)](c-api/type#c.PyType_Slot.PyType_Slot.slot) * [PyType\_Spec (C type)](c-api/type#c.PyType_Spec) * [PyType\_Spec.PyType\_Spec.basicsize (C member)](c-api/type#c.PyType_Spec.PyType_Spec.basicsize) * [PyType\_Spec.PyType\_Spec.flags (C member)](c-api/type#c.PyType_Spec.PyType_Spec.flags) * [PyType\_Spec.PyType\_Spec.itemsize (C member)](c-api/type#c.PyType_Spec.PyType_Spec.itemsize) * [PyType\_Spec.PyType\_Spec.name (C member)](c-api/type#c.PyType_Spec.PyType_Spec.name) * [PyType\_Spec.PyType\_Spec.slots (C member)](c-api/type#c.PyType_Spec.PyType_Spec.slots) * [PyType\_Type (C variable)](c-api/type#c.PyType_Type) * [PyTypeObject (C type)](c-api/type#c.PyTypeObject) * [PyTypeObject.tp\_alloc (C member)](c-api/typeobj#c.PyTypeObject.tp_alloc) * [PyTypeObject.tp\_as\_async (C member)](c-api/typeobj#c.PyTypeObject.tp_as_async) * [PyTypeObject.tp\_as\_buffer (C member)](c-api/typeobj#c.PyTypeObject.tp_as_buffer) * [PyTypeObject.tp\_as\_mapping (C member)](c-api/typeobj#c.PyTypeObject.tp_as_mapping) * [PyTypeObject.tp\_as\_number (C member)](c-api/typeobj#c.PyTypeObject.tp_as_number) * [PyTypeObject.tp\_as\_sequence (C member)](c-api/typeobj#c.PyTypeObject.tp_as_sequence) * [PyTypeObject.tp\_base (C member)](c-api/typeobj#c.PyTypeObject.tp_base) * [PyTypeObject.tp\_bases (C member)](c-api/typeobj#c.PyTypeObject.tp_bases) * [PyTypeObject.tp\_basicsize (C member)](c-api/typeobj#c.PyTypeObject.tp_basicsize) * [PyTypeObject.tp\_cache (C member)](c-api/typeobj#c.PyTypeObject.tp_cache) * [PyTypeObject.tp\_call (C member)](c-api/typeobj#c.PyTypeObject.tp_call) * [PyTypeObject.tp\_clear (C member)](c-api/typeobj#c.PyTypeObject.tp_clear) * [PyTypeObject.tp\_dealloc (C member)](c-api/typeobj#c.PyTypeObject.tp_dealloc) * [PyTypeObject.tp\_del (C member)](c-api/typeobj#c.PyTypeObject.tp_del) * [PyTypeObject.tp\_descr\_get (C member)](c-api/typeobj#c.PyTypeObject.tp_descr_get) * [PyTypeObject.tp\_descr\_set (C member)](c-api/typeobj#c.PyTypeObject.tp_descr_set) * [PyTypeObject.tp\_dict (C member)](c-api/typeobj#c.PyTypeObject.tp_dict) * [PyTypeObject.tp\_dictoffset (C member)](c-api/typeobj#c.PyTypeObject.tp_dictoffset) * [PyTypeObject.tp\_doc (C member)](c-api/typeobj#c.PyTypeObject.tp_doc) * [PyTypeObject.tp\_finalize (C member)](c-api/typeobj#c.PyTypeObject.tp_finalize) * [PyTypeObject.tp\_flags (C member)](c-api/typeobj#c.PyTypeObject.tp_flags) * [PyTypeObject.tp\_free (C member)](c-api/typeobj#c.PyTypeObject.tp_free) * [PyTypeObject.tp\_getattr (C member)](c-api/typeobj#c.PyTypeObject.tp_getattr) * [PyTypeObject.tp\_getattro (C member)](c-api/typeobj#c.PyTypeObject.tp_getattro) * [PyTypeObject.tp\_getset (C member)](c-api/typeobj#c.PyTypeObject.tp_getset) * [PyTypeObject.tp\_hash (C member)](c-api/typeobj#c.PyTypeObject.tp_hash) * [PyTypeObject.tp\_init (C member)](c-api/typeobj#c.PyTypeObject.tp_init) * [PyTypeObject.tp\_is\_gc (C member)](c-api/typeobj#c.PyTypeObject.tp_is_gc) * [PyTypeObject.tp\_itemsize (C member)](c-api/typeobj#c.PyTypeObject.tp_itemsize) * [PyTypeObject.tp\_iter (C member)](c-api/typeobj#c.PyTypeObject.tp_iter) * [PyTypeObject.tp\_iternext (C member)](c-api/typeobj#c.PyTypeObject.tp_iternext) * [PyTypeObject.tp\_members (C member)](c-api/typeobj#c.PyTypeObject.tp_members) * [PyTypeObject.tp\_methods (C member)](c-api/typeobj#c.PyTypeObject.tp_methods) * [PyTypeObject.tp\_mro (C member)](c-api/typeobj#c.PyTypeObject.tp_mro) * [PyTypeObject.tp\_name (C member)](c-api/typeobj#c.PyTypeObject.tp_name) * [PyTypeObject.tp\_new (C member)](c-api/typeobj#c.PyTypeObject.tp_new) * [PyTypeObject.tp\_repr (C member)](c-api/typeobj#c.PyTypeObject.tp_repr) * [PyTypeObject.tp\_richcompare (C member)](c-api/typeobj#c.PyTypeObject.tp_richcompare) * [PyTypeObject.tp\_setattr (C member)](c-api/typeobj#c.PyTypeObject.tp_setattr) * [PyTypeObject.tp\_setattro (C member)](c-api/typeobj#c.PyTypeObject.tp_setattro) * [PyTypeObject.tp\_str (C member)](c-api/typeobj#c.PyTypeObject.tp_str) * [PyTypeObject.tp\_subclasses (C member)](c-api/typeobj#c.PyTypeObject.tp_subclasses) * [PyTypeObject.tp\_traverse (C member)](c-api/typeobj#c.PyTypeObject.tp_traverse) * [PyTypeObject.tp\_vectorcall (C member)](c-api/typeobj#c.PyTypeObject.tp_vectorcall) * [PyTypeObject.tp\_vectorcall\_offset (C member)](c-api/typeobj#c.PyTypeObject.tp_vectorcall_offset) * [PyTypeObject.tp\_version\_tag (C member)](c-api/typeobj#c.PyTypeObject.tp_version_tag) * [PyTypeObject.tp\_weaklist (C member)](c-api/typeobj#c.PyTypeObject.tp_weaklist) * [PyTypeObject.tp\_weaklistoffset (C member)](c-api/typeobj#c.PyTypeObject.tp_weaklistoffset) * [PyTZInfo\_Check (C function)](c-api/datetime#c.PyTZInfo_Check) * [PyTZInfo\_CheckExact (C function)](c-api/datetime#c.PyTZInfo_CheckExact) * [PyUnicode\_1BYTE\_DATA (C function)](c-api/unicode#c.PyUnicode_1BYTE_DATA) * [PyUnicode\_1BYTE\_KIND (C macro)](c-api/unicode#c.PyUnicode_1BYTE_KIND) * [PyUnicode\_2BYTE\_DATA (C function)](c-api/unicode#c.PyUnicode_2BYTE_DATA) * [PyUnicode\_2BYTE\_KIND (C macro)](c-api/unicode#c.PyUnicode_2BYTE_KIND) * [PyUnicode\_4BYTE\_DATA (C function)](c-api/unicode#c.PyUnicode_4BYTE_DATA) * [PyUnicode\_4BYTE\_KIND (C macro)](c-api/unicode#c.PyUnicode_4BYTE_KIND) * [PyUnicode\_AS\_DATA (C function)](c-api/unicode#c.PyUnicode_AS_DATA) * [PyUnicode\_AS\_UNICODE (C function)](c-api/unicode#c.PyUnicode_AS_UNICODE) * [PyUnicode\_AsASCIIString (C function)](c-api/unicode#c.PyUnicode_AsASCIIString) * [PyUnicode\_AsCharmapString (C function)](c-api/unicode#c.PyUnicode_AsCharmapString) * [PyUnicode\_AsEncodedString (C function)](c-api/unicode#c.PyUnicode_AsEncodedString) * [PyUnicode\_AsLatin1String (C function)](c-api/unicode#c.PyUnicode_AsLatin1String) * [PyUnicode\_AsMBCSString (C function)](c-api/unicode#c.PyUnicode_AsMBCSString) * [PyUnicode\_AsRawUnicodeEscapeString (C function)](c-api/unicode#c.PyUnicode_AsRawUnicodeEscapeString) * [PyUnicode\_AsUCS4 (C function)](c-api/unicode#c.PyUnicode_AsUCS4) * [PyUnicode\_AsUCS4Copy (C function)](c-api/unicode#c.PyUnicode_AsUCS4Copy) * [PyUnicode\_AsUnicode (C function)](c-api/unicode#c.PyUnicode_AsUnicode) * [PyUnicode\_AsUnicodeAndSize (C function)](c-api/unicode#c.PyUnicode_AsUnicodeAndSize) * [PyUnicode\_AsUnicodeCopy (C function)](c-api/unicode#c.PyUnicode_AsUnicodeCopy) * [PyUnicode\_AsUnicodeEscapeString (C function)](c-api/unicode#c.PyUnicode_AsUnicodeEscapeString) * [PyUnicode\_AsUTF16String (C function)](c-api/unicode#c.PyUnicode_AsUTF16String) * [PyUnicode\_AsUTF32String (C function)](c-api/unicode#c.PyUnicode_AsUTF32String) * [PyUnicode\_AsUTF8 (C function)](c-api/unicode#c.PyUnicode_AsUTF8) * [PyUnicode\_AsUTF8AndSize (C function)](c-api/unicode#c.PyUnicode_AsUTF8AndSize) * [PyUnicode\_AsUTF8String (C function)](c-api/unicode#c.PyUnicode_AsUTF8String) * [PyUnicode\_AsWideChar (C function)](c-api/unicode#c.PyUnicode_AsWideChar) * [PyUnicode\_AsWideCharString (C function)](c-api/unicode#c.PyUnicode_AsWideCharString) * [PyUnicode\_Check (C function)](c-api/unicode#c.PyUnicode_Check) * [PyUnicode\_CheckExact (C function)](c-api/unicode#c.PyUnicode_CheckExact) * [PyUnicode\_Compare (C function)](c-api/unicode#c.PyUnicode_Compare) * [PyUnicode\_CompareWithASCIIString (C function)](c-api/unicode#c.PyUnicode_CompareWithASCIIString) * [PyUnicode\_Concat (C function)](c-api/unicode#c.PyUnicode_Concat) * [PyUnicode\_Contains (C function)](c-api/unicode#c.PyUnicode_Contains) * [PyUnicode\_CopyCharacters (C function)](c-api/unicode#c.PyUnicode_CopyCharacters) * [PyUnicode\_Count (C function)](c-api/unicode#c.PyUnicode_Count) * [PyUnicode\_DATA (C function)](c-api/unicode#c.PyUnicode_DATA) * [PyUnicode\_Decode (C function)](c-api/unicode#c.PyUnicode_Decode) * [PyUnicode\_DecodeASCII (C function)](c-api/unicode#c.PyUnicode_DecodeASCII) * [PyUnicode\_DecodeCharmap (C function)](c-api/unicode#c.PyUnicode_DecodeCharmap) * [PyUnicode\_DecodeFSDefault (C function)](c-api/unicode#c.PyUnicode_DecodeFSDefault) * [PyUnicode\_DecodeFSDefaultAndSize (C function)](c-api/unicode#c.PyUnicode_DecodeFSDefaultAndSize) * [PyUnicode\_DecodeLatin1 (C function)](c-api/unicode#c.PyUnicode_DecodeLatin1) * [PyUnicode\_DecodeLocale (C function)](c-api/unicode#c.PyUnicode_DecodeLocale) * [PyUnicode\_DecodeLocaleAndSize (C function)](c-api/unicode#c.PyUnicode_DecodeLocaleAndSize) * [PyUnicode\_DecodeMBCS (C function)](c-api/unicode#c.PyUnicode_DecodeMBCS) * [PyUnicode\_DecodeMBCSStateful (C function)](c-api/unicode#c.PyUnicode_DecodeMBCSStateful) * [PyUnicode\_DecodeRawUnicodeEscape (C function)](c-api/unicode#c.PyUnicode_DecodeRawUnicodeEscape) * [PyUnicode\_DecodeUnicodeEscape (C function)](c-api/unicode#c.PyUnicode_DecodeUnicodeEscape) * [PyUnicode\_DecodeUTF16 (C function)](c-api/unicode#c.PyUnicode_DecodeUTF16) * [PyUnicode\_DecodeUTF16Stateful (C function)](c-api/unicode#c.PyUnicode_DecodeUTF16Stateful) * [PyUnicode\_DecodeUTF32 (C function)](c-api/unicode#c.PyUnicode_DecodeUTF32) * [PyUnicode\_DecodeUTF32Stateful (C function)](c-api/unicode#c.PyUnicode_DecodeUTF32Stateful) * [PyUnicode\_DecodeUTF7 (C function)](c-api/unicode#c.PyUnicode_DecodeUTF7) * [PyUnicode\_DecodeUTF7Stateful (C function)](c-api/unicode#c.PyUnicode_DecodeUTF7Stateful) * [PyUnicode\_DecodeUTF8 (C function)](c-api/unicode#c.PyUnicode_DecodeUTF8) * [PyUnicode\_DecodeUTF8Stateful (C function)](c-api/unicode#c.PyUnicode_DecodeUTF8Stateful) * [PyUnicode\_Encode (C function)](c-api/unicode#c.PyUnicode_Encode) * [PyUnicode\_EncodeASCII (C function)](c-api/unicode#c.PyUnicode_EncodeASCII) * [PyUnicode\_EncodeCharmap (C function)](c-api/unicode#c.PyUnicode_EncodeCharmap) * [PyUnicode\_EncodeCodePage (C function)](c-api/unicode#c.PyUnicode_EncodeCodePage) * [PyUnicode\_EncodeFSDefault (C function)](c-api/unicode#c.PyUnicode_EncodeFSDefault) * [PyUnicode\_EncodeLatin1 (C function)](c-api/unicode#c.PyUnicode_EncodeLatin1) * [PyUnicode\_EncodeLocale (C function)](c-api/unicode#c.PyUnicode_EncodeLocale) * [PyUnicode\_EncodeMBCS (C function)](c-api/unicode#c.PyUnicode_EncodeMBCS) * [PyUnicode\_EncodeRawUnicodeEscape (C function)](c-api/unicode#c.PyUnicode_EncodeRawUnicodeEscape) * [PyUnicode\_EncodeUnicodeEscape (C function)](c-api/unicode#c.PyUnicode_EncodeUnicodeEscape) * [PyUnicode\_EncodeUTF16 (C function)](c-api/unicode#c.PyUnicode_EncodeUTF16) * [PyUnicode\_EncodeUTF32 (C function)](c-api/unicode#c.PyUnicode_EncodeUTF32) * [PyUnicode\_EncodeUTF7 (C function)](c-api/unicode#c.PyUnicode_EncodeUTF7) * [PyUnicode\_EncodeUTF8 (C function)](c-api/unicode#c.PyUnicode_EncodeUTF8) * [PyUnicode\_Fill (C function)](c-api/unicode#c.PyUnicode_Fill) * [PyUnicode\_Find (C function)](c-api/unicode#c.PyUnicode_Find) * [PyUnicode\_FindChar (C function)](c-api/unicode#c.PyUnicode_FindChar) * [PyUnicode\_Format (C function)](c-api/unicode#c.PyUnicode_Format) * [PyUnicode\_FromEncodedObject (C function)](c-api/unicode#c.PyUnicode_FromEncodedObject) * [PyUnicode\_FromFormat (C function)](c-api/unicode#c.PyUnicode_FromFormat) * [PyUnicode\_FromFormatV (C function)](c-api/unicode#c.PyUnicode_FromFormatV) * [PyUnicode\_FromKindAndData (C function)](c-api/unicode#c.PyUnicode_FromKindAndData) * [PyUnicode\_FromObject (C function)](c-api/unicode#c.PyUnicode_FromObject) * [PyUnicode\_FromString (C function)](c-api/unicode#c.PyUnicode_FromString) * [PyUnicode\_FromString()](c-api/dict#index-1) * [PyUnicode\_FromStringAndSize (C function)](c-api/unicode#c.PyUnicode_FromStringAndSize) * [PyUnicode\_FromUnicode (C function)](c-api/unicode#c.PyUnicode_FromUnicode) * [PyUnicode\_FromWideChar (C function)](c-api/unicode#c.PyUnicode_FromWideChar) * [PyUnicode\_FSConverter (C function)](c-api/unicode#c.PyUnicode_FSConverter) * [PyUnicode\_FSDecoder (C function)](c-api/unicode#c.PyUnicode_FSDecoder) * [PyUnicode\_GET\_DATA\_SIZE (C function)](c-api/unicode#c.PyUnicode_GET_DATA_SIZE) * [PyUnicode\_GET\_LENGTH (C function)](c-api/unicode#c.PyUnicode_GET_LENGTH) * [PyUnicode\_GET\_SIZE (C function)](c-api/unicode#c.PyUnicode_GET_SIZE) * [PyUnicode\_GetLength (C function)](c-api/unicode#c.PyUnicode_GetLength) * [PyUnicode\_GetSize (C function)](c-api/unicode#c.PyUnicode_GetSize) * [PyUnicode\_InternFromString (C function)](c-api/unicode#c.PyUnicode_InternFromString) * [PyUnicode\_InternInPlace (C function)](c-api/unicode#c.PyUnicode_InternInPlace) * [PyUnicode\_IsIdentifier (C function)](c-api/unicode#c.PyUnicode_IsIdentifier) * [PyUnicode\_Join (C function)](c-api/unicode#c.PyUnicode_Join) * [PyUnicode\_KIND (C function)](c-api/unicode#c.PyUnicode_KIND) * [PyUnicode\_MAX\_CHAR\_VALUE (C macro)](c-api/unicode#c.PyUnicode_MAX_CHAR_VALUE) * [PyUnicode\_New (C function)](c-api/unicode#c.PyUnicode_New) * [PyUnicode\_READ (C function)](c-api/unicode#c.PyUnicode_READ) * [PyUnicode\_READ\_CHAR (C function)](c-api/unicode#c.PyUnicode_READ_CHAR) * [PyUnicode\_ReadChar (C function)](c-api/unicode#c.PyUnicode_ReadChar) * [PyUnicode\_READY (C function)](c-api/unicode#c.PyUnicode_READY) * [PyUnicode\_Replace (C function)](c-api/unicode#c.PyUnicode_Replace) * [PyUnicode\_RichCompare (C function)](c-api/unicode#c.PyUnicode_RichCompare) * [PyUnicode\_Split (C function)](c-api/unicode#c.PyUnicode_Split) * [PyUnicode\_Splitlines (C function)](c-api/unicode#c.PyUnicode_Splitlines) * [PyUnicode\_Substring (C function)](c-api/unicode#c.PyUnicode_Substring) * [PyUnicode\_Tailmatch (C function)](c-api/unicode#c.PyUnicode_Tailmatch) * [PyUnicode\_TransformDecimalToASCII (C function)](c-api/unicode#c.PyUnicode_TransformDecimalToASCII) * [PyUnicode\_Translate (C function)](c-api/unicode#c.PyUnicode_Translate) * [PyUnicode\_TranslateCharmap (C function)](c-api/unicode#c.PyUnicode_TranslateCharmap) * [PyUnicode\_Type (C variable)](c-api/unicode#c.PyUnicode_Type) * [PyUnicode\_WCHAR\_KIND (C macro)](c-api/unicode#c.PyUnicode_WCHAR_KIND) * [PyUnicode\_WRITE (C function)](c-api/unicode#c.PyUnicode_WRITE) * [PyUnicode\_WriteChar (C function)](c-api/unicode#c.PyUnicode_WriteChar) * [PyUnicodeDecodeError\_Create (C function)](c-api/exceptions#c.PyUnicodeDecodeError_Create) * [PyUnicodeDecodeError\_GetEncoding (C function)](c-api/exceptions#c.PyUnicodeDecodeError_GetEncoding) * [PyUnicodeDecodeError\_GetEnd (C function)](c-api/exceptions#c.PyUnicodeDecodeError_GetEnd) * [PyUnicodeDecodeError\_GetObject (C function)](c-api/exceptions#c.PyUnicodeDecodeError_GetObject) * [PyUnicodeDecodeError\_GetReason (C function)](c-api/exceptions#c.PyUnicodeDecodeError_GetReason) * [PyUnicodeDecodeError\_GetStart (C function)](c-api/exceptions#c.PyUnicodeDecodeError_GetStart) * [PyUnicodeDecodeError\_SetEnd (C function)](c-api/exceptions#c.PyUnicodeDecodeError_SetEnd) * [PyUnicodeDecodeError\_SetReason (C function)](c-api/exceptions#c.PyUnicodeDecodeError_SetReason) * [PyUnicodeDecodeError\_SetStart (C function)](c-api/exceptions#c.PyUnicodeDecodeError_SetStart) * [PyUnicodeEncodeError\_Create (C function)](c-api/exceptions#c.PyUnicodeEncodeError_Create) * [PyUnicodeEncodeError\_GetEncoding (C function)](c-api/exceptions#c.PyUnicodeEncodeError_GetEncoding) * [PyUnicodeEncodeError\_GetEnd (C function)](c-api/exceptions#c.PyUnicodeEncodeError_GetEnd) * [PyUnicodeEncodeError\_GetObject (C function)](c-api/exceptions#c.PyUnicodeEncodeError_GetObject) * [PyUnicodeEncodeError\_GetReason (C function)](c-api/exceptions#c.PyUnicodeEncodeError_GetReason) * [PyUnicodeEncodeError\_GetStart (C function)](c-api/exceptions#c.PyUnicodeEncodeError_GetStart) * [PyUnicodeEncodeError\_SetEnd (C function)](c-api/exceptions#c.PyUnicodeEncodeError_SetEnd) * [PyUnicodeEncodeError\_SetReason (C function)](c-api/exceptions#c.PyUnicodeEncodeError_SetReason) * [PyUnicodeEncodeError\_SetStart (C function)](c-api/exceptions#c.PyUnicodeEncodeError_SetStart) * [PyUnicodeObject (C type)](c-api/unicode#c.PyUnicodeObject) * [PyUnicodeTranslateError\_Create (C function)](c-api/exceptions#c.PyUnicodeTranslateError_Create) * [PyUnicodeTranslateError\_GetEnd (C function)](c-api/exceptions#c.PyUnicodeTranslateError_GetEnd) * [PyUnicodeTranslateError\_GetObject (C function)](c-api/exceptions#c.PyUnicodeTranslateError_GetObject) * [PyUnicodeTranslateError\_GetReason (C function)](c-api/exceptions#c.PyUnicodeTranslateError_GetReason) * [PyUnicodeTranslateError\_GetStart (C function)](c-api/exceptions#c.PyUnicodeTranslateError_GetStart) * [PyUnicodeTranslateError\_SetEnd (C function)](c-api/exceptions#c.PyUnicodeTranslateError_SetEnd) * [PyUnicodeTranslateError\_SetReason (C function)](c-api/exceptions#c.PyUnicodeTranslateError_SetReason) * [PyUnicodeTranslateError\_SetStart (C function)](c-api/exceptions#c.PyUnicodeTranslateError_SetStart) * [PyVarObject (C type)](c-api/structures#c.PyVarObject) * [PyVarObject.ob\_size (C member)](c-api/typeobj#c.PyVarObject.ob_size) * [PyVarObject\_HEAD\_INIT (C macro)](c-api/structures#c.PyVarObject_HEAD_INIT) * [PyVectorcall\_Call (C function)](c-api/call#c.PyVectorcall_Call) * [PyVectorcall\_Function (C function)](c-api/call#c.PyVectorcall_Function) * [PyVectorcall\_NARGS (C function)](c-api/call#c.PyVectorcall_NARGS) * [PyWeakref\_Check (C function)](c-api/weakref#c.PyWeakref_Check) * [PyWeakref\_CheckProxy (C function)](c-api/weakref#c.PyWeakref_CheckProxy) * [PyWeakref\_CheckRef (C function)](c-api/weakref#c.PyWeakref_CheckRef) * [PyWeakref\_GET\_OBJECT (C function)](c-api/weakref#c.PyWeakref_GET_OBJECT) * [PyWeakref\_GetObject (C function)](c-api/weakref#c.PyWeakref_GetObject) * [PyWeakref\_NewProxy (C function)](c-api/weakref#c.PyWeakref_NewProxy) * [PyWeakref\_NewRef (C function)](c-api/weakref#c.PyWeakref_NewRef) * [PyWideStringList (C type)](c-api/init_config#c.PyWideStringList) * [PyWideStringList.items (C member)](c-api/init_config#c.PyWideStringList.items) * [PyWideStringList.length (C member)](c-api/init_config#c.PyWideStringList.length) * [PyWideStringList\_Append (C function)](c-api/init_config#c.PyWideStringList_Append) * [PyWideStringList\_Insert (C function)](c-api/init_config#c.PyWideStringList_Insert) * [PyWrapper\_New (C function)](c-api/descriptor#c.PyWrapper_New) * [PyZipFile (class in zipfile)](library/zipfile#zipfile.PyZipFile) | Q - | | | | --- | --- | | * [qiflush() (in module curses)](library/curses#curses.qiflush) * [QName (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.QName) * [qsize() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.qsize) + [(multiprocessing.Queue method)](library/multiprocessing#multiprocessing.Queue.qsize) + [(queue.Queue method)](library/queue#queue.Queue.qsize) + [(queue.SimpleQueue method)](library/queue#queue.SimpleQueue.qsize) * [**qualified name**](glossary#term-qualified-name) * [quantiles() (in module statistics)](library/statistics#statistics.quantiles) + [(statistics.NormalDist method)](library/statistics#statistics.NormalDist.quantiles) * [quantize() (decimal.Context method)](library/decimal#decimal.Context.quantize) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.quantize) * [QueryInfoKey() (in module winreg)](library/winreg#winreg.QueryInfoKey) * [QueryReflectionKey() (in module winreg)](library/winreg#winreg.QueryReflectionKey) * [QueryValue() (in module winreg)](library/winreg#winreg.QueryValue) * [QueryValueEx() (in module winreg)](library/winreg#winreg.QueryValueEx) * [Queue (class in asyncio)](library/asyncio-queue#asyncio.Queue) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.Queue) + [(class in queue)](library/queue#queue.Queue) * [queue (module)](library/queue#module-queue) + [(sched.scheduler attribute)](library/sched#sched.scheduler.queue) * [Queue() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Queue) * [QueueEmpty](library/asyncio-queue#asyncio.QueueEmpty) * [QueueFull](library/asyncio-queue#asyncio.QueueFull) * [QueueHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.QueueHandler) | * [QueueListener (class in logging.handlers)](library/logging.handlers#logging.handlers.QueueListener) * [quick\_ratio() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.quick_ratio) * [quit (built-in variable)](library/constants#quit) + [(pdb command)](library/pdb#pdbcommand-quit) * [quit() (ftplib.FTP method)](library/ftplib#ftplib.FTP.quit) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.quit) + [(poplib.POP3 method)](library/poplib#poplib.POP3.quit) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.quit) + [(tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.quit) * [quopri (module)](library/quopri#module-quopri) * [quote() (in module email.utils)](library/email.utils#email.utils.quote) + [(in module shlex)](library/shlex#shlex.quote) + [(in module urllib.parse)](library/urllib.parse#urllib.parse.quote) * [QUOTE\_ALL (in module csv)](library/csv#csv.QUOTE_ALL) * [quote\_from\_bytes() (in module urllib.parse)](library/urllib.parse#urllib.parse.quote_from_bytes) * [QUOTE\_MINIMAL (in module csv)](library/csv#csv.QUOTE_MINIMAL) * [QUOTE\_NONE (in module csv)](library/csv#csv.QUOTE_NONE) * [QUOTE\_NONNUMERIC (in module csv)](library/csv#csv.QUOTE_NONNUMERIC) * [quote\_plus() (in module urllib.parse)](library/urllib.parse#urllib.parse.quote_plus) * [quoteattr() (in module xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.quoteattr) * [quotechar (csv.Dialect attribute)](library/csv#csv.Dialect.quotechar) * quoted-printable + [encoding](library/quopri#index-0) * [quotes (shlex.shlex attribute)](library/shlex#shlex.shlex.quotes) * [quoting (csv.Dialect attribute)](library/csv#csv.Dialect.quoting) | R - | | | | --- | --- | | * r" + [raw string literal](reference/lexical_analysis#index-19) * r' + [raw string literal](reference/lexical_analysis#index-19) * [R\_OK (in module os)](library/os#os.R_OK) * [radians() (in module math)](library/math#math.radians) + [(in module turtle)](library/turtle#turtle.radians) * [RadioButtonGroup (class in msilib)](library/msilib#msilib.RadioButtonGroup) * [radiogroup() (msilib.Dialog method)](library/msilib#msilib.Dialog.radiogroup) * [radix() (decimal.Context method)](library/decimal#decimal.Context.radix) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.radix) * [RADIXCHAR (in module locale)](library/locale#locale.RADIXCHAR) * raise + [statement](library/exceptions#index-1), [**[1]**](reference/simple_stmts#index-27) * [raise (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-raise) * [Raise (class in ast)](library/ast#ast.Raise) * [raise an exception](reference/executionmodel#index-13) * [raise\_on\_defect (email.policy.Policy attribute)](library/email.policy#email.policy.Policy.raise_on_defect) * [raise\_signal() (in module signal)](library/signal#signal.raise_signal) * [RAISE\_VARARGS (opcode)](library/dis#opcode-RAISE_VARARGS) * raising + [exception](reference/simple_stmts#index-27) * [RAND\_add() (in module ssl)](library/ssl#ssl.RAND_add) * [RAND\_bytes() (in module ssl)](library/ssl#ssl.RAND_bytes) * [RAND\_egd() (in module ssl)](library/ssl#ssl.RAND_egd) * [RAND\_pseudo\_bytes() (in module ssl)](library/ssl#ssl.RAND_pseudo_bytes) * [RAND\_status() (in module ssl)](library/ssl#ssl.RAND_status) * [randbelow() (in module secrets)](library/secrets#secrets.randbelow) * [randbits() (in module secrets)](library/secrets#secrets.randbits) * [randbytes() (in module random)](library/random#random.randbytes) * [randint() (in module random)](library/random#random.randint) * [Random (class in random)](library/random#random.Random) * [random (module)](library/random#module-random) * [random() (in module random)](library/random#random.random) * [randrange() (in module random)](library/random#random.randrange) * range + [built-in function](reference/compound_stmts#index-8) + [object](library/stdtypes#index-25) * [range (built-in class)](library/stdtypes#range) * [RARROW (in module token)](library/token#token.RARROW) * [ratecv() (in module audioop)](library/audioop#audioop.ratecv) * [ratio() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.ratio) * [Rational (class in numbers)](library/numbers#numbers.Rational) * [raw (io.BufferedIOBase attribute)](library/io#io.BufferedIOBase.raw) * [raw string](reference/lexical_analysis#index-17) * [raw() (in module curses)](library/curses#curses.raw) + [(pickle.PickleBuffer method)](library/pickle#pickle.PickleBuffer.raw) * [raw\_data\_manager (in module email.contentmanager)](library/email.contentmanager#email.contentmanager.raw_data_manager) * [raw\_decode() (json.JSONDecoder method)](library/json#json.JSONDecoder.raw_decode) * [raw\_input (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-raw_input) * [raw\_input() (code.InteractiveConsole method)](library/code#code.InteractiveConsole.raw_input) * [RawArray() (in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.RawArray) * [RawConfigParser (class in configparser)](library/configparser#configparser.RawConfigParser) * [RawDescriptionHelpFormatter (class in argparse)](library/argparse#argparse.RawDescriptionHelpFormatter) * [RawIOBase (class in io)](library/io#io.RawIOBase) * [RawPen (class in turtle)](library/turtle#turtle.RawPen) * [RawTextHelpFormatter (class in argparse)](library/argparse#argparse.RawTextHelpFormatter) * [RawTurtle (class in turtle)](library/turtle#turtle.RawTurtle) * [RawValue() (in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.RawValue) * [RBRACE (in module token)](library/token#token.RBRACE) * [rcpttos (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.rcpttos) * re + [module](library/fnmatch#index-1), [[1]](library/stdtypes#index-31) * [re (module)](library/re#module-re) + [(re.Match attribute)](library/re#re.Match.re) * [read() (asyncio.StreamReader method)](library/asyncio-stream#asyncio.StreamReader.read) + [(chunk.Chunk method)](library/chunk#chunk.Chunk.read) + [(codecs.StreamReader method)](library/codecs#codecs.StreamReader.read) + [(configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.read) + [(http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.read) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.read) + [(in module os)](library/os#os.read) + [(io.BufferedIOBase method)](library/io#io.BufferedIOBase.read) + [(io.BufferedReader method)](library/io#io.BufferedReader.read) + [(io.RawIOBase method)](library/io#io.RawIOBase.read) + [(io.TextIOBase method)](library/io#io.TextIOBase.read) + [(mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.read) + [(mmap.mmap method)](library/mmap#mmap.mmap.read) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.read) + [(ssl.MemoryBIO method)](library/ssl#ssl.MemoryBIO.read) + [(ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.read) + [(urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.read) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.read) * [read1() (io.BufferedIOBase method)](library/io#io.BufferedIOBase.read1) + [(io.BufferedReader method)](library/io#io.BufferedReader.read1) + [(io.BytesIO method)](library/io#io.BytesIO.read1) * [read\_all() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_all) * [read\_binary() (in module importlib.resources)](library/importlib#importlib.resources.read_binary) * [read\_byte() (mmap.mmap method)](library/mmap#mmap.mmap.read_byte) * [read\_bytes() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.read_bytes) + [(pathlib.Path method)](library/pathlib#pathlib.Path.read_bytes) + [(zipfile.Path method)](library/zipfile#zipfile.Path.read_bytes) * [read\_dict() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.read_dict) * [read\_eager() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_eager) * [read\_environ() (in module wsgiref.handlers)](library/wsgiref#wsgiref.handlers.read_environ) * [read\_events() (xml.etree.ElementTree.XMLPullParser method)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLPullParser.read_events) * [read\_file() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.read_file) * [read\_history\_file() (in module readline)](library/readline#readline.read_history_file) * [read\_init\_file() (in module readline)](library/readline#readline.read_init_file) * [read\_lazy() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_lazy) * [read\_mime\_types() (in module mimetypes)](library/mimetypes#mimetypes.read_mime_types) * [READ\_RESTRICTED](extending/newtypes#index-4) * [read\_sb\_data() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_sb_data) * [read\_some() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_some) * [read\_string() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.read_string) * [read\_text() (importlib.abc.Traversable method)](library/importlib#importlib.abc.Traversable.read_text) + [(in module importlib.resources)](library/importlib#importlib.resources.read_text) + [(pathlib.Path method)](library/pathlib#pathlib.Path.read_text) + [(zipfile.Path method)](library/zipfile#zipfile.Path.read_text) * [read\_token() (shlex.shlex method)](library/shlex#shlex.shlex.read_token) * [read\_until() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_until) * [read\_very\_eager() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_very_eager) * [read\_very\_lazy() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.read_very_lazy) * [read\_windows\_registry() (mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.read_windows_registry) * [READABLE (in module tkinter)](library/tkinter#tkinter.READABLE) * [readable() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.readable) + [(io.IOBase method)](library/io#io.IOBase.readable) * [readall() (io.RawIOBase method)](library/io#io.RawIOBase.readall) * [reader() (in module csv)](library/csv#csv.reader) * [ReadError](library/tarfile#tarfile.ReadError) * [readexactly() (asyncio.StreamReader method)](library/asyncio-stream#asyncio.StreamReader.readexactly) * [readfp() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.readfp) + [(mimetypes.MimeTypes method)](library/mimetypes#mimetypes.MimeTypes.readfp) * [readframes() (aifc.aifc method)](library/aifc#aifc.aifc.readframes) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.readframes) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.readframes) * [readinto() (http.client.HTTPResponse method)](library/http.client#http.client.HTTPResponse.readinto) + [(io.BufferedIOBase method)](library/io#io.BufferedIOBase.readinto) + [(io.RawIOBase method)](library/io#io.RawIOBase.readinto) * [readinto1() (io.BufferedIOBase method)](library/io#io.BufferedIOBase.readinto1) + [(io.BytesIO method)](library/io#io.BytesIO.readinto1) * [readline (module)](library/readline#module-readline) * [readline() (asyncio.StreamReader method)](library/asyncio-stream#asyncio.StreamReader.readline) + [(codecs.StreamReader method)](library/codecs#codecs.StreamReader.readline) + [(distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.readline) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.readline) + [(io.IOBase method)](library/io#io.IOBase.readline) + [(io.TextIOBase method)](library/io#io.TextIOBase.readline) + [(mmap.mmap method)](library/mmap#mmap.mmap.readline) * [readlines() (codecs.StreamReader method)](library/codecs#codecs.StreamReader.readlines) + [(distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.readlines) + [(io.IOBase method)](library/io#io.IOBase.readlines) * [readlink() (in module os)](library/os#os.readlink) + [(pathlib.Path method)](library/pathlib#pathlib.Path.readlink) * [readmodule() (in module pyclbr)](library/pyclbr#pyclbr.readmodule) * [readmodule\_ex() (in module pyclbr)](library/pyclbr#pyclbr.readmodule_ex) * [READONLY](extending/newtypes#index-4) * [readonly (memoryview attribute)](library/stdtypes#memoryview.readonly) * [ReadTransport (class in asyncio)](library/asyncio-protocol#asyncio.ReadTransport) * [readuntil() (asyncio.StreamReader method)](library/asyncio-stream#asyncio.StreamReader.readuntil) * [readv() (in module os)](library/os#os.readv) * [ready() (multiprocessing.pool.AsyncResult method)](library/multiprocessing#multiprocessing.pool.AsyncResult.ready) * [Real (class in numbers)](library/numbers#numbers.Real) * [real (numbers.Complex attribute)](library/numbers#numbers.Complex.real) * [Real Media File Format](library/chunk#index-0) * [real\_max\_memuse (in module test.support)](library/test#test.support.real_max_memuse) * [real\_quick\_ratio() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.real_quick_ratio) * [realloc()](c-api/memory#index-0) * [realpath() (in module os.path)](library/os.path#os.path.realpath) * [REALTIME\_PRIORITY\_CLASS (in module subprocess)](library/subprocess#subprocess.REALTIME_PRIORITY_CLASS) * [reap\_children() (in module test.support)](library/test#test.support.reap_children) * [reap\_threads() (in module test.support)](library/test#test.support.reap_threads) * [reason (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.reason) + [(ssl.SSLError attribute)](library/ssl#ssl.SSLError.reason) + [(UnicodeError attribute)](library/exceptions#UnicodeError.reason) + [(urllib.error.HTTPError attribute)](library/urllib.error#urllib.error.HTTPError.reason) + [(urllib.error.URLError attribute)](library/urllib.error#urllib.error.URLError.reason) * [reattach() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.reattach) * rebinding + [name](reference/simple_stmts#index-4) * [reccontrols() (ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.reccontrols) * [received\_data (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.received_data) * [received\_lines (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.received_lines) * [recent() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.recent) * [reconfigure() (io.TextIOWrapper method)](library/io#io.TextIOWrapper.reconfigure) * [record\_original\_stdout() (in module test.support)](library/test#test.support.record_original_stdout) * [records (unittest.TestCase attribute)](library/unittest#unittest.TestCase.records) * [rect() (in module cmath)](library/cmath#cmath.rect) * [rectangle() (in module curses.textpad)](library/curses#curses.textpad.rectangle) * [RecursionError](library/exceptions#RecursionError) * [recursive\_repr() (in module reprlib)](library/reprlib#reprlib.recursive_repr) * [recv() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.recv) + [(multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.recv) + [(socket.socket method)](library/socket#socket.socket.recv) * [recv\_bytes() (multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.recv_bytes) * [recv\_bytes\_into() (multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.recv_bytes_into) * [recv\_fds() (in module socket)](library/socket#socket.recv_fds) * [recv\_into() (socket.socket method)](library/socket#socket.socket.recv_into) * [recvfrom() (socket.socket method)](library/socket#socket.socket.recvfrom) * [recvfrom\_into() (socket.socket method)](library/socket#socket.socket.recvfrom_into) * [recvmsg() (socket.socket method)](library/socket#socket.socket.recvmsg) * [recvmsg\_into() (socket.socket method)](library/socket#socket.socket.recvmsg_into) * [redirect\_request() (urllib.request.HTTPRedirectHandler method)](library/urllib.request#urllib.request.HTTPRedirectHandler.redirect_request) * [redirect\_stderr() (in module contextlib)](library/contextlib#contextlib.redirect_stderr) * [redirect\_stdout() (in module contextlib)](library/contextlib#contextlib.redirect_stdout) * [redisplay() (in module readline)](library/readline#readline.redisplay) * [redrawln() (curses.window method)](library/curses#curses.window.redrawln) * [redrawwin() (curses.window method)](library/curses#curses.window.redrawwin) * [reduce (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-reduce) * [reduce() (in module functools)](library/functools#functools.reduce) * [reducer\_override() (pickle.Pickler method)](library/pickle#pickle.Pickler.reducer_override) * [ref (class in weakref)](library/weakref#weakref.ref) * [refcount\_test() (in module test.support)](library/test#test.support.refcount_test) * reference + [attribute](reference/expressions#index-39) * [**reference count**](glossary#term-reference-count) * [reference counting](reference/datamodel#index-2) * [ReferenceError](library/exceptions#ReferenceError) * [ReferenceType (in module weakref)](library/weakref#weakref.ReferenceType) * [refold\_source (email.policy.EmailPolicy attribute)](library/email.policy#email.policy.EmailPolicy.refold_source) * [refresh() (curses.window method)](library/curses#curses.window.refresh) * [REG\_BINARY (in module winreg)](library/winreg#winreg.REG_BINARY) * [REG\_DWORD (in module winreg)](library/winreg#winreg.REG_DWORD) * [REG\_DWORD\_BIG\_ENDIAN (in module winreg)](library/winreg#winreg.REG_DWORD_BIG_ENDIAN) * [REG\_DWORD\_LITTLE\_ENDIAN (in module winreg)](library/winreg#winreg.REG_DWORD_LITTLE_ENDIAN) * [REG\_EXPAND\_SZ (in module winreg)](library/winreg#winreg.REG_EXPAND_SZ) * [REG\_FULL\_RESOURCE\_DESCRIPTOR (in module winreg)](library/winreg#winreg.REG_FULL_RESOURCE_DESCRIPTOR) * [REG\_LINK (in module winreg)](library/winreg#winreg.REG_LINK) * [REG\_MULTI\_SZ (in module winreg)](library/winreg#winreg.REG_MULTI_SZ) * [REG\_NONE (in module winreg)](library/winreg#winreg.REG_NONE) * [REG\_QWORD (in module winreg)](library/winreg#winreg.REG_QWORD) * [REG\_QWORD\_LITTLE\_ENDIAN (in module winreg)](library/winreg#winreg.REG_QWORD_LITTLE_ENDIAN) * [REG\_RESOURCE\_LIST (in module winreg)](library/winreg#winreg.REG_RESOURCE_LIST) * [REG\_RESOURCE\_REQUIREMENTS\_LIST (in module winreg)](library/winreg#winreg.REG_RESOURCE_REQUIREMENTS_LIST) * [REG\_SZ (in module winreg)](library/winreg#winreg.REG_SZ) * [register() (abc.ABCMeta method)](library/abc#abc.ABCMeta.register) + [(in module atexit)](library/atexit#atexit.register) + [(in module codecs)](library/codecs#codecs.register) + [(in module faulthandler)](library/faulthandler#faulthandler.register) + [(in module webbrowser)](library/webbrowser#webbrowser.register) + [(multiprocessing.managers.BaseManager method)](library/multiprocessing#multiprocessing.managers.BaseManager.register) + [(select.devpoll method)](library/select#select.devpoll.register) + [(select.epoll method)](library/select#select.epoll.register) + [(select.poll method)](library/select#select.poll.register) + [(selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.register) * [register\_adapter() (in module sqlite3)](library/sqlite3#sqlite3.register_adapter) * [register\_archive\_format() (in module shutil)](library/shutil#shutil.register_archive_format) * [register\_at\_fork() (in module os)](library/os#os.register_at_fork) * [register\_converter() (in module sqlite3)](library/sqlite3#sqlite3.register_converter) * [register\_defect() (email.policy.Policy method)](library/email.policy#email.policy.Policy.register_defect) * [register\_dialect() (in module csv)](library/csv#csv.register_dialect) * [register\_error() (in module codecs)](library/codecs#codecs.register_error) * [register\_function() (xmlrpc.server.CGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_function) + [(xmlrpc.server.SimpleXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_function) * [register\_instance() (xmlrpc.server.CGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_instance) + [(xmlrpc.server.SimpleXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_instance) * [register\_introspection\_functions() (xmlrpc.server.CGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_introspection_functions) + [(xmlrpc.server.SimpleXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_introspection_functions) * [register\_multicall\_functions() (xmlrpc.server.CGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_multicall_functions) + [(xmlrpc.server.SimpleXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_multicall_functions) * [register\_namespace() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.register_namespace) * [register\_optionflag() (in module doctest)](library/doctest#doctest.register_optionflag) * [register\_shape() (in module turtle)](library/turtle#turtle.register_shape) * [register\_unpack\_format() (in module shutil)](library/shutil#shutil.register_unpack_format) * [registerDOMImplementation() (in module xml.dom)](library/xml.dom#xml.dom.registerDOMImplementation) * [registerResult() (in module unittest)](library/unittest#unittest.registerResult) * regular + [package](reference/import#index-4) * [**regular package**](glossary#term-regular-package) * relative + [import](reference/simple_stmts#index-39) + [URL](library/urllib.parse#index-0) * [relative\_to() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.relative_to) * [release() (\_thread.lock method)](library/_thread#_thread.lock.release) + [(asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.release) + [(asyncio.Lock method)](library/asyncio-sync#asyncio.Lock.release) + [(asyncio.Semaphore method)](library/asyncio-sync#asyncio.Semaphore.release) + [(in module platform)](library/platform#platform.release) + [(logging.Handler method)](library/logging#logging.Handler.release) + [(memoryview method)](library/stdtypes#memoryview.release) + [(multiprocessing.Lock method)](library/multiprocessing#multiprocessing.Lock.release) + [(multiprocessing.RLock method)](library/multiprocessing#multiprocessing.RLock.release) + [(pickle.PickleBuffer method)](library/pickle#pickle.PickleBuffer.release) + [(threading.Condition method)](library/threading#threading.Condition.release) + [(threading.Lock method)](library/threading#threading.Lock.release) + [(threading.RLock method)](library/threading#threading.RLock.release) + [(threading.Semaphore method)](library/threading#threading.Semaphore.release) * [release\_lock() (in module imp)](library/imp#imp.release_lock) * [releasebufferproc (C type)](c-api/typeobj#c.releasebufferproc) * [reload (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-reload) * [reload() (in module imp)](library/imp#imp.reload) + [(in module importlib)](library/importlib#importlib.reload) * [relpath() (in module os.path)](library/os.path#os.path.relpath) * [remainder() (decimal.Context method)](library/decimal#decimal.Context.remainder) + [(in module math)](library/math#math.remainder) * [remainder\_near() (decimal.Context method)](library/decimal#decimal.Context.remainder_near) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.remainder_near) * [RemoteDisconnected](library/http.client#http.client.RemoteDisconnected) * [remove() (array.array method)](library/array#array.array.remove) + [(collections.deque method)](library/collections#collections.deque.remove) + [(frozenset method)](library/stdtypes#frozenset.remove) + [(in module os)](library/os#os.remove) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.remove) + [(mailbox.MH method)](library/mailbox#mailbox.MH.remove) + [(sequence method)](library/stdtypes#index-22) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.remove) * [remove\_child\_handler() (asyncio.AbstractChildWatcher method)](library/asyncio-policy#asyncio.AbstractChildWatcher.remove_child_handler) * [remove\_done\_callback() (asyncio.Future method)](library/asyncio-future#asyncio.Future.remove_done_callback) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.remove_done_callback) * [remove\_flag() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.remove_flag) + [(mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.remove_flag) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.remove_flag) * [remove\_folder() (mailbox.Maildir method)](library/mailbox#mailbox.Maildir.remove_folder) + [(mailbox.MH method)](library/mailbox#mailbox.MH.remove_folder) * [remove\_header() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.remove_header) * [remove\_history\_item() (in module readline)](library/readline#readline.remove_history_item) * [remove\_label() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.remove_label) * [remove\_option() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.remove_option) + [(optparse.OptionParser method)](library/optparse#optparse.OptionParser.remove_option) * [remove\_pyc() (msilib.Directory method)](library/msilib#msilib.Directory.remove_pyc) * [remove\_reader() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.remove_reader) * [remove\_section() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.remove_section) * [remove\_sequence() (mailbox.MHMessage method)](library/mailbox#mailbox.MHMessage.remove_sequence) * [remove\_signal\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.remove_signal_handler) * [remove\_tree() (in module distutils.dir\_util)](distutils/apiref#distutils.dir_util.remove_tree) * [remove\_writer() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.remove_writer) * [removeAttribute() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.removeAttribute) * [removeAttributeNode() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.removeAttributeNode) * [removeAttributeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.removeAttributeNS) * [removeChild() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.removeChild) * [removedirs() (in module os)](library/os#os.removedirs) * [removeFilter() (logging.Handler method)](library/logging#logging.Handler.removeFilter) + [(logging.Logger method)](library/logging#logging.Logger.removeFilter) * [removeHandler() (in module unittest)](library/unittest#unittest.removeHandler) + [(logging.Logger method)](library/logging#logging.Logger.removeHandler) * [removeprefix() (bytearray method)](library/stdtypes#bytearray.removeprefix) + [(bytes method)](library/stdtypes#bytes.removeprefix) + [(str method)](library/stdtypes#str.removeprefix) * [removeResult() (in module unittest)](library/unittest#unittest.removeResult) * [removesuffix() (bytearray method)](library/stdtypes#bytearray.removesuffix) + [(bytes method)](library/stdtypes#bytes.removesuffix) + [(str method)](library/stdtypes#str.removesuffix) * [removexattr() (in module os)](library/os#os.removexattr) * [rename() (ftplib.FTP method)](library/ftplib#ftplib.FTP.rename) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.rename) + [(in module os)](library/os#os.rename) + [(pathlib.Path method)](library/pathlib#pathlib.Path.rename) * [renames (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-renames) * [renames() (in module os)](library/os#os.renames) * [reopenIfNeeded() (logging.handlers.WatchedFileHandler method)](library/logging.handlers#logging.handlers.WatchedFileHandler.reopenIfNeeded) * [reorganize() (dbm.gnu.gdbm method)](library/dbm#dbm.gnu.gdbm.reorganize) * [repeat() (in module itertools)](library/itertools#itertools.repeat) + [(in module timeit)](library/timeit#timeit.repeat) + [(timeit.Timer method)](library/timeit#timeit.Timer.repeat) * repetition + [operation](library/stdtypes#index-19) * replace + [error handler's name](library/codecs#index-1) * [replace() (bytearray method)](library/stdtypes#bytearray.replace) + [(bytes method)](library/stdtypes#bytes.replace) + [(curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.replace) + [(datetime.date method)](library/datetime#datetime.date.replace) + [(datetime.datetime method)](library/datetime#datetime.datetime.replace) + [(datetime.time method)](library/datetime#datetime.time.replace) + [(in module dataclasses)](library/dataclasses#dataclasses.replace) + [(in module os)](library/os#os.replace) + [(inspect.Parameter method)](library/inspect#inspect.Parameter.replace) + [(inspect.Signature method)](library/inspect#inspect.Signature.replace) + [(pathlib.Path method)](library/pathlib#pathlib.Path.replace) + [(str method)](library/stdtypes#str.replace) + [(types.CodeType method)](library/types#types.CodeType.replace) * [replace\_errors() (in module codecs)](library/codecs#codecs.replace_errors) * [replace\_header() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.replace_header) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.replace_header) * [replace\_history\_item() (in module readline)](library/readline#readline.replace_history_item) * [replace\_whitespace (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.replace_whitespace) * [replaceChild() (xml.dom.Node method)](library/xml.dom#xml.dom.Node.replaceChild) * [ReplacePackage() (in module modulefinder)](library/modulefinder#modulefinder.ReplacePackage) * [report() (filecmp.dircmp method)](library/filecmp#filecmp.dircmp.report) + [(modulefinder.ModuleFinder method)](library/modulefinder#modulefinder.ModuleFinder.report) * [REPORT\_CDIFF (in module doctest)](library/doctest#doctest.REPORT_CDIFF) * [report\_failure() (doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.report_failure) * [report\_full\_closure() (filecmp.dircmp method)](library/filecmp#filecmp.dircmp.report_full_closure) * [REPORT\_NDIFF (in module doctest)](library/doctest#doctest.REPORT_NDIFF) * [REPORT\_ONLY\_FIRST\_FAILURE (in module doctest)](library/doctest#doctest.REPORT_ONLY_FIRST_FAILURE) * [report\_partial\_closure() (filecmp.dircmp method)](library/filecmp#filecmp.dircmp.report_partial_closure) * [report\_start() (doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.report_start) * [report\_success() (doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.report_success) * [REPORT\_UDIFF (in module doctest)](library/doctest#doctest.REPORT_UDIFF) * [report\_unexpected\_exception() (doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.report_unexpected_exception) * [REPORTING\_FLAGS (in module doctest)](library/doctest#doctest.REPORTING_FLAGS) * repr + [built-in function](c-api/object#index-0), [[1]](c-api/typeobj#index-1), [[2]](extending/newtypes#index-3), [[3]](reference/simple_stmts#index-3) * [repr (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-repr) * [Repr (class in reprlib)](library/reprlib#reprlib.Repr) * [repr() (built-in function)](library/functions#repr) + [\_\_repr\_\_() (object method)](reference/datamodel#index-71) * [repr() (in module reprlib)](library/reprlib#reprlib.repr) + [(reprlib.Repr method)](library/reprlib#reprlib.Repr.repr) * [repr1() (reprlib.Repr method)](library/reprlib#reprlib.Repr.repr1) * representation + [integer](reference/datamodel#index-12) * [reprfunc (C type)](c-api/typeobj#c.reprfunc) * [reprlib (module)](library/reprlib#module-reprlib) * [Request (class in urllib.request)](library/urllib.request#urllib.request.Request) * [request() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.request) * [request\_queue\_size (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.request_queue_size) * [request\_rate() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.request_rate) * [request\_uri() (in module wsgiref.util)](library/wsgiref#wsgiref.util.request_uri) * [request\_version (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.request_version) * [RequestHandlerClass (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.RequestHandlerClass) * [requestline (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.requestline) * [requires() (in module test.support)](library/test#test.support.requires) * [requires\_bz2() (in module test.support)](library/test#test.support.requires_bz2) * [requires\_docstrings() (in module test.support)](library/test#test.support.requires_docstrings) * [requires\_freebsd\_version() (in module test.support)](library/test#test.support.requires_freebsd_version) * [requires\_gzip() (in module test.support)](library/test#test.support.requires_gzip) * [requires\_IEEE\_754() (in module test.support)](library/test#test.support.requires_IEEE_754) * [requires\_linux\_version() (in module test.support)](library/test#test.support.requires_linux_version) | * [requires\_lzma() (in module test.support)](library/test#test.support.requires_lzma) * [requires\_mac\_version() (in module test.support)](library/test#test.support.requires_mac_version) * [requires\_resource() (in module test.support)](library/test#test.support.requires_resource) * [requires\_zlib() (in module test.support)](library/test#test.support.requires_zlib) * [RERAISE (opcode)](library/dis#opcode-RERAISE) * [reserved (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.reserved) * [reserved word](reference/lexical_analysis#index-13) * [RESERVED\_FUTURE (in module uuid)](library/uuid#uuid.RESERVED_FUTURE) * [RESERVED\_MICROSOFT (in module uuid)](library/uuid#uuid.RESERVED_MICROSOFT) * [RESERVED\_NCS (in module uuid)](library/uuid#uuid.RESERVED_NCS) * [reset() (bdb.Bdb method)](library/bdb#bdb.Bdb.reset) + [(codecs.IncrementalDecoder method)](library/codecs#codecs.IncrementalDecoder.reset) + [(codecs.IncrementalEncoder method)](library/codecs#codecs.IncrementalEncoder.reset) + [(codecs.StreamReader method)](library/codecs#codecs.StreamReader.reset) + [(codecs.StreamWriter method)](library/codecs#codecs.StreamWriter.reset) + [(contextvars.ContextVar method)](library/contextvars#contextvars.ContextVar.reset) + [(html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.reset) + [(in module turtle)](library/turtle#turtle.reset) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.reset) + [(pipes.Template method)](library/pipes#pipes.Template.reset) + [(threading.Barrier method)](library/threading#threading.Barrier.reset) + [(xdrlib.Packer method)](library/xdrlib#xdrlib.Packer.reset) + [(xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.reset) + [(xml.dom.pulldom.DOMEventStream method)](library/xml.dom.pulldom#xml.dom.pulldom.DOMEventStream.reset) + [(xml.sax.xmlreader.IncrementalParser method)](library/xml.sax.reader#xml.sax.xmlreader.IncrementalParser.reset) * [reset\_mock() (unittest.mock.AsyncMock method)](library/unittest.mock#unittest.mock.AsyncMock.reset_mock) + [(unittest.mock.Mock method)](library/unittest.mock#unittest.mock.Mock.reset_mock) * [reset\_peak() (in module tracemalloc)](library/tracemalloc#tracemalloc.reset_peak) * [reset\_prog\_mode() (in module curses)](library/curses#curses.reset_prog_mode) * [reset\_shell\_mode() (in module curses)](library/curses#curses.reset_shell_mode) * [reset\_tzpath() (in module zoneinfo)](library/zoneinfo#zoneinfo.reset_tzpath) * [resetbuffer() (code.InteractiveConsole method)](library/code#code.InteractiveConsole.resetbuffer) * [resetlocale() (in module locale)](library/locale#locale.resetlocale) * [resetscreen() (in module turtle)](library/turtle#turtle.resetscreen) * [resetty() (in module curses)](library/curses#curses.resetty) * [resetwarnings() (in module warnings)](library/warnings#warnings.resetwarnings) * [resize() (curses.window method)](library/curses#curses.window.resize) + [(in module ctypes)](library/ctypes#ctypes.resize) + [(mmap.mmap method)](library/mmap#mmap.mmap.resize) * [resize\_term() (in module curses)](library/curses#curses.resize_term) * [resizemode() (in module turtle)](library/turtle#turtle.resizemode) * [resizeterm() (in module curses)](library/curses#curses.resizeterm) * [resolution (datetime.date attribute)](library/datetime#datetime.date.resolution) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.resolution) + [(datetime.time attribute)](library/datetime#datetime.time.resolution) + [(datetime.timedelta attribute)](library/datetime#datetime.timedelta.resolution) * [resolve() (pathlib.Path method)](library/pathlib#pathlib.Path.resolve) * [resolve\_bases() (in module types)](library/types#types.resolve_bases) * [resolve\_name() (in module importlib.util)](library/importlib#importlib.util.resolve_name) + [(in module pkgutil)](library/pkgutil#pkgutil.resolve_name) * [resolveEntity() (xml.sax.handler.EntityResolver method)](library/xml.sax.handler#xml.sax.handler.EntityResolver.resolveEntity) * [Resource (in module importlib.resources)](library/importlib#importlib.resources.Resource) * [resource (module)](library/resource#module-resource) * [resource\_path() (importlib.abc.ResourceReader method)](library/importlib#importlib.abc.ResourceReader.resource_path) * [ResourceDenied](library/test#test.support.ResourceDenied) * [ResourceLoader (class in importlib.abc)](library/importlib#importlib.abc.ResourceLoader) * [ResourceReader (class in importlib.abc)](library/importlib#importlib.abc.ResourceReader) * [ResourceWarning](library/exceptions#ResourceWarning) * [response (nntplib.NNTPError attribute)](library/nntplib#nntplib.NNTPError.response) * [response() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.response) * [ResponseNotReady](library/http.client#http.client.ResponseNotReady) * [responses (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.responses) + [(in module http.client)](library/http.client#http.client.responses) * [restart (pdb command)](library/pdb#pdbcommand-restart) * [restore() (in module difflib)](library/difflib#difflib.restore) * [RESTRICTED](extending/newtypes#index-4) * restricted + [execution](reference/executionmodel#index-11) * [restype (ctypes.\_FuncPtr attribute)](library/ctypes#ctypes._FuncPtr.restype) * [result() (asyncio.Future method)](library/asyncio-future#asyncio.Future.result) + [(asyncio.Task method)](library/asyncio-task#asyncio.Task.result) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.result) * [results() (trace.Trace method)](library/trace#trace.Trace.results) * [resume\_reading() (asyncio.ReadTransport method)](library/asyncio-protocol#asyncio.ReadTransport.resume_reading) * [resume\_writing() (asyncio.BaseProtocol method)](library/asyncio-protocol#asyncio.BaseProtocol.resume_writing) * [retr() (poplib.POP3 method)](library/poplib#poplib.POP3.retr) * [retrbinary() (ftplib.FTP method)](library/ftplib#ftplib.FTP.retrbinary) * [retrieve() (urllib.request.URLopener method)](library/urllib.request#urllib.request.URLopener.retrieve) * [retrlines() (ftplib.FTP method)](library/ftplib#ftplib.FTP.retrlines) * return + [statement](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [**[2]**](reference/simple_stmts#index-24) * [Return (class in ast)](library/ast#ast.Return) * [return (pdb command)](library/pdb#pdbcommand-return) * [return\_annotation (inspect.Signature attribute)](library/inspect#inspect.Signature.return_annotation) * [return\_ok() (http.cookiejar.CookiePolicy method)](library/http.cookiejar#http.cookiejar.CookiePolicy.return_ok) * [RETURN\_VALUE (opcode)](library/dis#opcode-RETURN_VALUE) * [return\_value (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.return_value) * [returncode (asyncio.subprocess.Process attribute)](library/asyncio-subprocess#asyncio.subprocess.Process.returncode) + [(subprocess.CalledProcessError attribute)](library/subprocess#subprocess.CalledProcessError.returncode) + [(subprocess.CompletedProcess attribute)](library/subprocess#subprocess.CompletedProcess.returncode) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.returncode) * [retval (pdb command)](library/pdb#pdbcommand-retval) * [reverse() (array.array method)](library/array#array.array.reverse) + [(collections.deque method)](library/collections#collections.deque.reverse) + [(in module audioop)](library/audioop#audioop.reverse) + [(sequence method)](library/stdtypes#index-22) * [reverse\_order() (pstats.Stats method)](library/profile#pstats.Stats.reverse_order) * [reverse\_pointer (ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.reverse_pointer) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.reverse_pointer) * [reversed() (built-in function)](library/functions#reversed) * [Reversible (class in collections.abc)](library/collections.abc#collections.abc.Reversible) + [(class in typing)](library/typing#typing.Reversible) * [revert() (http.cookiejar.FileCookieJar method)](library/http.cookiejar#http.cookiejar.FileCookieJar.revert) * [rewind() (aifc.aifc method)](library/aifc#aifc.aifc.rewind) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.rewind) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.rewind) * RFC + [RFC 1014](library/xdrlib#index-2), [[1]](library/xdrlib#index-3) + [RFC 1123](library/time#index-21) + [RFC 1321](library/hashlib#index-1) + [RFC 1422](library/ssl#index-19), [[1]](library/ssl#index-22) + [RFC 1521](library/base64#index-9), [[1]](library/quopri#index-1), [[2]](library/quopri#index-3) + [RFC 1522](library/binascii#index-2), [[1]](library/quopri#index-2), [[2]](library/quopri#index-4) + [RFC 1524](library/mailcap#index-1), [[1]](library/mailcap#index-2) + [RFC 1730](library/imaplib#index-2) + [RFC 1738](library/urllib.parse#index-12) + [RFC 1750](library/ssl#index-4) + [RFC 1766](library/locale#index-4), [[1]](library/locale#index-5) + [RFC 1808](library/urllib.parse#index-1), [[1]](library/urllib.parse#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-45) + [RFC 1832](library/xdrlib#index-4), [[1]](library/xdrlib#index-5) + [RFC 1869](library/smtplib#index-2), [[1]](library/smtplib#index-5) + [RFC 1870](library/smtpd#index-2), [[1]](library/smtpd#index-9), [[2]](https://docs.python.org/3.9/whatsnew/3.3.html#index-27) + [RFC 1939](library/poplib#index-1), [[1]](library/poplib#index-2) + [RFC 2033](https://docs.python.org/3.9/whatsnew/2.6.html#index-22) + [RFC 2045](library/base64#index-4), [[1]](library/base64#index-5), [[2]](library/base64#index-7), [[3]](library/base64#index-8), [[4]](library/email.compat32-message#index-4), [[5]](library/email.compat32-message#index-5), [[6]](library/email.compat32-message#index-6), [[7]](library/email.compat32-message#index-9), [[8]](library/email.header#index-4), [[9]](library/email.headerregistry#index-10), [[10]](library/email.headerregistry#index-9), [[11]](library/email#index-3), [[12]](library/email.message#index-6), [[13]](library/email.message#index-7), [[14]](library/email.message#index-8) + [RFC 2045#section-6.8](library/xmlrpc.client#index-0) + [RFC 2046](library/email.contentmanager#index-0), [[1]](library/email.header#index-5), [[2]](library/email#index-4) + [RFC 2047](library/email.header#index-11), [[1]](library/email.header#index-13), [[2]](library/email.header#index-6), [[3]](library/email.header#index-8), [[4]](library/email.headerregistry#index-1), [[5]](library/email.headerregistry#index-4), [[6]](library/email.headerregistry#index-6), [[7]](library/email#index-5), [[8]](library/email.policy#index-3), [[9]](library/email.policy#index-4), [[10]](library/email.utils#index-1), [[11]](https://docs.python.org/3.9/whatsnew/3.2.html#index-11), [[12]](https://docs.python.org/3.9/whatsnew/3.2.html#index-8) + [RFC 2060](library/imaplib#index-1), [[1]](library/imaplib#index-7) + [RFC 2068](library/http.cookies#index-1) + [RFC 2104](library/hmac#index-0), [[1]](https://docs.python.org/3.9/whatsnew/2.2.html#index-17) + [RFC 2109](library/http.cookiejar#index-1), [[1]](library/http.cookiejar#index-15), [[2]](library/http.cookiejar#index-21), [[3]](library/http.cookiejar#index-23), [[4]](library/http.cookiejar#index-24), [[5]](library/http.cookiejar#index-3), [[6]](library/http.cookiejar#index-4), [[7]](library/http.cookiejar#index-6), [[8]](library/http.cookies#index-0), [[9]](library/http.cookies#index-2), [[10]](library/http.cookies#index-3), [[11]](library/http.cookies#index-4), [[12]](library/http.cookies#index-5), [[13]](library/http.cookies#index-6), [[14]](library/http.cookies#index-7) + [RFC 2183](library/email.compat32-message#index-11), [[1]](library/email#index-6), [[2]](library/email.message#index-10) + [RFC 2231](library/email.compat32-message#index-10), [[1]](library/email.compat32-message#index-2), [[2]](library/email.compat32-message#index-3), [[3]](library/email.compat32-message#index-7), [[4]](library/email.compat32-message#index-8), [[5]](library/email.header#index-7), [[6]](library/email#index-7), [[7]](library/email.message#index-4), [[8]](library/email.message#index-5), [[9]](library/email.message#index-9), [[10]](library/email.utils#index-5), [[11]](library/email.utils#index-6), [[12]](library/email.utils#index-7), [[13]](library/email.utils#index-8), [[14]](library/email.utils#index-9) + [RFC 2295](library/http#index-58) + [RFC 2324](library/http#index-41) + [RFC 2342](library/imaplib#index-6), [[1]](https://docs.python.org/3.9/whatsnew/2.2.html#index-19) + [RFC 2368](library/urllib.parse#index-10) + [RFC 2373](library/ipaddress#index-1), [[1]](library/ipaddress#index-3), [[2]](library/ipaddress#index-5) + [RFC 2396](library/urllib.parse#index-3), [[1]](library/urllib.parse#index-5), [[2]](library/urllib.parse#index-9), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-46), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-34) + [RFC 2397](library/urllib.request#index-8) + [RFC 2449](library/poplib#index-4) + [RFC 2487](https://docs.python.org/3.9/whatsnew/2.2.html#index-18) + [RFC 2518](library/http#index-3) + [RFC 2595](library/poplib#index-3), [[1]](library/poplib#index-6) + [RFC 2616](howto/urllib2#index-0), [[1]](howto/urllib2#index-1), [[2]](howto/urllib2#index-2), [[3]](library/urllib.error#index-0), [[4]](library/urllib.request#index-10), [[5]](library/urllib.request#index-6), [[6]](library/urllib.request#index-7), [[7]](library/wsgiref#index-10), [[8]](library/wsgiref#index-5), [[9]](https://docs.python.org/3.9/whatsnew/3.2.html#index-7) + [RFC 2640](library/ftplib#index-2), [[1]](library/ftplib#index-3), [[2]](library/ftplib#index-5), [[3]](https://docs.python.org/3.9/whatsnew/3.9.html#index-22), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-30) + [RFC 2732](library/urllib.parse#index-8), [[1]](https://docs.python.org/3.9/whatsnew/2.7.html#index-11), [[2]](https://docs.python.org/3.9/whatsnew/3.2.html#index-13) + [RFC 2774](library/http#index-61) + [RFC 2818](library/ssl#index-5), [[1]](https://docs.python.org/3.9/whatsnew/3.2.html#index-12) + [RFC 2821](library/email#index-0) + [RFC 2822](library/email.compat32-message#index-1), [[1]](library/email.header#index-0), [[2]](library/email.header#index-10), [[3]](library/email.header#index-12), [[4]](library/email.header#index-2), [[5]](library/email.header#index-3), [[6]](library/email.header#index-9), [[7]](library/email.utils#index-0), [[8]](library/email.utils#index-10), [[9]](library/email.utils#index-2), [[10]](library/email.utils#index-3), [[11]](library/email.utils#index-4), [[12]](library/http.client#index-2), [[13]](library/http.server#index-2), [[14]](library/mailbox#index-0), [[15]](library/time#index-10), [[16]](library/time#index-22), [[17]](tutorial/stdlib#index-1), [[18]](https://docs.python.org/3.9/whatsnew/2.2.html#index-20) + [RFC 2964](library/http.cookiejar#index-10) + [RFC 2965](library/http.cookiejar#index-0), [[1]](library/http.cookiejar#index-11), [[2]](library/http.cookiejar#index-12), [[3]](library/http.cookiejar#index-13), [[4]](library/http.cookiejar#index-14), [[5]](library/http.cookiejar#index-16), [[6]](library/http.cookiejar#index-17), [[7]](library/http.cookiejar#index-18), [[8]](library/http.cookiejar#index-19), [[9]](library/http.cookiejar#index-2), [[10]](library/http.cookiejar#index-20), [[11]](library/http.cookiejar#index-22), [[12]](library/http.cookiejar#index-25), [[13]](library/http.cookiejar#index-5), [[14]](library/http.cookiejar#index-7), [[15]](library/http.cookiejar#index-8), [[16]](library/http.cookiejar#index-9), [[17]](library/urllib.request#index-2), [[18]](library/urllib.request#index-3), [[19]](library/urllib.request#index-5) + [RFC 2980](library/nntplib#index-4), [[1]](library/nntplib#index-9) + [RFC 3056](library/ipaddress#index-12) + [RFC 3171](library/ipaddress#index-0) + [RFC 3207](https://docs.python.org/3.9/whatsnew/2.6.html#index-23) + [RFC 3229](library/http#index-14) + [RFC 3280](library/ssl#index-13) + [RFC 3330](library/ipaddress#index-4) + [RFC 3339](howto/logging#index-0) + [RFC 3454](library/stringprep#index-0), [[1]](library/stringprep#index-1) + [RFC 3490](library/codecs#index-13), [[1]](library/codecs#index-14), [[2]](library/codecs#index-6), [[3]](library/codecs#index-8) + [RFC 3490#section-3.1](library/codecs#index-12) + [RFC 3492](library/codecs#index-7), [[1]](library/codecs#index-9) + [RFC 3493](library/socket#index-15) + [RFC 3501](library/imaplib#index-8) + [RFC 3542](library/socket#index-3), [[1]](https://docs.python.org/3.9/whatsnew/changelog.html#index-71) + [RFC 3548](library/base64#index-1), [[1]](library/base64#index-2), [[2]](library/base64#index-3), [[3]](library/base64#index-6), [[4]](library/binascii#index-1), [[5]](https://docs.python.org/3.9/whatsnew/2.4.html#index-18) + [RFC 3659](library/ftplib#index-6) + [RFC 3879](library/ipaddress#index-9) + [RFC 3927](library/ipaddress#index-6) + [RFC 3977](library/nntplib#index-10), [[1]](library/nntplib#index-2), [[2]](library/nntplib#index-6), [[3]](library/nntplib#index-7), [[4]](library/nntplib#index-8) + [RFC 3986](library/http.server#index-1), [[1]](library/urllib.parse#index-2), [[2]](library/urllib.parse#index-4), [[3]](library/urllib.parse#index-6), [[4]](library/urllib.parse#index-7), [[5]](https://docs.python.org/3.9/whatsnew/2.7.html#index-10), [[6]](https://docs.python.org/3.9/whatsnew/2.7.html#index-13), [[7]](https://docs.python.org/3.9/whatsnew/3.5.html#index-44), [[8]](https://docs.python.org/3.9/whatsnew/3.7.html#index-35), [[9]](https://docs.python.org/3.9/whatsnew/3.9.html#index-28) + [RFC 4007](library/ipaddress#index-11), [[1]](library/ipaddress#index-8) + [RFC 4086](library/ssl#index-23) + [RFC 4122](library/uuid#index-0), [[1]](library/uuid#index-1), [[2]](library/uuid#index-10), [[3]](library/uuid#index-11), [[4]](library/uuid#index-2), [[5]](library/uuid#index-3), [[6]](library/uuid#index-4), [[7]](https://docs.python.org/3.9/whatsnew/2.5.html#index-22), [[8]](https://docs.python.org/3.9/whatsnew/2.5.html#index-23) + [RFC 4180](library/csv#index-1) + [RFC 4193](library/ipaddress#index-10) + [RFC 4217](library/ftplib#index-4) + [RFC 4291](library/ipaddress#index-7) + [RFC 4380](library/ipaddress#index-13) + [RFC 4627](library/json#index-1), [[1]](library/json#index-3) + [RFC 4642](library/nntplib#index-5) + [RFC 4918](library/http#index-12), [[1]](library/http#index-43), [[2]](library/http#index-44), [[3]](library/http#index-45), [[4]](library/http#index-59) + [RFC 4954](library/smtplib#index-7), [[1]](library/smtplib#index-8) + [RFC 5161](library/imaplib#index-3), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-35) + [RFC 5246](library/ssl#index-12), [[1]](library/ssl#index-25) + [RFC 5280](library/ssl#index-24), [[1]](library/ssl#index-6), [[2]](library/ssl#index-9), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-43), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-53) + [RFC 5321](library/email.headerregistry#index-13), [[1]](library/smtpd#index-1), [[2]](library/smtpd#index-6), [[3]](library/smtpd#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.3.html#index-26) + [RFC 5322](library/email.compat32-message#index-0), [[1]](library/email.errors#index-0), [[2]](library/email.generator#index-0), [[3]](library/email.generator#index-1), [[4]](library/email.headerregistry#index-0), [[5]](library/email.headerregistry#index-11), [[6]](library/email.headerregistry#index-12), [[7]](library/email.headerregistry#index-14), [[8]](library/email.headerregistry#index-2), [[9]](library/email.headerregistry#index-3), [[10]](library/email.headerregistry#index-5), [[11]](library/email.headerregistry#index-7), [[12]](library/email.headerregistry#index-8), [[13]](library/email#index-1), [[14]](library/email.message#index-0), [[15]](library/email.message#index-2), [[16]](library/email.parser#index-0), [[17]](library/email.policy#index-0), [[18]](library/email.policy#index-1), [[19]](library/email.policy#index-2), [[20]](library/email.policy#index-5), [[21]](library/email.policy#index-6), [[22]](library/email.policy#index-9), [[23]](library/smtplib#index-11) + [RFC 5424](howto/logging-cookbook#index-0), [[1]](howto/logging-cookbook#index-2), [[2]](howto/logging-cookbook#index-3), [[3]](library/logging.handlers#index-0) + [RFC 5424#section-6](howto/logging-cookbook#index-1) + [RFC 5735](library/ipaddress#index-2) + [RFC 5842](library/http#index-13), [[1]](library/http#index-60) + [RFC 5891](library/codecs#index-10) + [RFC 5895](library/codecs#index-11) + [RFC 5929](library/ssl#index-14) + [RFC 6066](library/ssl#index-11), [[1]](library/ssl#index-16), [[2]](library/ssl#index-26) + [RFC 6125](library/ssl#index-7), [[1]](library/ssl#index-8) + [RFC 6152](library/smtpd#index-5), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-39) + [RFC 6531](library/email.message#index-3), [[1]](library/email.policy#index-8), [[2]](library/smtpd#index-3), [[3]](library/smtpd#index-4), [[4]](library/smtpd#index-8), [[5]](library/smtplib#index-3), [[6]](https://docs.python.org/3.9/whatsnew/3.5.html#index-34), [[7]](https://docs.python.org/3.9/whatsnew/3.5.html#index-40), [[8]](https://docs.python.org/3.9/whatsnew/3.5.html#index-41) + [RFC 6532](library/email#index-2), [[1]](library/email.message#index-1), [[2]](library/email.parser#index-1), [[3]](library/email.policy#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.5.html#index-33) + [RFC 6585](library/http#index-48), [[1]](library/http#index-49), [[2]](library/http#index-50), [[3]](library/http#index-62) + [RFC 6855](library/imaplib#index-4), [[1]](library/imaplib#index-5), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-36), [[3]](https://docs.python.org/3.9/whatsnew/3.5.html#index-37) + [RFC 6856](library/poplib#index-5), [[1]](https://docs.python.org/3.9/whatsnew/3.5.html#index-38) + [RFC 7159](library/json#index-0), [[1]](library/json#index-2), [[2]](library/json#index-4) + [RFC 7230](library/http.client#index-4), [[1]](library/urllib.request#index-1) + [RFC 7231](library/http#index-1), [[1]](library/http#index-10), [[2]](library/http#index-15), [[3]](library/http#index-16), [[4]](library/http#index-17), [[5]](library/http#index-18), [[6]](library/http#index-2), [[7]](library/http#index-20), [[8]](library/http#index-21), [[9]](library/http#index-23), [[10]](library/http#index-25), [[11]](library/http#index-26), [[12]](library/http#index-27), [[13]](library/http#index-28), [[14]](library/http#index-29), [[15]](library/http#index-31), [[16]](library/http#index-32), [[17]](library/http#index-33), [[18]](library/http#index-34), [[19]](library/http#index-36), [[20]](library/http#index-37), [[21]](library/http#index-38), [[22]](library/http#index-40), [[23]](library/http#index-47), [[24]](library/http#index-5), [[25]](library/http#index-52), [[26]](library/http#index-53), [[27]](library/http#index-54), [[28]](library/http#index-55), [[29]](library/http#index-56), [[30]](library/http#index-57), [[31]](library/http#index-6), [[32]](library/http#index-7), [[33]](library/http#index-8), [[34]](library/http#index-9) + [RFC 7232](library/http#index-19), [[1]](library/http#index-35) + [RFC 7233](library/http#index-11), [[1]](library/http#index-39) + [RFC 7235](library/http#index-24), [[1]](library/http#index-30) + [RFC 7238](library/http#index-22) + [RFC 7301](library/ssl#index-10), [[1]](library/ssl#index-15), [[2]](https://docs.python.org/3.9/whatsnew/3.5.html#index-42) + [RFC 7525](library/ssl#index-27) + [RFC 7540](library/http#index-42) + [RFC 7693](library/hashlib#index-5) + [RFC 7725](library/http#index-51) + [RFC 7914](library/hashlib#index-3) + [RFC 821](library/smtplib#index-1), [[1]](library/smtplib#index-4) + [RFC 822](distutils/apiref#index-6), [[1]](library/email.examples#index-0), [[2]](library/email.header#index-1), [[3]](library/gettext#index-9), [[4]](library/http.client#index-3), [[5]](library/smtplib#index-10), [[6]](library/smtplib#index-12), [[7]](library/smtplib#index-6), [[8]](library/smtplib#index-9), [[9]](library/time#index-19), [[10]](library/time#index-20), [[11]](https://docs.python.org/3.9/whatsnew/2.2.html#index-21) + [RFC 8297](library/http#index-4) + [RFC 8305](library/asyncio-eventloop#index-3), [[1]](library/asyncio-eventloop#index-4) + [RFC 8470](library/http#index-46) + [RFC 854](library/telnetlib#index-2), [[1]](library/telnetlib#index-3) + [RFC 959](library/ftplib#index-1) + [RFC 977](library/nntplib#index-3) * [rfc2109 (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.rfc2109) * [rfc2109\_as\_netscape (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.rfc2109_as_netscape) * [rfc2965 (http.cookiejar.CookiePolicy attribute)](library/http.cookiejar#http.cookiejar.CookiePolicy.rfc2965) * [rfc822\_escape() (in module distutils.util)](distutils/apiref#distutils.util.rfc822_escape) * [RFC\_4122 (in module uuid)](library/uuid#uuid.RFC_4122) * [rfile (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.rfile) * [rfind() (bytearray method)](library/stdtypes#bytearray.rfind) + [(bytes method)](library/stdtypes#bytes.rfind) + [(mmap.mmap method)](library/mmap#mmap.mmap.rfind) + [(str method)](library/stdtypes#str.rfind) * [rgb\_to\_hls() (in module colorsys)](library/colorsys#colorsys.rgb_to_hls) * [rgb\_to\_hsv() (in module colorsys)](library/colorsys#colorsys.rgb_to_hsv) * [rgb\_to\_yiq() (in module colorsys)](library/colorsys#colorsys.rgb_to_yiq) * [rglob() (pathlib.Path method)](library/pathlib#pathlib.Path.rglob) * [richcmpfunc (C type)](c-api/typeobj#c.richcmpfunc) * [right (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.right) * [right() (in module turtle)](library/turtle#turtle.right) * [right\_list (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.right_list) * [right\_only (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.right_only) * [RIGHTSHIFT (in module token)](library/token#token.RIGHTSHIFT) * [RIGHTSHIFTEQUAL (in module token)](library/token#token.RIGHTSHIFTEQUAL) * [rindex() (bytearray method)](library/stdtypes#bytearray.rindex) + [(bytes method)](library/stdtypes#bytes.rindex) + [(str method)](library/stdtypes#str.rindex) * [rjust() (bytearray method)](library/stdtypes#bytearray.rjust) + [(bytes method)](library/stdtypes#bytes.rjust) + [(str method)](library/stdtypes#str.rjust) * [rlcompleter (module)](library/rlcompleter#module-rlcompleter) * [rlecode\_hqx() (in module binascii)](library/binascii#binascii.rlecode_hqx) * [rledecode\_hqx() (in module binascii)](library/binascii#binascii.rledecode_hqx) * [RLIM\_INFINITY (in module resource)](library/resource#resource.RLIM_INFINITY) * [RLIMIT\_AS (in module resource)](library/resource#resource.RLIMIT_AS) * [RLIMIT\_CORE (in module resource)](library/resource#resource.RLIMIT_CORE) * [RLIMIT\_CPU (in module resource)](library/resource#resource.RLIMIT_CPU) * [RLIMIT\_DATA (in module resource)](library/resource#resource.RLIMIT_DATA) * [RLIMIT\_FSIZE (in module resource)](library/resource#resource.RLIMIT_FSIZE) * [RLIMIT\_MEMLOCK (in module resource)](library/resource#resource.RLIMIT_MEMLOCK) * [RLIMIT\_MSGQUEUE (in module resource)](library/resource#resource.RLIMIT_MSGQUEUE) * [RLIMIT\_NICE (in module resource)](library/resource#resource.RLIMIT_NICE) * [RLIMIT\_NOFILE (in module resource)](library/resource#resource.RLIMIT_NOFILE) * [RLIMIT\_NPROC (in module resource)](library/resource#resource.RLIMIT_NPROC) * [RLIMIT\_NPTS (in module resource)](library/resource#resource.RLIMIT_NPTS) * [RLIMIT\_OFILE (in module resource)](library/resource#resource.RLIMIT_OFILE) * [RLIMIT\_RSS (in module resource)](library/resource#resource.RLIMIT_RSS) * [RLIMIT\_RTPRIO (in module resource)](library/resource#resource.RLIMIT_RTPRIO) * [RLIMIT\_RTTIME (in module resource)](library/resource#resource.RLIMIT_RTTIME) * [RLIMIT\_SBSIZE (in module resource)](library/resource#resource.RLIMIT_SBSIZE) * [RLIMIT\_SIGPENDING (in module resource)](library/resource#resource.RLIMIT_SIGPENDING) * [RLIMIT\_STACK (in module resource)](library/resource#resource.RLIMIT_STACK) * [RLIMIT\_SWAP (in module resource)](library/resource#resource.RLIMIT_SWAP) * [RLIMIT\_VMEM (in module resource)](library/resource#resource.RLIMIT_VMEM) * [RLock (class in multiprocessing)](library/multiprocessing#multiprocessing.RLock) + [(class in threading)](library/threading#threading.RLock) * [RLock() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.RLock) * [rmd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.rmd) * [rmdir() (in module os)](library/os#os.rmdir) + [(in module test.support)](library/test#test.support.rmdir) + [(pathlib.Path method)](library/pathlib#pathlib.Path.rmdir) * [RMFF](library/chunk#index-0) * [rms() (in module audioop)](library/audioop#audioop.rms) * [rmtree() (in module shutil)](library/shutil#shutil.rmtree) + [(in module test.support)](library/test#test.support.rmtree) * [RobotFileParser (class in urllib.robotparser)](library/urllib.robotparser#urllib.robotparser.RobotFileParser) * [robots.txt](library/urllib.robotparser#index-0) * [rollback() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.rollback) * [ROMAN (in module tkinter.font)](library/tkinter.font#tkinter.font.ROMAN) * [ROT\_FOUR (opcode)](library/dis#opcode-ROT_FOUR) * [ROT\_THREE (opcode)](library/dis#opcode-ROT_THREE) * [ROT\_TWO (opcode)](library/dis#opcode-ROT_TWO) * [rotate() (collections.deque method)](library/collections#collections.deque.rotate) + [(decimal.Context method)](library/decimal#decimal.Context.rotate) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.rotate) + [(logging.handlers.BaseRotatingHandler method)](library/logging.handlers#logging.handlers.BaseRotatingHandler.rotate) * [RotatingFileHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.RotatingFileHandler) * [rotation\_filename() (logging.handlers.BaseRotatingHandler method)](library/logging.handlers#logging.handlers.BaseRotatingHandler.rotation_filename) * [rotator (logging.handlers.BaseRotatingHandler attribute)](library/logging.handlers#logging.handlers.BaseRotatingHandler.rotator) * round + [built-in function](reference/datamodel#index-101) * [round() (built-in function)](library/functions#round) * [ROUND\_05UP (in module decimal)](library/decimal#decimal.ROUND_05UP) * [ROUND\_CEILING (in module decimal)](library/decimal#decimal.ROUND_CEILING) * [ROUND\_DOWN (in module decimal)](library/decimal#decimal.ROUND_DOWN) * [ROUND\_FLOOR (in module decimal)](library/decimal#decimal.ROUND_FLOOR) * [ROUND\_HALF\_DOWN (in module decimal)](library/decimal#decimal.ROUND_HALF_DOWN) * [ROUND\_HALF\_EVEN (in module decimal)](library/decimal#decimal.ROUND_HALF_EVEN) * [ROUND\_HALF\_UP (in module decimal)](library/decimal#decimal.ROUND_HALF_UP) * [ROUND\_UP (in module decimal)](library/decimal#decimal.ROUND_UP) * [Rounded (class in decimal)](library/decimal#decimal.Rounded) * [Row (class in sqlite3)](library/sqlite3#sqlite3.Row) * [row\_factory (sqlite3.Connection attribute)](library/sqlite3#sqlite3.Connection.row_factory) * [rowcount (sqlite3.Cursor attribute)](library/sqlite3#sqlite3.Cursor.rowcount) * [RPAR (in module token)](library/token#token.RPAR) * [rpartition() (bytearray method)](library/stdtypes#bytearray.rpartition) + [(bytes method)](library/stdtypes#bytes.rpartition) + [(str method)](library/stdtypes#str.rpartition) * [rpc\_paths (xmlrpc.server.SimpleXMLRPCRequestHandler attribute)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_paths) * [rpop() (poplib.POP3 method)](library/poplib#poplib.POP3.rpop) * [rset() (poplib.POP3 method)](library/poplib#poplib.POP3.rset) * [RShift (class in ast)](library/ast#ast.RShift) * [rshift() (in module operator)](library/operator#operator.rshift) * [rsplit() (bytearray method)](library/stdtypes#bytearray.rsplit) + [(bytes method)](library/stdtypes#bytes.rsplit) + [(str method)](library/stdtypes#str.rsplit) * [RSQB (in module token)](library/token#token.RSQB) * [rstrip() (bytearray method)](library/stdtypes#bytearray.rstrip) + [(bytes method)](library/stdtypes#bytes.rstrip) + [(str method)](library/stdtypes#str.rstrip) * [rt() (in module turtle)](library/turtle#turtle.rt) * [RTLD\_DEEPBIND (in module os)](library/os#os.RTLD_DEEPBIND) * [RTLD\_GLOBAL (in module os)](library/os#os.RTLD_GLOBAL) * [RTLD\_LAZY (in module os)](library/os#os.RTLD_LAZY) * [RTLD\_LOCAL (in module os)](library/os#os.RTLD_LOCAL) * [RTLD\_NODELETE (in module os)](library/os#os.RTLD_NODELETE) * [RTLD\_NOLOAD (in module os)](library/os#os.RTLD_NOLOAD) * [RTLD\_NOW (in module os)](library/os#os.RTLD_NOW) * [ruler (cmd.Cmd attribute)](library/cmd#cmd.Cmd.ruler) * [run (pdb command)](library/pdb#pdbcommand-run) * [Run script](library/idle#index-2) * [run() (bdb.Bdb method)](library/bdb#bdb.Bdb.run) + [(contextvars.Context method)](library/contextvars#contextvars.Context.run) + [(distutils.cmd.Command method)](distutils/apiref#distutils.cmd.Command.run) + [(doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.run) + [(in module asyncio)](library/asyncio-task#asyncio.run) + [(in module pdb)](library/pdb#pdb.run) + [(in module profile)](library/profile#profile.run) + [(in module subprocess)](library/subprocess#subprocess.run) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.run) + [(pdb.Pdb method)](library/pdb#pdb.Pdb.run) + [(profile.Profile method)](library/profile#profile.Profile.run) + [(sched.scheduler method)](library/sched#sched.scheduler.run) + [(test.support.BasicTestRunner method)](library/test#test.support.BasicTestRunner.run) + [(threading.Thread method)](library/threading#threading.Thread.run) + [(trace.Trace method)](library/trace#trace.Trace.run) + [(unittest.IsolatedAsyncioTestCase method)](library/unittest#unittest.IsolatedAsyncioTestCase.run) + [(unittest.TestCase method)](library/unittest#unittest.TestCase.run) + [(unittest.TestSuite method)](library/unittest#unittest.TestSuite.run) + [(unittest.TextTestRunner method)](library/unittest#unittest.TextTestRunner.run) + [(wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.run) * [run\_coroutine\_threadsafe() (in module asyncio)](library/asyncio-task#asyncio.run_coroutine_threadsafe) * [run\_docstring\_examples() (in module doctest)](library/doctest#doctest.run_docstring_examples) * [run\_doctest() (in module test.support)](library/test#test.support.run_doctest) * [run\_forever() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.run_forever) * [run\_in\_executor() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.run_in_executor) * [run\_in\_subinterp() (in module test.support)](library/test#test.support.run_in_subinterp) * [run\_module() (in module runpy)](library/runpy#runpy.run_module) * [run\_path() (in module runpy)](library/runpy#runpy.run_path) * [run\_python\_until\_end() (in module test.support.script\_helper)](library/test#test.support.script_helper.run_python_until_end) * [run\_script() (modulefinder.ModuleFinder method)](library/modulefinder#modulefinder.ModuleFinder.run_script) * [run\_setup() (in module distutils.core)](distutils/apiref#distutils.core.run_setup) * [run\_unittest() (in module test.support)](library/test#test.support.run_unittest) * [run\_until\_complete() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.run_until_complete) * [run\_with\_locale() (in module test.support)](library/test#test.support.run_with_locale) * [run\_with\_tz() (in module test.support)](library/test#test.support.run_with_tz) * [runcall() (bdb.Bdb method)](library/bdb#bdb.Bdb.runcall) + [(in module pdb)](library/pdb#pdb.runcall) + [(pdb.Pdb method)](library/pdb#pdb.Pdb.runcall) + [(profile.Profile method)](library/profile#profile.Profile.runcall) * [runcode() (code.InteractiveInterpreter method)](library/code#code.InteractiveInterpreter.runcode) * [runctx() (bdb.Bdb method)](library/bdb#bdb.Bdb.runctx) + [(in module profile)](library/profile#profile.runctx) + [(profile.Profile method)](library/profile#profile.Profile.runctx) + [(trace.Trace method)](library/trace#trace.Trace.runctx) * [runeval() (bdb.Bdb method)](library/bdb#bdb.Bdb.runeval) + [(in module pdb)](library/pdb#pdb.runeval) + [(pdb.Pdb method)](library/pdb#pdb.Pdb.runeval) * [runfunc() (trace.Trace method)](library/trace#trace.Trace.runfunc) * [running() (concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.running) * [runpy (module)](library/runpy#module-runpy) * [runsource() (code.InteractiveInterpreter method)](library/code#code.InteractiveInterpreter.runsource) * [runtime\_checkable() (in module typing)](library/typing#typing.runtime_checkable) * [runtime\_library\_dir\_option() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.runtime_library_dir_option) * [RuntimeError](library/exceptions#RuntimeError) * [RuntimeWarning](library/exceptions#RuntimeWarning) * [RUSAGE\_BOTH (in module resource)](library/resource#resource.RUSAGE_BOTH) * [RUSAGE\_CHILDREN (in module resource)](library/resource#resource.RUSAGE_CHILDREN) * [RUSAGE\_SELF (in module resource)](library/resource#resource.RUSAGE_SELF) * [RUSAGE\_THREAD (in module resource)](library/resource#resource.RUSAGE_THREAD) * [RWF\_DSYNC (in module os)](library/os#os.RWF_DSYNC) * [RWF\_HIPRI (in module os)](library/os#os.RWF_HIPRI) * [RWF\_NOWAIT (in module os)](library/os#os.RWF_NOWAIT) * [RWF\_SYNC (in module os)](library/os#os.RWF_SYNC) | S - | | | | --- | --- | | * [S (in module re)](library/re#re.S) * [S\_ENFMT (in module stat)](library/stat#stat.S_ENFMT) * [S\_IEXEC (in module stat)](library/stat#stat.S_IEXEC) * [S\_IFBLK (in module stat)](library/stat#stat.S_IFBLK) * [S\_IFCHR (in module stat)](library/stat#stat.S_IFCHR) * [S\_IFDIR (in module stat)](library/stat#stat.S_IFDIR) * [S\_IFDOOR (in module stat)](library/stat#stat.S_IFDOOR) * [S\_IFIFO (in module stat)](library/stat#stat.S_IFIFO) * [S\_IFLNK (in module stat)](library/stat#stat.S_IFLNK) * [S\_IFMT() (in module stat)](library/stat#stat.S_IFMT) * [S\_IFPORT (in module stat)](library/stat#stat.S_IFPORT) * [S\_IFREG (in module stat)](library/stat#stat.S_IFREG) * [S\_IFSOCK (in module stat)](library/stat#stat.S_IFSOCK) * [S\_IFWHT (in module stat)](library/stat#stat.S_IFWHT) * [S\_IMODE() (in module stat)](library/stat#stat.S_IMODE) * [S\_IREAD (in module stat)](library/stat#stat.S_IREAD) * [S\_IRGRP (in module stat)](library/stat#stat.S_IRGRP) * [S\_IROTH (in module stat)](library/stat#stat.S_IROTH) * [S\_IRUSR (in module stat)](library/stat#stat.S_IRUSR) * [S\_IRWXG (in module stat)](library/stat#stat.S_IRWXG) * [S\_IRWXO (in module stat)](library/stat#stat.S_IRWXO) * [S\_IRWXU (in module stat)](library/stat#stat.S_IRWXU) * [S\_ISBLK() (in module stat)](library/stat#stat.S_ISBLK) * [S\_ISCHR() (in module stat)](library/stat#stat.S_ISCHR) * [S\_ISDIR() (in module stat)](library/stat#stat.S_ISDIR) * [S\_ISDOOR() (in module stat)](library/stat#stat.S_ISDOOR) * [S\_ISFIFO() (in module stat)](library/stat#stat.S_ISFIFO) * [S\_ISGID (in module stat)](library/stat#stat.S_ISGID) * [S\_ISLNK() (in module stat)](library/stat#stat.S_ISLNK) * [S\_ISPORT() (in module stat)](library/stat#stat.S_ISPORT) * [S\_ISREG() (in module stat)](library/stat#stat.S_ISREG) * [S\_ISSOCK() (in module stat)](library/stat#stat.S_ISSOCK) * [S\_ISUID (in module stat)](library/stat#stat.S_ISUID) * [S\_ISVTX (in module stat)](library/stat#stat.S_ISVTX) * [S\_ISWHT() (in module stat)](library/stat#stat.S_ISWHT) * [S\_IWGRP (in module stat)](library/stat#stat.S_IWGRP) * [S\_IWOTH (in module stat)](library/stat#stat.S_IWOTH) * [S\_IWRITE (in module stat)](library/stat#stat.S_IWRITE) * [S\_IWUSR (in module stat)](library/stat#stat.S_IWUSR) * [S\_IXGRP (in module stat)](library/stat#stat.S_IXGRP) * [S\_IXOTH (in module stat)](library/stat#stat.S_IXOTH) * [S\_IXUSR (in module stat)](library/stat#stat.S_IXUSR) * [safe (uuid.SafeUUID attribute)](library/uuid#uuid.SafeUUID.safe) * [safe\_substitute() (string.Template method)](library/string#string.Template.safe_substitute) * [SafeChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.SafeChildWatcher) * [saferepr() (in module pprint)](library/pprint#pprint.saferepr) * [SafeUUID (class in uuid)](library/uuid#uuid.SafeUUID) * [same\_files (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.same_files) * [same\_quantum() (decimal.Context method)](library/decimal#decimal.Context.same_quantum) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.same_quantum) * [samefile() (in module os.path)](library/os.path#os.path.samefile) + [(pathlib.Path method)](library/pathlib#pathlib.Path.samefile) * [SameFileError](library/shutil#shutil.SameFileError) * [sameopenfile() (in module os.path)](library/os.path#os.path.sameopenfile) * [samestat() (in module os.path)](library/os.path#os.path.samestat) * [sample() (in module random)](library/random#random.sample) * [samples() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.samples) * [save() (http.cookiejar.FileCookieJar method)](library/http.cookiejar#http.cookiejar.FileCookieJar.save) * [SaveAs (class in tkinter.filedialog)](library/dialog#tkinter.filedialog.SaveAs) * [SAVEDCWD (in module test.support)](library/test#test.support.SAVEDCWD) * [SaveFileDialog (class in tkinter.filedialog)](library/dialog#tkinter.filedialog.SaveFileDialog) * [SaveKey() (in module winreg)](library/winreg#winreg.SaveKey) * [SaveSignals (class in test.support)](library/test#test.support.SaveSignals) * [savetty() (in module curses)](library/curses#curses.savetty) * [SAX2DOM (class in xml.dom.pulldom)](library/xml.dom.pulldom#xml.dom.pulldom.SAX2DOM) * [SAXException](library/xml.sax#xml.sax.SAXException) * [SAXNotRecognizedException](library/xml.sax#xml.sax.SAXNotRecognizedException) * [SAXNotSupportedException](library/xml.sax#xml.sax.SAXNotSupportedException) * [SAXParseException](library/xml.sax#xml.sax.SAXParseException) * [scaleb() (decimal.Context method)](library/decimal#decimal.Context.scaleb) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.scaleb) * [scandir() (in module os)](library/os#os.scandir) * [scanf()](library/re#index-38) * [sched (module)](library/sched#module-sched) * [SCHED\_BATCH (in module os)](library/os#os.SCHED_BATCH) * [SCHED\_FIFO (in module os)](library/os#os.SCHED_FIFO) * [sched\_get\_priority\_max() (in module os)](library/os#os.sched_get_priority_max) * [sched\_get\_priority\_min() (in module os)](library/os#os.sched_get_priority_min) * [sched\_getaffinity() (in module os)](library/os#os.sched_getaffinity) * [sched\_getparam() (in module os)](library/os#os.sched_getparam) * [sched\_getscheduler() (in module os)](library/os#os.sched_getscheduler) * [SCHED\_IDLE (in module os)](library/os#os.SCHED_IDLE) * [SCHED\_OTHER (in module os)](library/os#os.SCHED_OTHER) * [sched\_param (class in os)](library/os#os.sched_param) * [sched\_priority (os.sched\_param attribute)](library/os#os.sched_param.sched_priority) * [SCHED\_RESET\_ON\_FORK (in module os)](library/os#os.SCHED_RESET_ON_FORK) * [SCHED\_RR (in module os)](library/os#os.SCHED_RR) * [sched\_rr\_get\_interval() (in module os)](library/os#os.sched_rr_get_interval) * [sched\_setaffinity() (in module os)](library/os#os.sched_setaffinity) * [sched\_setparam() (in module os)](library/os#os.sched_setparam) * [sched\_setscheduler() (in module os)](library/os#os.sched_setscheduler) * [SCHED\_SPORADIC (in module os)](library/os#os.SCHED_SPORADIC) * [sched\_yield() (in module os)](library/os#os.sched_yield) * [scheduler (class in sched)](library/sched#sched.scheduler) * [schema (in module msilib)](library/msilib#msilib.schema) * [scope](reference/executionmodel#index-3), [[1]](reference/executionmodel#index-7) * [scope\_id (ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.scope_id) * [Screen (class in turtle)](library/turtle#turtle.Screen) * [screensize() (in module turtle)](library/turtle#turtle.screensize) * [script\_from\_examples() (in module doctest)](library/doctest#doctest.script_from_examples) * [scroll() (curses.window method)](library/curses#curses.window.scroll) * [ScrolledCanvas (class in turtle)](library/turtle#turtle.ScrolledCanvas) * [ScrolledText (class in tkinter.scrolledtext)](library/tkinter.scrolledtext#tkinter.scrolledtext.ScrolledText) * [scrollok() (curses.window method)](library/curses#curses.window.scrollok) * [scrypt() (in module hashlib)](library/hashlib#hashlib.scrypt) * sdterr + [stdin stdout](c-api/init#index-17) * [seal() (in module unittest.mock)](library/unittest.mock#unittest.mock.seal) * search + [path, module](c-api/init#index-16), [[1]](c-api/init#index-23), [[2]](c-api/init#index-24), [[3]](c-api/intro#index-23), [[4]](library/linecache#index-0), [[5]](library/site#index-0), [[6]](library/sys#index-21), [[7]](tutorial/modules#index-0) * [search() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.search) + [(in module re)](library/re#re.search) + [(re.Pattern method)](library/re#re.Pattern.search) * [second (datetime.datetime attribute)](library/datetime#datetime.datetime.second) + [(datetime.time attribute)](library/datetime#datetime.time.second) * [seconds since the epoch](library/time#index-1) * [secrets (module)](library/secrets#module-secrets) * [SECTCRE (configparser.ConfigParser attribute)](library/configparser#configparser.ConfigParser.SECTCRE) * [sections() (configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.sections) * [secure (http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.secure) * [secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512](library/hashlib#index-0) * [Secure Sockets Layer](library/ssl#index-1) * security + [CGI](library/cgi#index-2) + [http.server](library/http.server#index-3) * [security considerations](library/security_warnings#index-0) * [see() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.see) * [seed() (in module random)](library/random#random.seed) * [seek() (chunk.Chunk method)](library/chunk#chunk.Chunk.seek) + [(io.IOBase method)](library/io#io.IOBase.seek) + [(io.TextIOBase method)](library/io#io.TextIOBase.seek) + [(mmap.mmap method)](library/mmap#mmap.mmap.seek) * [SEEK\_CUR (in module os)](library/os#os.SEEK_CUR) * [SEEK\_END (in module os)](library/os#os.SEEK_END) * [SEEK\_SET (in module os)](library/os#os.SEEK_SET) * [seekable() (io.IOBase method)](library/io#io.IOBase.seekable) * [seen\_greeting (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.seen_greeting) * [Select (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Select) * [select (module)](library/select#module-select) * [select() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.select) + [(in module select)](library/select#select.select) + [(selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.select) + [(tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.select) * [selected\_alpn\_protocol() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.selected_alpn_protocol) * [selected\_npn\_protocol() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.selected_npn_protocol) * [selection() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.selection) * [selection\_add() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.selection_add) * [selection\_remove() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.selection_remove) * [selection\_set() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.selection_set) * [selection\_toggle() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.selection_toggle) * [selector (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.selector) * [SelectorEventLoop (class in asyncio)](library/asyncio-eventloop#asyncio.SelectorEventLoop) * [SelectorKey (class in selectors)](library/selectors#selectors.SelectorKey) * [selectors (module)](library/selectors#module-selectors) * [SelectSelector (class in selectors)](library/selectors#selectors.SelectSelector) * [Semaphore (class in asyncio)](library/asyncio-sync#asyncio.Semaphore) + [(class in multiprocessing)](library/multiprocessing#multiprocessing.Semaphore) + [(class in threading)](library/threading#threading.Semaphore) * [Semaphore() (multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Semaphore) * [semaphores, binary](library/_thread#index-0) * [SEMI (in module token)](library/token#token.SEMI) * [send() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.send) + [(coroutine method)](reference/datamodel#coroutine.send) + [(generator method)](reference/expressions#generator.send) + [(http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.send) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.send) + [(logging.handlers.DatagramHandler method)](library/logging.handlers#logging.handlers.DatagramHandler.send) + [(logging.handlers.SocketHandler method)](library/logging.handlers#logging.handlers.SocketHandler.send) + [(multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.send) + [(socket.socket method)](library/socket#socket.socket.send) * [send\_bytes() (multiprocessing.connection.Connection method)](library/multiprocessing#multiprocessing.connection.Connection.send_bytes) * [send\_error() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.send_error) * [send\_fds() (in module socket)](library/socket#socket.send_fds) * [send\_flowing\_data() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_flowing_data) * [send\_header() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.send_header) * [send\_hor\_rule() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_hor_rule) * [send\_label\_data() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_label_data) * [send\_line\_break() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_line_break) * [send\_literal\_data() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_literal_data) * [send\_message() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.send_message) * [send\_paragraph() (formatter.writer method)](https://docs.python.org/3.9/library/formatter.html#formatter.writer.send_paragraph) * [send\_response() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.send_response) * [send\_response\_only() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.send_response_only) * [send\_signal() (asyncio.subprocess.Process method)](library/asyncio-subprocess#asyncio.subprocess.Process.send_signal) + [(asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.send_signal) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.send_signal) * [sendall() (socket.socket method)](library/socket#socket.socket.sendall) * [sendcmd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.sendcmd) * [sendfile() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sendfile) + [(in module os)](library/os#os.sendfile) + [(socket.socket method)](library/socket#socket.socket.sendfile) + [(wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.sendfile) * [SendfileNotAvailableError](library/asyncio-exceptions#asyncio.SendfileNotAvailableError) * [sendmail() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.sendmail) * [sendmsg() (socket.socket method)](library/socket#socket.socket.sendmsg) * [sendmsg\_afalg() (socket.socket method)](library/socket#socket.socket.sendmsg_afalg) * [sendto() (asyncio.DatagramTransport method)](library/asyncio-protocol#asyncio.DatagramTransport.sendto) + [(socket.socket method)](library/socket#socket.socket.sendto) * [sentinel (in module unittest.mock)](library/unittest.mock#unittest.mock.sentinel) + [(multiprocessing.Process attribute)](library/multiprocessing#multiprocessing.Process.sentinel) * [sep (in module os)](library/os#os.sep) * [**sequence**](glossary#term-sequence) + [item](reference/expressions#index-42) + [iteration](library/stdtypes#index-17) + [object](c-api/concrete#index-1), [[1]](library/stdtypes#index-18), [[2]](reference/compound_stmts#index-6), [[3]](reference/datamodel#index-15), [[4]](reference/datamodel#index-51), [[5]](reference/expressions#index-42), [[6]](reference/expressions#index-45), [[7]](reference/expressions#index-80), [[8]](reference/simple_stmts#index-10) + [types, immutable](library/stdtypes#index-20) + [types, mutable](library/stdtypes#index-21) + [types, operations on](library/stdtypes#index-19), [[1]](library/stdtypes#index-22) * [Sequence (class in collections.abc)](library/collections.abc#collections.abc.Sequence) + [(class in typing)](library/typing#typing.Sequence) * [sequence (in module msilib)](library/msilib#msilib.sequence) * [sequence2st() (in module parser)](library/parser#parser.sequence2st) * [SequenceMatcher (class in difflib)](library/difflib#difflib.SequenceMatcher) * serializing + [objects](library/pickle#index-0) * [serve\_forever() (asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.serve_forever) + [(socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.serve_forever) * server + [WWW](library/cgi#index-0), [[1]](library/http.server#index-0) * [Server (class in asyncio)](library/asyncio-eventloop#asyncio.Server) * [server (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.server) * [server\_activate() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.server_activate) * [server\_address (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.server_address) * [server\_bind() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.server_bind) * [server\_close() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.server_close) * [server\_hostname (ssl.SSLSocket attribute)](library/ssl#ssl.SSLSocket.server_hostname) * [server\_side (ssl.SSLSocket attribute)](library/ssl#ssl.SSLSocket.server_side) * [server\_software (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.server_software) * [server\_version (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.server_version) + [(http.server.SimpleHTTPRequestHandler attribute)](library/http.server#http.server.SimpleHTTPRequestHandler.server_version) * [ServerProxy (class in xmlrpc.client)](library/xmlrpc.client#xmlrpc.client.ServerProxy) * [service\_actions() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.service_actions) * [session (ssl.SSLSocket attribute)](library/ssl#ssl.SSLSocket.session) * [session\_reused (ssl.SSLSocket attribute)](library/ssl#ssl.SSLSocket.session_reused) * [session\_stats() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.session_stats) * set + [comprehensions](reference/expressions#index-16) + [display](reference/expressions#index-16) + [object](c-api/set#index-0), [[1]](library/stdtypes#index-49), [[2]](reference/datamodel#index-27), [[3]](reference/expressions#index-16) * [set (built-in class)](library/stdtypes#set) * [Set (class in ast)](library/ast#ast.Set) + [(class in collections.abc)](library/collections.abc#collections.abc.Set) + [(class in typing)](library/typing#typing.Set) * [Set Breakpoint](library/idle#index-4) * [**set comprehension**](glossary#term-set-comprehension) * set type + [object](reference/datamodel#index-26) * [set() (asyncio.Event method)](library/asyncio-sync#asyncio.Event.set) + [(configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.set) + [(configparser.RawConfigParser method)](library/configparser#configparser.RawConfigParser.set) + [(contextvars.ContextVar method)](library/contextvars#contextvars.ContextVar.set) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.set) + [(ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.set) + [(test.support.EnvironmentVarGuard method)](library/test#test.support.EnvironmentVarGuard.set) + [(threading.Event method)](library/threading#threading.Event.set) + [(tkinter.ttk.Combobox method)](library/tkinter.ttk#tkinter.ttk.Combobox.set) + [(tkinter.ttk.Spinbox method)](library/tkinter.ttk#tkinter.ttk.Spinbox.set) + [(tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.set) + [(xml.etree.ElementTree.Element method)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.set) * [SET\_ADD (opcode)](library/dis#opcode-SET_ADD) * [set\_all()](c-api/intro#index-11) * [set\_allowed\_domains() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.set_allowed_domains) * [set\_alpn\_protocols() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.set_alpn_protocols) * [set\_app() (wsgiref.simple\_server.WSGIServer method)](library/wsgiref#wsgiref.simple_server.WSGIServer.set_app) * [set\_asyncgen\_hooks() (in module sys)](library/sys#sys.set_asyncgen_hooks) * [set\_authorizer() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.set_authorizer) * [set\_auto\_history() (in module readline)](library/readline#readline.set_auto_history) * [set\_blocked\_domains() (http.cookiejar.DefaultCookiePolicy method)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.set_blocked_domains) * [set\_blocking() (in module os)](library/os#os.set_blocking) * [set\_boundary() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.set_boundary) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.set_boundary) * [set\_break() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_break) * [set\_charset() (email.message.Message method)](library/email.compat32-message#email.message.Message.set_charset) * [set\_child\_watcher() (asyncio.AbstractEventLoopPolicy method)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy.set_child_watcher) + [(in module asyncio)](library/asyncio-policy#asyncio.set_child_watcher) * [set\_children() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.set_children) * [set\_ciphers() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.set_ciphers) * [set\_completer() (in module readline)](library/readline#readline.set_completer) * [set\_completer\_delims() (in module readline)](library/readline#readline.set_completer_delims) * [set\_completion\_display\_matches\_hook() (in module readline)](library/readline#readline.set_completion_display_matches_hook) * [set\_content() (email.contentmanager.ContentManager method)](library/email.contentmanager#email.contentmanager.ContentManager.set_content) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.set_content) + [(in module email.contentmanager)](library/email.contentmanager#email.contentmanager.set_content) * [set\_continue() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_continue) * [set\_cookie() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.set_cookie) * [set\_cookie\_if\_ok() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.set_cookie_if_ok) * [set\_coroutine\_origin\_tracking\_depth() (in module sys)](library/sys#sys.set_coroutine_origin_tracking_depth) * [set\_current() (msilib.Feature method)](library/msilib#msilib.Feature.set_current) * [set\_data() (importlib.abc.SourceLoader method)](library/importlib#importlib.abc.SourceLoader.set_data) + [(importlib.machinery.SourceFileLoader method)](library/importlib#importlib.machinery.SourceFileLoader.set_data) * [set\_date() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.set_date) * [set\_debug() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.set_debug) + [(in module gc)](library/gc#gc.set_debug) * [set\_debuglevel() (ftplib.FTP method)](library/ftplib#ftplib.FTP.set_debuglevel) + [(http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.set_debuglevel) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.set_debuglevel) + [(poplib.POP3 method)](library/poplib#poplib.POP3.set_debuglevel) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.set_debuglevel) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.set_debuglevel) * [set\_default\_executor() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.set_default_executor) * [set\_default\_type() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.set_default_type) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.set_default_type) * [set\_default\_verify\_paths() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.set_default_verify_paths) * [set\_defaults() (argparse.ArgumentParser method)](library/argparse#argparse.ArgumentParser.set_defaults) + [(optparse.OptionParser method)](library/optparse#optparse.OptionParser.set_defaults) * [set\_ecdh\_curve() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.set_ecdh_curve) * [set\_errno() (in module ctypes)](library/ctypes#ctypes.set_errno) * [set\_escdelay() (in module curses)](library/curses#curses.set_escdelay) * [set\_event\_loop() (asyncio.AbstractEventLoopPolicy method)](library/asyncio-policy#asyncio.AbstractEventLoopPolicy.set_event_loop) + [(in module asyncio)](library/asyncio-eventloop#asyncio.set_event_loop) * [set\_event\_loop\_policy() (in module asyncio)](library/asyncio-policy#asyncio.set_event_loop_policy) * [set\_exception() (asyncio.Future method)](library/asyncio-future#asyncio.Future.set_exception) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.set_exception) * [set\_exception\_handler() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.set_exception_handler) * [set\_executable() (in module multiprocessing)](library/multiprocessing#multiprocessing.set_executable) * [set\_executables() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_executables) * [set\_filter() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.set_filter) * [set\_flags() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.set_flags) + [(mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.set_flags) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.set_flags) * [set\_from() (mailbox.mboxMessage method)](library/mailbox#mailbox.mboxMessage.set_from) + [(mailbox.MMDFMessage method)](library/mailbox#mailbox.MMDFMessage.set_from) * [set\_handle\_inheritable() (in module os)](library/os#os.set_handle_inheritable) * [set\_history\_length() (in module readline)](library/readline#readline.set_history_length) * [set\_include\_dirs() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_include_dirs) * [set\_info() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.set_info) * [set\_inheritable() (in module os)](library/os#os.set_inheritable) + [(socket.socket method)](library/socket#socket.socket.set_inheritable) * [set\_int\_max\_str\_digits() (in module sys)](library/sys#sys.set_int_max_str_digits) * [set\_labels() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.set_labels) * [set\_last\_error() (in module ctypes)](library/ctypes#ctypes.set_last_error) * [set\_libraries() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_libraries) * [set\_library\_dirs() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_library_dirs) * [set\_link\_objects() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_link_objects) * [set\_literal (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-set_literal) * [set\_loader() (in module importlib.util)](library/importlib#importlib.util.set_loader) * [set\_match\_tests() (in module test.support)](library/test#test.support.set_match_tests) * [set\_memlimit() (in module test.support)](library/test#test.support.set_memlimit) * [set\_name() (asyncio.Task method)](library/asyncio-task#asyncio.Task.set_name) * [set\_next() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_next) * [set\_nonstandard\_attr() (http.cookiejar.Cookie method)](library/http.cookiejar#http.cookiejar.Cookie.set_nonstandard_attr) * [set\_npn\_protocols() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.set_npn_protocols) * [set\_ok() (http.cookiejar.CookiePolicy method)](library/http.cookiejar#http.cookiejar.CookiePolicy.set_ok) * [set\_option\_negotiation\_callback() (telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.set_option_negotiation_callback) * [set\_output\_charset() (gettext.NullTranslations method)](library/gettext#gettext.NullTranslations.set_output_charset) * [set\_package() (in module importlib.util)](library/importlib#importlib.util.set_package) * [set\_param() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.set_param) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.set_param) * [set\_pasv() (ftplib.FTP method)](library/ftplib#ftplib.FTP.set_pasv) * [set\_payload() (email.message.Message method)](library/email.compat32-message#email.message.Message.set_payload) * [set\_policy() (http.cookiejar.CookieJar method)](library/http.cookiejar#http.cookiejar.CookieJar.set_policy) * [set\_position() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.set_position) * [set\_pre\_input\_hook() (in module readline)](library/readline#readline.set_pre_input_hook) * [set\_progress\_handler() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.set_progress_handler) * [set\_protocol() (asyncio.BaseTransport method)](library/asyncio-protocol#asyncio.BaseTransport.set_protocol) * [set\_proxy() (urllib.request.Request method)](library/urllib.request#urllib.request.Request.set_proxy) * [set\_python\_build() (in module distutils.sysconfig)](distutils/apiref#distutils.sysconfig.set_python_build) * [set\_quit() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_quit) * [set\_recsrc() (ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.set_recsrc) * [set\_result() (asyncio.Future method)](library/asyncio-future#asyncio.Future.set_result) + [(concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.set_result) * [set\_return() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_return) * [set\_running\_or\_notify\_cancel() (concurrent.futures.Future method)](library/concurrent.futures#concurrent.futures.Future.set_running_or_notify_cancel) * [set\_runtime\_library\_dirs() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.set_runtime_library_dirs) * [set\_selection() (tkinter.filedialog.FileDialog method)](library/dialog#tkinter.filedialog.FileDialog.set_selection) * [set\_seq1() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.set_seq1) * [set\_seq2() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.set_seq2) * [set\_seqs() (difflib.SequenceMatcher method)](library/difflib#difflib.SequenceMatcher.set_seqs) * [set\_sequences() (mailbox.MH method)](library/mailbox#mailbox.MH.set_sequences) + [(mailbox.MHMessage method)](library/mailbox#mailbox.MHMessage.set_sequences) * [set\_server\_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_documentation) + [(xmlrpc.server.DocXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_documentation) * [set\_server\_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_name) + [(xmlrpc.server.DocXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_name) * [set\_server\_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler method)](library/xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_title) + [(xmlrpc.server.DocXMLRPCServer method)](library/xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_title) * [set\_servername\_callback (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.set_servername_callback) * [set\_spacing() (formatter.formatter method)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.set_spacing) * [set\_start\_method() (in module multiprocessing)](library/multiprocessing#multiprocessing.set_start_method) * [set\_startup\_hook() (in module readline)](library/readline#readline.set_startup_hook) * [set\_step() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_step) * [set\_subdir() (mailbox.MaildirMessage method)](library/mailbox#mailbox.MaildirMessage.set_subdir) * [set\_tabsize() (in module curses)](library/curses#curses.set_tabsize) * [set\_task\_factory() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.set_task_factory) * [set\_terminator() (asynchat.async\_chat method)](library/asynchat#asynchat.async_chat.set_terminator) * [set\_threshold() (in module gc)](library/gc#gc.set_threshold) * [set\_trace() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_trace) + [(in module bdb)](library/bdb#bdb.set_trace) + [(in module pdb)](library/pdb#pdb.set_trace) + [(pdb.Pdb method)](library/pdb#pdb.Pdb.set_trace) * [set\_trace\_callback() (sqlite3.Connection method)](library/sqlite3#sqlite3.Connection.set_trace_callback) * [set\_tunnel() (http.client.HTTPConnection method)](library/http.client#http.client.HTTPConnection.set_tunnel) * [set\_type() (email.message.Message method)](library/email.compat32-message#email.message.Message.set_type) * [set\_unittest\_reportflags() (in module doctest)](library/doctest#doctest.set_unittest_reportflags) * [set\_unixfrom() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.set_unixfrom) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.set_unixfrom) * [set\_until() (bdb.Bdb method)](library/bdb#bdb.Bdb.set_until) * [SET\_UPDATE (opcode)](library/dis#opcode-SET_UPDATE) * [set\_url() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.set_url) * [set\_usage() (optparse.OptionParser method)](library/optparse#optparse.OptionParser.set_usage) * [set\_userptr() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.set_userptr) * [set\_visible() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.set_visible) * [set\_wakeup\_fd() (in module signal)](library/signal#signal.set_wakeup_fd) * [set\_write\_buffer\_limits() (asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.set_write_buffer_limits) * [setacl() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.setacl) * [setannotation() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.setannotation) * [setattr() (built-in function)](library/functions#setattr) * [setattrfunc (C type)](c-api/typeobj#c.setattrfunc) * [setAttribute() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.setAttribute) * [setAttributeNode() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.setAttributeNode) * [setAttributeNodeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.setAttributeNodeNS) * [setAttributeNS() (xml.dom.Element method)](library/xml.dom#xml.dom.Element.setAttributeNS) * [setattrofunc (C type)](c-api/typeobj#c.setattrofunc) * [SetBase() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.SetBase) * [setblocking() (socket.socket method)](library/socket#socket.socket.setblocking) * [setByteStream() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.setByteStream) * [setcbreak() (in module tty)](library/tty#tty.setcbreak) * [setCharacterStream() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.setCharacterStream) * [SetComp (class in ast)](library/ast#ast.SetComp) * [setcomptype() (aifc.aifc method)](library/aifc#aifc.aifc.setcomptype) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setcomptype) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setcomptype) * [setContentHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setContentHandler) * [setcontext() (in module decimal)](library/decimal#decimal.setcontext) * [setDaemon() (threading.Thread method)](library/threading#threading.Thread.setDaemon) * [setdefault() (dict method)](library/stdtypes#dict.setdefault) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.setdefault) * [setdefaulttimeout() (in module socket)](library/socket#socket.setdefaulttimeout) * [setdlopenflags() (in module sys)](library/sys#sys.setdlopenflags) * [setDocumentLocator() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.setDocumentLocator) * [setDTDHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setDTDHandler) * [setegid() (in module os)](library/os#os.setegid) * [setEncoding() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.setEncoding) * [setEntityResolver() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setEntityResolver) * [setErrorHandler() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setErrorHandler) * [seteuid() (in module os)](library/os#os.seteuid) * [setFeature() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setFeature) * [setfirstweekday() (in module calendar)](library/calendar#calendar.setfirstweekday) * [setfmt() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.setfmt) * [setFormatter() (logging.Handler method)](library/logging#logging.Handler.setFormatter) * [setframerate() (aifc.aifc method)](library/aifc#aifc.aifc.setframerate) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setframerate) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setframerate) * [setgid() (in module os)](library/os#os.setgid) * [setgroups() (in module os)](library/os#os.setgroups) * [seth() (in module turtle)](library/turtle#turtle.seth) * [setheading() (in module turtle)](library/turtle#turtle.setheading) * [sethostname() (in module socket)](library/socket#socket.sethostname) * [setinputsizes() (sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.setinputsizes) * [SetInteger() (msilib.Record method)](library/msilib#msilib.Record.SetInteger) * [setitem() (in module operator)](library/operator#operator.setitem) * [setitimer() (in module signal)](library/signal#signal.setitimer) * [setLevel() (logging.Handler method)](library/logging#logging.Handler.setLevel) + [(logging.Logger method)](library/logging#logging.Logger.setLevel) * [setlocale() (in module locale)](library/locale#locale.setlocale) * [setLocale() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setLocale) * [setLoggerClass() (in module logging)](library/logging#logging.setLoggerClass) * [setlogmask() (in module syslog)](library/syslog#syslog.setlogmask) * [setLogRecordFactory() (in module logging)](library/logging#logging.setLogRecordFactory) * [setmark() (aifc.aifc method)](library/aifc#aifc.aifc.setmark) * [setMaxConns() (urllib.request.CacheFTPHandler method)](library/urllib.request#urllib.request.CacheFTPHandler.setMaxConns) * [setmode() (in module msvcrt)](library/msvcrt#msvcrt.setmode) * [setName() (threading.Thread method)](library/threading#threading.Thread.setName) * [setnchannels() (aifc.aifc method)](library/aifc#aifc.aifc.setnchannels) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setnchannels) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setnchannels) * [setnframes() (aifc.aifc method)](library/aifc#aifc.aifc.setnframes) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setnframes) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setnframes) * [setoutputsize() (sqlite3.Cursor method)](library/sqlite3#sqlite3.Cursor.setoutputsize) * [SetParamEntityParsing() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.SetParamEntityParsing) * [setparameters() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.setparameters) * [setparams() (aifc.aifc method)](library/aifc#aifc.aifc.setparams) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setparams) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setparams) * [setpassword() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.setpassword) * [setpgid() (in module os)](library/os#os.setpgid) * [setpgrp() (in module os)](library/os#os.setpgrp) * [setpos() (aifc.aifc method)](library/aifc#aifc.aifc.setpos) + [(in module turtle)](library/turtle#turtle.setpos) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.setpos) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.setpos) * [setposition() (in module turtle)](library/turtle#turtle.setposition) * [setpriority() (in module os)](library/os#os.setpriority) * [setprofile() (in module sys)](library/sys#sys.setprofile) + [(in module threading)](library/threading#threading.setprofile) * [SetProperty() (msilib.SummaryInformation method)](library/msilib#msilib.SummaryInformation.SetProperty) * [setProperty() (xml.sax.xmlreader.XMLReader method)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader.setProperty) * [setPublicId() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.setPublicId) * [setquota() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.setquota) * [setraw() (in module tty)](library/tty#tty.setraw) * [setrecursionlimit() (in module sys)](library/sys#sys.setrecursionlimit) * [setregid() (in module os)](library/os#os.setregid) * [setresgid() (in module os)](library/os#os.setresgid) * [setresuid() (in module os)](library/os#os.setresuid) * [setreuid() (in module os)](library/os#os.setreuid) * [setrlimit() (in module resource)](library/resource#resource.setrlimit) * [setsampwidth() (aifc.aifc method)](library/aifc#aifc.aifc.setsampwidth) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.setsampwidth) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.setsampwidth) * [setscrreg() (curses.window method)](library/curses#curses.window.setscrreg) * [setsid() (in module os)](library/os#os.setsid) * [setsockopt() (socket.socket method)](library/socket#socket.socket.setsockopt) * [setstate() (codecs.IncrementalDecoder method)](library/codecs#codecs.IncrementalDecoder.setstate) + [(codecs.IncrementalEncoder method)](library/codecs#codecs.IncrementalEncoder.setstate) + [(in module random)](library/random#random.setstate) * [setStream() (logging.StreamHandler method)](library/logging.handlers#logging.StreamHandler.setStream) * [SetStream() (msilib.Record method)](library/msilib#msilib.Record.SetStream) * [SetString() (msilib.Record method)](library/msilib#msilib.Record.SetString) * [setswitchinterval() (in module sys)](c-api/init#index-34), [[1]](library/sys#sys.setswitchinterval) + [(in module test.support)](library/test#test.support.setswitchinterval) * [setSystemId() (xml.sax.xmlreader.InputSource method)](library/xml.sax.reader#xml.sax.xmlreader.InputSource.setSystemId) * [setsyx() (in module curses)](library/curses#curses.setsyx) * [setTarget() (logging.handlers.MemoryHandler method)](library/logging.handlers#logging.handlers.MemoryHandler.setTarget) * [settiltangle() (in module turtle)](library/turtle#turtle.settiltangle) * [settimeout() (socket.socket method)](library/socket#socket.socket.settimeout) * [setTimeout() (urllib.request.CacheFTPHandler method)](library/urllib.request#urllib.request.CacheFTPHandler.setTimeout) * [settrace() (in module sys)](library/sys#sys.settrace) + [(in module threading)](library/threading#threading.settrace) * [setuid() (in module os)](library/os#os.setuid) * [setundobuffer() (in module turtle)](library/turtle#turtle.setundobuffer) * [setup() (in module distutils.core)](distutils/apiref#distutils.core.setup) + [(in module turtle)](library/turtle#turtle.setup) + [(socketserver.BaseRequestHandler method)](library/socketserver#socketserver.BaseRequestHandler.setup) * [setUp() (unittest.TestCase method)](library/unittest#unittest.TestCase.setUp) * [SETUP\_ANNOTATIONS (opcode)](library/dis#opcode-SETUP_ANNOTATIONS) * [SETUP\_ASYNC\_WITH (opcode)](library/dis#opcode-SETUP_ASYNC_WITH) * [setup\_environ() (wsgiref.handlers.BaseHandler method)](library/wsgiref#wsgiref.handlers.BaseHandler.setup_environ) * [SETUP\_FINALLY (opcode)](library/dis#opcode-SETUP_FINALLY) * [setup\_python() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.setup_python) * [setup\_scripts() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.setup_scripts) * [setup\_testing\_defaults() (in module wsgiref.util)](library/wsgiref#wsgiref.util.setup_testing_defaults) * [SETUP\_WITH (opcode)](library/dis#opcode-SETUP_WITH) * [setUpClass() (unittest.TestCase method)](library/unittest#unittest.TestCase.setUpClass) * [setupterm() (in module curses)](library/curses#curses.setupterm) * [SetValue() (in module winreg)](library/winreg#winreg.SetValue) * [SetValueEx() (in module winreg)](library/winreg#winreg.SetValueEx) * [setworldcoordinates() (in module turtle)](library/turtle#turtle.setworldcoordinates) * [setx() (in module turtle)](library/turtle#turtle.setx) * [setxattr() (in module os)](library/os#os.setxattr) * [sety() (in module turtle)](library/turtle#turtle.sety) * [SF\_APPEND (in module stat)](library/stat#stat.SF_APPEND) * [SF\_ARCHIVED (in module stat)](library/stat#stat.SF_ARCHIVED) * [SF\_IMMUTABLE (in module stat)](library/stat#stat.SF_IMMUTABLE) * [SF\_MNOWAIT (in module os)](library/os#os.SF_MNOWAIT) * [SF\_NODISKIO (in module os)](library/os#os.SF_NODISKIO) * [SF\_NOUNLINK (in module stat)](library/stat#stat.SF_NOUNLINK) * [SF\_SNAPSHOT (in module stat)](library/stat#stat.SF_SNAPSHOT) * [SF\_SYNC (in module os)](library/os#os.SF_SYNC) * [Shape (class in turtle)](library/turtle#turtle.Shape) * [shape (memoryview attribute)](library/stdtypes#memoryview.shape) * [shape() (in module turtle)](library/turtle#turtle.shape) * [shapesize() (in module turtle)](library/turtle#turtle.shapesize) * [shapetransform() (in module turtle)](library/turtle#turtle.shapetransform) * [share() (socket.socket method)](library/socket#socket.socket.share) * [ShareableList (class in multiprocessing.shared\_memory)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.ShareableList) * [ShareableList() (multiprocessing.managers.SharedMemoryManager method)](library/multiprocessing.shared_memory#multiprocessing.managers.SharedMemoryManager.ShareableList) * [Shared Memory](library/multiprocessing.shared_memory#index-0) * [shared\_ciphers() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.shared_ciphers) * [shared\_object\_filename() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.shared_object_filename) * [SharedMemory (class in multiprocessing.shared\_memory)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory) * [SharedMemory() (multiprocessing.managers.SharedMemoryManager method)](library/multiprocessing.shared_memory#multiprocessing.managers.SharedMemoryManager.SharedMemory) * [SharedMemoryManager (class in multiprocessing.managers)](library/multiprocessing.shared_memory#multiprocessing.managers.SharedMemoryManager) * [shearfactor() (in module turtle)](library/turtle#turtle.shearfactor) * [Shelf (class in shelve)](library/shelve#shelve.Shelf) * shelve + [module](library/marshal#index-0) * [shelve (module)](library/shelve#module-shelve) * [shield() (in module asyncio)](library/asyncio-task#asyncio.shield) * [shift() (decimal.Context method)](library/decimal#decimal.Context.shift) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.shift) * [shift\_path\_info() (in module wsgiref.util)](library/wsgiref#wsgiref.util.shift_path_info) * shifting + [operation](reference/expressions#index-71) + [operations](library/stdtypes#index-16) * [shlex (class in shlex)](library/shlex#shlex.shlex) + [(module)](library/shlex#module-shlex) * [shm (multiprocessing.shared\_memory.ShareableList attribute)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.ShareableList.shm) * [SHORT\_TIMEOUT (in module test.support)](library/test#test.support.SHORT_TIMEOUT) * [shortDescription() (unittest.TestCase method)](library/unittest#unittest.TestCase.shortDescription) * [shorten() (in module textwrap)](library/textwrap#textwrap.shorten) * [shouldFlush() (logging.handlers.BufferingHandler method)](library/logging.handlers#logging.handlers.BufferingHandler.shouldFlush) + [(logging.handlers.MemoryHandler method)](library/logging.handlers#logging.handlers.MemoryHandler.shouldFlush) * [shouldStop (unittest.TestResult attribute)](library/unittest#unittest.TestResult.shouldStop) * [show() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.show) + [(tkinter.commondialog.Dialog method)](library/dialog#tkinter.commondialog.Dialog.show) * [show\_code() (in module dis)](library/dis#dis.show_code) * [show\_compilers() (in module distutils.ccompiler)](distutils/apiref#distutils.ccompiler.show_compilers) * [showerror() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.showerror) * [showinfo() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.showinfo) * [showsyntaxerror() (code.InteractiveInterpreter method)](library/code#code.InteractiveInterpreter.showsyntaxerror) * [showtraceback() (code.InteractiveInterpreter method)](library/code#code.InteractiveInterpreter.showtraceback) * [showturtle() (in module turtle)](library/turtle#turtle.showturtle) * [showwarning() (in module tkinter.messagebox)](library/tkinter.messagebox#tkinter.messagebox.showwarning) + [(in module warnings)](library/warnings#warnings.showwarning) * [shuffle() (in module random)](library/random#random.shuffle) * [shutdown() (concurrent.futures.Executor method)](library/concurrent.futures#concurrent.futures.Executor.shutdown) + [(imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.shutdown) + [(in module logging)](library/logging#logging.shutdown) + [(multiprocessing.managers.BaseManager method)](library/multiprocessing#multiprocessing.managers.BaseManager.shutdown) + [(socket.socket method)](library/socket#socket.socket.shutdown) + [(socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.shutdown) * [shutdown\_asyncgens() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.shutdown_asyncgens) * [shutdown\_default\_executor() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.shutdown_default_executor) * [shutil (module)](library/shutil#module-shutil) * [side\_effect (unittest.mock.Mock attribute)](library/unittest.mock#unittest.mock.Mock.side_effect) * [SIG\_BLOCK (in module signal)](library/signal#signal.SIG_BLOCK) * [SIG\_DFL (in module signal)](library/signal#signal.SIG_DFL) * [SIG\_IGN (in module signal)](library/signal#signal.SIG_IGN) * [SIG\_SETMASK (in module signal)](library/signal#signal.SIG_SETMASK) * [SIG\_UNBLOCK (in module signal)](library/signal#signal.SIG_UNBLOCK) * [SIGABRT (in module signal)](library/signal#signal.SIGABRT) * [SIGALRM (in module signal)](library/signal#signal.SIGALRM) * [SIGBREAK (in module signal)](library/signal#signal.SIGBREAK) * [SIGBUS (in module signal)](library/signal#signal.SIGBUS) * [SIGCHLD (in module signal)](library/signal#signal.SIGCHLD) * [SIGCLD (in module signal)](library/signal#signal.SIGCLD) * [SIGCONT (in module signal)](library/signal#signal.SIGCONT) * [SIGFPE (in module signal)](library/signal#signal.SIGFPE) * [SIGHUP (in module signal)](library/signal#signal.SIGHUP) * [SIGILL (in module signal)](library/signal#signal.SIGILL) * [SIGINT](c-api/exceptions#index-1), [[1]](c-api/exceptions#index-2) + [(in module signal)](library/signal#signal.SIGINT) * [siginterrupt() (in module signal)](library/signal#signal.siginterrupt) * [SIGKILL (in module signal)](library/signal#signal.SIGKILL) * signal + [module](c-api/exceptions#index-1), [[1]](library/_thread#index-2) * [signal (module)](library/signal#module-signal) * [signal() (in module signal)](library/signal#signal.signal) * [Signature (class in inspect)](library/inspect#inspect.Signature) * [signature (inspect.BoundArguments attribute)](library/inspect#inspect.BoundArguments.signature) * [signature() (in module inspect)](library/inspect#inspect.signature) * [sigpending() (in module signal)](library/signal#signal.sigpending) * [SIGPIPE (in module signal)](library/signal#signal.SIGPIPE) * [SIGSEGV (in module signal)](library/signal#signal.SIGSEGV) * [SIGTERM (in module signal)](library/signal#signal.SIGTERM) * [sigtimedwait() (in module signal)](library/signal#signal.sigtimedwait) * [SIGUSR1 (in module signal)](library/signal#signal.SIGUSR1) * [SIGUSR2 (in module signal)](library/signal#signal.SIGUSR2) * [sigwait() (in module signal)](library/signal#signal.sigwait) * [sigwaitinfo() (in module signal)](library/signal#signal.sigwaitinfo) * [SIGWINCH (in module signal)](library/signal#signal.SIGWINCH) * simple + [statement](reference/simple_stmts#index-0) * [Simple Mail Transfer Protocol](library/smtplib#index-0) * [SimpleCookie (class in http.cookies)](library/http.cookies#http.cookies.SimpleCookie) * [simplefilter() (in module warnings)](library/warnings#warnings.simplefilter) * [SimpleHandler (class in wsgiref.handlers)](library/wsgiref#wsgiref.handlers.SimpleHandler) * [SimpleHTTPRequestHandler (class in http.server)](library/http.server#http.server.SimpleHTTPRequestHandler) * [SimpleNamespace (class in types)](library/types#types.SimpleNamespace) * [SimpleQueue (class in multiprocessing)](library/multiprocessing#multiprocessing.SimpleQueue) + [(class in queue)](library/queue#queue.SimpleQueue) * [SimpleXMLRPCRequestHandler (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCRequestHandler) * [SimpleXMLRPCServer (class in xmlrpc.server)](library/xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer) * [sin() (in module cmath)](library/cmath#cmath.sin) + [(in module math)](library/math#math.sin) * [**single dispatch**](glossary#term-single-dispatch) * [SingleAddressHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.SingleAddressHeader) * [singledispatch() (in module functools)](library/functools#functools.singledispatch) * [singledispatchmethod (class in functools)](library/functools#functools.singledispatchmethod) * singleton + [tuple](reference/datamodel#index-20) * [sinh() (in module cmath)](library/cmath#cmath.sinh) + [(in module math)](library/math#math.sinh) | * [SIO\_KEEPALIVE\_VALS (in module socket)](library/socket#socket.SIO_KEEPALIVE_VALS) * [SIO\_LOOPBACK\_FAST\_PATH (in module socket)](library/socket#socket.SIO_LOOPBACK_FAST_PATH) * [SIO\_RCVALL (in module socket)](library/socket#socket.SIO_RCVALL) * [site (module)](library/site#module-site) * site command line option + [--user-base](library/site#cmdoption-site-user-base) + [--user-site](library/site#cmdoption-site-user-site) * site-packages + [directory](library/site#index-1) * [site\_maps() (urllib.robotparser.RobotFileParser method)](library/urllib.robotparser#urllib.robotparser.RobotFileParser.site_maps) * sitecustomize + [module](library/site#index-5) * [sixtofour (ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.sixtofour) * [size (multiprocessing.shared\_memory.SharedMemory attribute)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory.size) + [(struct.Struct attribute)](library/struct#struct.Struct.size) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.size) + [(tracemalloc.Statistic attribute)](library/tracemalloc#tracemalloc.Statistic.size) + [(tracemalloc.StatisticDiff attribute)](library/tracemalloc#tracemalloc.StatisticDiff.size) + [(tracemalloc.Trace attribute)](library/tracemalloc#tracemalloc.Trace.size) * [size() (ftplib.FTP method)](library/ftplib#ftplib.FTP.size) + [(mmap.mmap method)](library/mmap#mmap.mmap.size) * [size\_diff (tracemalloc.StatisticDiff attribute)](library/tracemalloc#tracemalloc.StatisticDiff.size_diff) * [SIZE\_MAX](c-api/long#index-5) * [Sized (class in collections.abc)](library/collections.abc#collections.abc.Sized) + [(class in typing)](library/typing#typing.Sized) * [sizeof() (in module ctypes)](library/ctypes#ctypes.sizeof) * [SKIP (in module doctest)](library/doctest#doctest.SKIP) * [skip() (chunk.Chunk method)](library/chunk#chunk.Chunk.skip) + [(in module unittest)](library/unittest#unittest.skip) * [skip\_unless\_bind\_unix\_socket() (in module test.support.socket\_helper)](library/test#test.support.socket_helper.skip_unless_bind_unix_socket) * [skip\_unless\_symlink() (in module test.support)](library/test#test.support.skip_unless_symlink) * [skip\_unless\_xattr() (in module test.support)](library/test#test.support.skip_unless_xattr) * [skipIf() (in module unittest)](library/unittest#unittest.skipIf) * [skipinitialspace (csv.Dialect attribute)](library/csv#csv.Dialect.skipinitialspace) * [skipped (unittest.TestResult attribute)](library/unittest#unittest.TestResult.skipped) * [skippedEntity() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.skippedEntity) * [SkipTest](library/unittest#unittest.SkipTest) * [skipTest() (unittest.TestCase method)](library/unittest#unittest.TestCase.skipTest) * [skipUnless() (in module unittest)](library/unittest#unittest.skipUnless) * [SLASH (in module token)](library/token#token.SLASH) * [SLASHEQUAL (in module token)](library/token#token.SLASHEQUAL) * [slave() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.slave) * [sleep() (in module asyncio)](library/asyncio-task#asyncio.sleep) + [(in module time)](library/time#time.sleep) * [slice](reference/expressions#index-44), [**[1]**](glossary#term-slice) + [assignment](library/stdtypes#index-22) + [built-in function](library/dis#index-0), [[1]](reference/datamodel#index-65) + [object](reference/datamodel#index-95) + [operation](library/stdtypes#index-19) * [slice (built-in class)](library/functions#slice) * [Slice (class in ast)](library/ast#ast.Slice) * [slicing](reference/datamodel#index-16), [[1]](reference/datamodel#index-22), [[2]](reference/expressions#index-44) + [assignment](reference/simple_stmts#index-12) * [SMALLEST (in module test.support)](library/test#test.support.SMALLEST) * SMTP + [protocol](library/smtplib#index-0) * [SMTP (class in smtplib)](library/smtplib#smtplib.SMTP) + [(in module email.policy)](library/email.policy#email.policy.SMTP) * [smtp\_server (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.smtp_server) * [SMTP\_SSL (class in smtplib)](library/smtplib#smtplib.SMTP_SSL) * [smtp\_state (smtpd.SMTPChannel attribute)](library/smtpd#smtpd.SMTPChannel.smtp_state) * [SMTPAuthenticationError](library/smtplib#smtplib.SMTPAuthenticationError) * [SMTPChannel (class in smtpd)](library/smtpd#smtpd.SMTPChannel) * [SMTPConnectError](library/smtplib#smtplib.SMTPConnectError) * [smtpd (module)](library/smtpd#module-smtpd) * [SMTPDataError](library/smtplib#smtplib.SMTPDataError) * [SMTPException](library/smtplib#smtplib.SMTPException) * [SMTPHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.SMTPHandler) * [SMTPHeloError](library/smtplib#smtplib.SMTPHeloError) * [smtplib (module)](library/smtplib#module-smtplib) * [SMTPNotSupportedError](library/smtplib#smtplib.SMTPNotSupportedError) * [SMTPRecipientsRefused](library/smtplib#smtplib.SMTPRecipientsRefused) * [SMTPResponseException](library/smtplib#smtplib.SMTPResponseException) * [SMTPSenderRefused](library/smtplib#smtplib.SMTPSenderRefused) * [SMTPServer (class in smtpd)](library/smtpd#smtpd.SMTPServer) * [SMTPServerDisconnected](library/smtplib#smtplib.SMTPServerDisconnected) * [SMTPUTF8 (in module email.policy)](library/email.policy#email.policy.SMTPUTF8) * [Snapshot (class in tracemalloc)](library/tracemalloc#tracemalloc.Snapshot) * [SND\_ALIAS (in module winsound)](library/winsound#winsound.SND_ALIAS) * [SND\_ASYNC (in module winsound)](library/winsound#winsound.SND_ASYNC) * [SND\_FILENAME (in module winsound)](library/winsound#winsound.SND_FILENAME) * [SND\_LOOP (in module winsound)](library/winsound#winsound.SND_LOOP) * [SND\_MEMORY (in module winsound)](library/winsound#winsound.SND_MEMORY) * [SND\_NODEFAULT (in module winsound)](library/winsound#winsound.SND_NODEFAULT) * [SND\_NOSTOP (in module winsound)](library/winsound#winsound.SND_NOSTOP) * [SND\_NOWAIT (in module winsound)](library/winsound#winsound.SND_NOWAIT) * [SND\_PURGE (in module winsound)](library/winsound#winsound.SND_PURGE) * [sndhdr (module)](library/sndhdr#module-sndhdr) * [sni\_callback (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.sni_callback) * [sniff() (csv.Sniffer method)](library/csv#csv.Sniffer.sniff) * [Sniffer (class in csv)](library/csv#csv.Sniffer) * [sock\_accept() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_accept) * [SOCK\_CLOEXEC (in module socket)](library/socket#socket.SOCK_CLOEXEC) * [sock\_connect() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_connect) * [SOCK\_DGRAM (in module socket)](library/socket#socket.SOCK_DGRAM) * [SOCK\_MAX\_SIZE (in module test.support)](library/test#test.support.SOCK_MAX_SIZE) * [SOCK\_NONBLOCK (in module socket)](library/socket#socket.SOCK_NONBLOCK) * [SOCK\_RAW (in module socket)](library/socket#socket.SOCK_RAW) * [SOCK\_RDM (in module socket)](library/socket#socket.SOCK_RDM) * [sock\_recv() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_recv) * [sock\_recv\_into() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_recv_into) * [sock\_sendall() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_sendall) * [sock\_sendfile() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.sock_sendfile) * [SOCK\_SEQPACKET (in module socket)](library/socket#socket.SOCK_SEQPACKET) * [SOCK\_STREAM (in module socket)](library/socket#socket.SOCK_STREAM) * socket + [module](library/internet#index-1) + [object](library/socket#index-0) * [socket (class in socket)](library/socket#socket.socket) + [(module)](library/socket#module-socket) + [(socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.socket) * [socket() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.socket) + [(in module socket)](library/select#index-1) * [socket\_type (socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.socket_type) * [SocketHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.SocketHandler) * [socketpair() (in module socket)](library/socket#socket.socketpair) * [sockets (asyncio.Server attribute)](library/asyncio-eventloop#asyncio.Server.sockets) * [socketserver (module)](library/socketserver#module-socketserver) * [SocketType (in module socket)](library/socket#socket.SocketType) * [softkwlist (in module keyword)](library/keyword#keyword.softkwlist) * [SOL\_ALG (in module socket)](library/socket#socket.SOL_ALG) * [SOL\_RDS (in module socket)](library/socket#socket.SOL_RDS) * [SOMAXCONN (in module socket)](library/socket#socket.SOMAXCONN) * [sort() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.sort) + [(list method)](library/stdtypes#list.sort) * [sort\_stats() (pstats.Stats method)](library/profile#pstats.Stats.sort_stats) * [sortdict() (in module test.support)](library/test#test.support.sortdict) * [sorted() (built-in function)](library/functions#sorted) * [sortTestMethodsUsing (unittest.TestLoader attribute)](library/unittest#unittest.TestLoader.sortTestMethodsUsing) * [source (doctest.Example attribute)](library/doctest#doctest.Example.source) + [(pdb command)](library/pdb#pdbcommand-source) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.source) * [source character set](reference/lexical_analysis#index-5) * [SOURCE\_DATE\_EPOCH](library/compileall#index-1), [[1]](library/py_compile#index-3), [[2]](library/py_compile#index-6), [[3]](library/py_compile#index-7), [[4]](https://docs.python.org/3.9/whatsnew/3.7.html#index-31), [[5]](https://docs.python.org/3.9/whatsnew/changelog.html#index-72), [[6]](https://docs.python.org/3.9/whatsnew/changelog.html#index-88) * [source\_from\_cache() (in module imp)](library/imp#imp.source_from_cache) + [(in module importlib.util)](library/importlib#importlib.util.source_from_cache) * [source\_hash() (in module importlib.util)](library/importlib#importlib.util.source_hash) * [SOURCE\_SUFFIXES (in module importlib.machinery)](library/importlib#importlib.machinery.SOURCE_SUFFIXES) * [source\_to\_code() (importlib.abc.InspectLoader static method)](library/importlib#importlib.abc.InspectLoader.source_to_code) * [SourceFileLoader (class in importlib.machinery)](library/importlib#importlib.machinery.SourceFileLoader) * [sourcehook() (shlex.shlex method)](library/shlex#shlex.shlex.sourcehook) * [SourcelessFileLoader (class in importlib.machinery)](library/importlib#importlib.machinery.SourcelessFileLoader) * [SourceLoader (class in importlib.abc)](library/importlib#importlib.abc.SourceLoader) * [space](reference/lexical_analysis#index-8) + [in printf-style formatting](library/stdtypes#index-35), [[1]](library/stdtypes#index-45) + [in string formatting](library/string#index-4) * [span() (re.Match method)](library/re#re.Match.span) * [spawn() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.spawn) + [(in module pty)](library/pty#pty.spawn) * [spawn\_python() (in module test.support.script\_helper)](library/test#test.support.script_helper.spawn_python) * [spawnl() (in module os)](library/os#os.spawnl) * [spawnle() (in module os)](library/os#os.spawnle) * [spawnlp() (in module os)](library/os#os.spawnlp) * [spawnlpe() (in module os)](library/os#os.spawnlpe) * [spawnv() (in module os)](library/os#os.spawnv) * [spawnve() (in module os)](library/os#os.spawnve) * [spawnvp() (in module os)](library/os#os.spawnvp) * [spawnvpe() (in module os)](library/os#os.spawnvpe) * [spec\_from\_file\_location() (in module importlib.util)](library/importlib#importlib.util.spec_from_file_location) * [spec\_from\_loader() (in module importlib.util)](library/importlib#importlib.util.spec_from_loader) * special + [attribute](reference/datamodel#index-5) + [attribute, generic](reference/datamodel#index-5) + [method](glossary#index-34) * [**special method**](glossary#term-special-method) * [specified\_attributes (xml.parsers.expat.xmlparser attribute)](library/pyexpat#xml.parsers.expat.xmlparser.specified_attributes) * [speed() (in module turtle)](library/turtle#turtle.speed) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.speed) * [Spinbox (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Spinbox) * [split() (bytearray method)](library/stdtypes#bytearray.split) + [(bytes method)](library/stdtypes#bytes.split) + [(in module os.path)](library/os.path#os.path.split) + [(in module re)](library/re#re.split) + [(in module shlex)](library/shlex#shlex.split) + [(re.Pattern method)](library/re#re.Pattern.split) + [(str method)](library/stdtypes#str.split) * [split\_quoted() (in module distutils.util)](distutils/apiref#distutils.util.split_quoted) * [splitdrive() (in module os.path)](library/os.path#os.path.splitdrive) * [splitext() (in module os.path)](library/os.path#os.path.splitext) * [splitlines() (bytearray method)](library/stdtypes#bytearray.splitlines) + [(bytes method)](library/stdtypes#bytes.splitlines) + [(str method)](library/stdtypes#str.splitlines) * [SplitResult (class in urllib.parse)](library/urllib.parse#urllib.parse.SplitResult) * [SplitResultBytes (class in urllib.parse)](library/urllib.parse#urllib.parse.SplitResultBytes) * [SpooledTemporaryFile() (in module tempfile)](library/tempfile#tempfile.SpooledTemporaryFile) * [sprintf-style formatting](library/stdtypes#index-33), [[1]](library/stdtypes#index-43) * [spwd (module)](library/spwd#module-spwd) * [sqlite3 (module)](library/sqlite3#module-sqlite3) * [sqlite\_version (in module sqlite3)](library/sqlite3#sqlite3.sqlite_version) * [sqlite\_version\_info (in module sqlite3)](library/sqlite3#sqlite3.sqlite_version_info) * [sqrt() (decimal.Context method)](library/decimal#decimal.Context.sqrt) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.sqrt) + [(in module cmath)](library/cmath#cmath.sqrt) + [(in module math)](library/math#math.sqrt) * [ssizeargfunc (C type)](c-api/typeobj#c.ssizeargfunc) * [ssizeobjargproc (C type)](c-api/typeobj#c.ssizeobjargproc) * [SSL](library/ssl#index-1) * [ssl (module)](library/ssl#module-ssl) * [SSL\_CERT\_FILE](library/ssl#index-20) * [SSL\_CERT\_PATH](library/ssl#index-21) * [ssl\_version (ftplib.FTP\_TLS attribute)](library/ftplib#ftplib.FTP_TLS.ssl_version) * [SSLCertVerificationError](library/ssl#ssl.SSLCertVerificationError) * [SSLContext (class in ssl)](library/ssl#ssl.SSLContext) * [SSLEOFError](library/ssl#ssl.SSLEOFError) * [SSLError](library/ssl#ssl.SSLError) * [SSLErrorNumber (class in ssl)](library/ssl#ssl.SSLErrorNumber) * [SSLKEYLOGFILE](library/ssl#index-2), [[1]](library/ssl#index-3) * [SSLObject (class in ssl)](library/ssl#ssl.SSLObject) * [sslobject\_class (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.sslobject_class) * [SSLSession (class in ssl)](library/ssl#ssl.SSLSession) * [SSLSocket (class in ssl)](library/ssl#ssl.SSLSocket) * [sslsocket\_class (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.sslsocket_class) * [SSLSyscallError](library/ssl#ssl.SSLSyscallError) * [SSLv3 (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.SSLv3) * [SSLWantReadError](library/ssl#ssl.SSLWantReadError) * [SSLWantWriteError](library/ssl#ssl.SSLWantWriteError) * [SSLZeroReturnError](library/ssl#ssl.SSLZeroReturnError) * [st() (in module turtle)](library/turtle#turtle.st) * [st2list() (in module parser)](library/parser#parser.st2list) * [st2tuple() (in module parser)](library/parser#parser.st2tuple) * [ST\_ATIME (in module stat)](library/stat#stat.ST_ATIME) * [st\_atime (os.stat\_result attribute)](library/os#os.stat_result.st_atime) * [st\_atime\_ns (os.stat\_result attribute)](library/os#os.stat_result.st_atime_ns) * [st\_birthtime (os.stat\_result attribute)](library/os#os.stat_result.st_birthtime) * [st\_blksize (os.stat\_result attribute)](library/os#os.stat_result.st_blksize) * [st\_blocks (os.stat\_result attribute)](library/os#os.stat_result.st_blocks) * [st\_creator (os.stat\_result attribute)](library/os#os.stat_result.st_creator) * [ST\_CTIME (in module stat)](library/stat#stat.ST_CTIME) * [st\_ctime (os.stat\_result attribute)](library/os#os.stat_result.st_ctime) * [st\_ctime\_ns (os.stat\_result attribute)](library/os#os.stat_result.st_ctime_ns) * [ST\_DEV (in module stat)](library/stat#stat.ST_DEV) * [st\_dev (os.stat\_result attribute)](library/os#os.stat_result.st_dev) * [st\_file\_attributes (os.stat\_result attribute)](library/os#os.stat_result.st_file_attributes) * [st\_flags (os.stat\_result attribute)](library/os#os.stat_result.st_flags) * [st\_fstype (os.stat\_result attribute)](library/os#os.stat_result.st_fstype) * [st\_gen (os.stat\_result attribute)](library/os#os.stat_result.st_gen) * [ST\_GID (in module stat)](library/stat#stat.ST_GID) * [st\_gid (os.stat\_result attribute)](library/os#os.stat_result.st_gid) * [ST\_INO (in module stat)](library/stat#stat.ST_INO) * [st\_ino (os.stat\_result attribute)](library/os#os.stat_result.st_ino) * [ST\_MODE (in module stat)](library/stat#stat.ST_MODE) * [st\_mode (os.stat\_result attribute)](library/os#os.stat_result.st_mode) * [ST\_MTIME (in module stat)](library/stat#stat.ST_MTIME) * [st\_mtime (os.stat\_result attribute)](library/os#os.stat_result.st_mtime) * [st\_mtime\_ns (os.stat\_result attribute)](library/os#os.stat_result.st_mtime_ns) * [ST\_NLINK (in module stat)](library/stat#stat.ST_NLINK) * [st\_nlink (os.stat\_result attribute)](library/os#os.stat_result.st_nlink) * [st\_rdev (os.stat\_result attribute)](library/os#os.stat_result.st_rdev) * [st\_reparse\_tag (os.stat\_result attribute)](library/os#os.stat_result.st_reparse_tag) * [st\_rsize (os.stat\_result attribute)](library/os#os.stat_result.st_rsize) * [ST\_SIZE (in module stat)](library/stat#stat.ST_SIZE) * [st\_size (os.stat\_result attribute)](library/os#os.stat_result.st_size) * [st\_type (os.stat\_result attribute)](library/os#os.stat_result.st_type) * [ST\_UID (in module stat)](library/stat#stat.ST_UID) * [st\_uid (os.stat\_result attribute)](library/os#os.stat_result.st_uid) * stack + [execution](reference/datamodel#index-62) + [trace](reference/datamodel#index-62) * [stack (traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.stack) * [stack viewer](library/idle#index-3) * [stack() (in module inspect)](library/inspect#inspect.stack) * [stack\_effect() (in module dis)](library/dis#dis.stack_effect) * [stack\_size() (in module \_thread)](library/_thread#_thread.stack_size) + [(in module threading)](library/threading#threading.stack_size) * stackable + [streams](library/codecs#index-0) * [StackSummary (class in traceback)](library/traceback#traceback.StackSummary) * [stamp() (in module turtle)](library/turtle#turtle.stamp) * standard + [output](reference/simple_stmts#index-3) * [Standard C](reference/lexical_analysis#index-22) * [standard input](reference/toplevel_components#index-4) * [standard\_b64decode() (in module base64)](library/base64#base64.standard_b64decode) * [standard\_b64encode() (in module base64)](library/base64#base64.standard_b64encode) * [standarderror (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-standarderror) * [standend() (curses.window method)](library/curses#curses.window.standend) * [standout() (curses.window method)](library/curses#curses.window.standout) * [STAR (in module token)](library/token#token.STAR) * [STAREQUAL (in module token)](library/token#token.STAREQUAL) * [starmap() (in module itertools)](library/itertools#itertools.starmap) + [(multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.starmap) * [starmap\_async() (multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.starmap_async) * [Starred (class in ast)](library/ast#ast.Starred) * [start (range attribute)](library/stdtypes#range.start) + [(slice object attribute)](reference/datamodel#index-66), [[1]](reference/expressions#index-46) + [(UnicodeError attribute)](library/exceptions#UnicodeError.start) * [start() (in module tracemalloc)](library/tracemalloc#tracemalloc.start) + [(logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.start) + [(multiprocessing.managers.BaseManager method)](library/multiprocessing#multiprocessing.managers.BaseManager.start) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.start) + [(re.Match method)](library/re#re.Match.start) + [(threading.Thread method)](library/threading#threading.Thread.start) + [(tkinter.ttk.Progressbar method)](library/tkinter.ttk#tkinter.ttk.Progressbar.start) + [(xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.start) * [start\_color() (in module curses)](library/curses#curses.start_color) * [start\_component() (msilib.Directory method)](library/msilib#msilib.Directory.start_component) * [start\_new\_thread() (in module \_thread)](library/_thread#_thread.start_new_thread) * [start\_ns() (xml.etree.ElementTree.TreeBuilder method)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder.start_ns) * [start\_server() (in module asyncio)](library/asyncio-stream#asyncio.start_server) * [start\_serving() (asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.start_serving) * [start\_threads() (in module test.support)](library/test#test.support.start_threads) * [start\_tls() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.start_tls) * [start\_unix\_server() (in module asyncio)](library/asyncio-stream#asyncio.start_unix_server) * [StartCdataSectionHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.StartCdataSectionHandler) * [StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler) * [startDocument() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.startDocument) * [startElement() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.startElement) * [StartElementHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.StartElementHandler) * [startElementNS() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.startElementNS) * [STARTF\_USESHOWWINDOW (in module subprocess)](library/subprocess#subprocess.STARTF_USESHOWWINDOW) * [STARTF\_USESTDHANDLES (in module subprocess)](library/subprocess#subprocess.STARTF_USESTDHANDLES) * [startfile() (in module os)](library/os#os.startfile) * [StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler) * [startPrefixMapping() (xml.sax.handler.ContentHandler method)](library/xml.sax.handler#xml.sax.handler.ContentHandler.startPrefixMapping) * [startswith() (bytearray method)](library/stdtypes#bytearray.startswith) + [(bytes method)](library/stdtypes#bytes.startswith) + [(str method)](library/stdtypes#str.startswith) * [startTest() (unittest.TestResult method)](library/unittest#unittest.TestResult.startTest) * [startTestRun() (unittest.TestResult method)](library/unittest#unittest.TestResult.startTestRun) * [starttls() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.starttls) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.starttls) + [(smtplib.SMTP method)](library/smtplib#smtplib.SMTP.starttls) * [STARTUPINFO (class in subprocess)](library/subprocess#subprocess.STARTUPINFO) * stat + [module](library/os#index-24) * [stat (module)](library/stat#module-stat) * [stat() (in module os)](library/os#os.stat) + [(nntplib.NNTP method)](library/nntplib#nntplib.NNTP.stat) + [(os.DirEntry method)](library/os#os.DirEntry.stat) + [(pathlib.Path method)](library/pathlib#pathlib.Path.stat) + [(poplib.POP3 method)](library/poplib#poplib.POP3.stat) * [stat\_result (class in os)](library/os#os.stat_result) * [state() (tkinter.ttk.Widget method)](library/tkinter.ttk#tkinter.ttk.Widget.state) * [**statement**](glossary#term-statement) + [assert](library/exceptions#index-2), [**[1]**](reference/simple_stmts#index-18) + [assignment](reference/datamodel#index-22), [[1]](reference/simple_stmts#index-4) + [assignment, annotated](reference/simple_stmts#index-15) + [assignment, augmented](reference/simple_stmts#index-14) + [async def](reference/compound_stmts#index-37) + [async for](reference/compound_stmts#index-39) + [async with](reference/compound_stmts#index-40) + [break](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [[2]](reference/compound_stmts#index-5), [[3]](reference/compound_stmts#index-7), [**[4]**](reference/simple_stmts#index-30) + [class](reference/compound_stmts#index-31) + [compound](reference/compound_stmts#index-0) + [continue](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [[2]](reference/compound_stmts#index-5), [[3]](reference/compound_stmts#index-7), [**[4]**](reference/simple_stmts#index-33) + [def](reference/compound_stmts#index-19) + [del](library/stdtypes#index-22), [[1]](library/stdtypes#index-50), [[2]](reference/datamodel#index-70), [**[3]**](reference/simple_stmts#index-21) + [except](library/exceptions#index-0) + [expression](reference/simple_stmts#index-1) + [for](reference/simple_stmts#index-30), [[1]](reference/simple_stmts#index-33), [[2]](tutorial/controlflow#index-0), [**[3]**](reference/compound_stmts#index-6) + [future](reference/simple_stmts#index-40) + [global](reference/simple_stmts#index-22), [**[1]**](reference/simple_stmts#index-43) + [if](library/stdtypes#index-1), [**[1]**](reference/compound_stmts#index-3) + [import](library/functions#index-12), [[1]](library/imp#index-0), [[2]](library/site#index-2), [[3]](reference/datamodel#index-42), [**[4]**](reference/simple_stmts#index-34) + [loop](reference/compound_stmts#index-4), [[1]](reference/compound_stmts#index-6), [[2]](reference/simple_stmts#index-30), [[3]](reference/simple_stmts#index-33) + [nonlocal](reference/simple_stmts#index-45) + [pass](reference/simple_stmts#index-20) + [raise](library/exceptions#index-1), [**[1]**](reference/simple_stmts#index-27) + [return](reference/compound_stmts#index-13), [[1]](reference/compound_stmts#index-15), [**[2]**](reference/simple_stmts#index-24) + [simple](reference/simple_stmts#index-0) + [try](library/exceptions#index-0), [[1]](reference/datamodel#index-63), [**[2]**](reference/compound_stmts#index-10) + [while](library/stdtypes#index-1), [[1]](reference/simple_stmts#index-30), [[2]](reference/simple_stmts#index-33), [**[3]**](reference/compound_stmts#index-4) + [with](reference/datamodel#index-102), [**[1]**](reference/compound_stmts#index-16) + [yield](reference/simple_stmts#index-26) * [statement grouping](reference/lexical_analysis#index-8) * [static\_order() (graphlib.TopologicalSorter method)](library/graphlib#graphlib.TopologicalSorter.static_order) * staticmethod + [built-in function](c-api/structures#index-1) * [staticmethod() (built-in function)](library/functions#staticmethod) * [Statistic (class in tracemalloc)](library/tracemalloc#tracemalloc.Statistic) * [StatisticDiff (class in tracemalloc)](library/tracemalloc#tracemalloc.StatisticDiff) * [statistics (module)](library/statistics#module-statistics) * [statistics() (tracemalloc.Snapshot method)](library/tracemalloc#tracemalloc.Snapshot.statistics) * [StatisticsError](library/statistics#statistics.StatisticsError) * [Stats (class in pstats)](library/profile#pstats.Stats) * [status (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.status) + [(urllib.response.addinfourl attribute)](library/urllib.request#urllib.response.addinfourl.status) * [status() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.status) * [statvfs() (in module os)](library/os#os.statvfs) * [STD\_ERROR\_HANDLE (in module subprocess)](library/subprocess#subprocess.STD_ERROR_HANDLE) * [STD\_INPUT\_HANDLE (in module subprocess)](library/subprocess#subprocess.STD_INPUT_HANDLE) * [STD\_OUTPUT\_HANDLE (in module subprocess)](library/subprocess#subprocess.STD_OUTPUT_HANDLE) * [StdButtonBox (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.StdButtonBox) * [stderr (asyncio.subprocess.Process attribute)](library/asyncio-subprocess#asyncio.subprocess.Process.stderr) + [(in module sys)](c-api/init#index-42), [[1]](library/sys#sys.stderr), [[2]](reference/datamodel#index-53) + [(subprocess.CalledProcessError attribute)](library/subprocess#subprocess.CalledProcessError.stderr) + [(subprocess.CompletedProcess attribute)](library/subprocess#subprocess.CompletedProcess.stderr) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.stderr) + [(subprocess.TimeoutExpired attribute)](library/subprocess#subprocess.TimeoutExpired.stderr) * [stdev (statistics.NormalDist attribute)](library/statistics#statistics.NormalDist.stdev) * [stdev() (in module statistics)](library/statistics#statistics.stdev) * stdin + [stdout sdterr](c-api/init#index-17) * [stdin (asyncio.subprocess.Process attribute)](library/asyncio-subprocess#asyncio.subprocess.Process.stdin) + [(in module sys)](c-api/init#index-42), [[1]](library/sys#sys.stdin), [[2]](reference/datamodel#index-53) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.stdin) * [stdio](reference/datamodel#index-53) * stdout + [sdterr, stdin](c-api/init#index-17) * [stdout (asyncio.subprocess.Process attribute)](library/asyncio-subprocess#asyncio.subprocess.Process.stdout) * [STDOUT (in module subprocess)](library/subprocess#subprocess.STDOUT) * [stdout (in module sys)](c-api/init#index-42), [[1]](library/sys#sys.stdout), [[2]](reference/datamodel#index-53) + [(subprocess.CalledProcessError attribute)](library/subprocess#subprocess.CalledProcessError.stdout) + [(subprocess.CompletedProcess attribute)](library/subprocess#subprocess.CompletedProcess.stdout) + [(subprocess.Popen attribute)](library/subprocess#subprocess.Popen.stdout) + [(subprocess.TimeoutExpired attribute)](library/subprocess#subprocess.TimeoutExpired.stdout) * [step (pdb command)](library/pdb#pdbcommand-step) + [(range attribute)](library/stdtypes#range.step) + [(slice object attribute)](reference/datamodel#index-66), [[1]](reference/expressions#index-46) * [step() (tkinter.ttk.Progressbar method)](library/tkinter.ttk#tkinter.ttk.Progressbar.step) * [stereocontrols() (ossaudiodev.oss\_mixer\_device method)](library/ossaudiodev#ossaudiodev.oss_mixer_device.stereocontrols) * [stls() (poplib.POP3 method)](library/poplib#poplib.POP3.stls) * [stop (range attribute)](library/stdtypes#range.stop) + [(slice object attribute)](reference/datamodel#index-66), [[1]](reference/expressions#index-46) * [stop() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.stop) + [(in module tracemalloc)](library/tracemalloc#tracemalloc.stop) + [(logging.handlers.QueueListener method)](library/logging.handlers#logging.handlers.QueueListener.stop) + [(tkinter.ttk.Progressbar method)](library/tkinter.ttk#tkinter.ttk.Progressbar.stop) + [(unittest.TestResult method)](library/unittest#unittest.TestResult.stop) * [stop\_here() (bdb.Bdb method)](library/bdb#bdb.Bdb.stop_here) * [StopAsyncIteration](library/exceptions#StopAsyncIteration) + [exception](reference/expressions#index-36) * [StopIteration](library/exceptions#StopIteration) + [exception](reference/expressions#index-32), [[1]](reference/simple_stmts#index-26) * [stopListening() (in module logging.config)](library/logging.config#logging.config.stopListening) * [stopTest() (unittest.TestResult method)](library/unittest#unittest.TestResult.stopTest) * [stopTestRun() (unittest.TestResult method)](library/unittest#unittest.TestResult.stopTestRun) * [storbinary() (ftplib.FTP method)](library/ftplib#ftplib.FTP.storbinary) * [Store (class in ast)](library/ast#ast.Store) * [store() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.store) * [STORE\_ACTIONS (optparse.Option attribute)](library/optparse#optparse.Option.STORE_ACTIONS) * [STORE\_ATTR (opcode)](library/dis#opcode-STORE_ATTR) * [STORE\_DEREF (opcode)](library/dis#opcode-STORE_DEREF) * [STORE\_FAST (opcode)](library/dis#opcode-STORE_FAST) * [STORE\_GLOBAL (opcode)](library/dis#opcode-STORE_GLOBAL) * [STORE\_NAME (opcode)](library/dis#opcode-STORE_NAME) * [STORE\_SUBSCR (opcode)](library/dis#opcode-STORE_SUBSCR) * [storlines() (ftplib.FTP method)](library/ftplib#ftplib.FTP.storlines) * [str (built-in class)](library/stdtypes#str) + [(see also string)](library/stdtypes#index-26) * [str() (in module locale)](library/locale#locale.str) * [strcoll() (in module locale)](library/locale#locale.strcoll) * [StreamError](library/tarfile#tarfile.StreamError) * [StreamHandler (class in logging)](library/logging.handlers#logging.StreamHandler) * [StreamReader (class in asyncio)](library/asyncio-stream#asyncio.StreamReader) + [(class in codecs)](library/codecs#codecs.StreamReader) * [streamreader (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.streamreader) * [StreamReaderWriter (class in codecs)](library/codecs#codecs.StreamReaderWriter) * [StreamRecoder (class in codecs)](library/codecs#codecs.StreamRecoder) * [StreamRequestHandler (class in socketserver)](library/socketserver#socketserver.StreamRequestHandler) * [streams](library/codecs#index-0) + [stackable](library/codecs#index-0) * [StreamWriter (class in asyncio)](library/asyncio-stream#asyncio.StreamWriter) + [(class in codecs)](library/codecs#codecs.StreamWriter) * [streamwriter (codecs.CodecInfo attribute)](library/codecs#codecs.CodecInfo.streamwriter) * [strerror (OSError attribute)](library/exceptions#OSError.strerror) * [strerror()](c-api/exceptions#index-0) + [(in module os)](library/os#os.strerror) * [strftime() (datetime.date method)](library/datetime#datetime.date.strftime) + [(datetime.datetime method)](library/datetime#datetime.datetime.strftime) + [(datetime.time method)](library/datetime#datetime.time.strftime) + [(in module time)](library/time#time.strftime) * strict + [error handler's name](library/codecs#index-1) * [strict (csv.Dialect attribute)](library/csv#csv.Dialect.strict) + [(in module email.policy)](library/email.policy#email.policy.strict) * [strict\_domain (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_domain) * [strict\_errors() (in module codecs)](library/codecs#codecs.strict_errors) * [strict\_ns\_domain (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_domain) * [strict\_ns\_set\_initial\_dollar (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_set_initial_dollar) * [strict\_ns\_set\_path (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_set_path) * [strict\_ns\_unverifiable (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_unverifiable) * [strict\_rfc2965\_unverifiable (http.cookiejar.DefaultCookiePolicy attribute)](library/http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_rfc2965_unverifiable) * [strides (memoryview attribute)](library/stdtypes#memoryview.strides) * string + [\_\_format\_\_() (object method)](reference/datamodel#index-74) + [\_\_str\_\_() (object method)](reference/datamodel#index-72) + [conversion](reference/datamodel#index-74), [[1]](reference/simple_stmts#index-3) + [format() (built-in function)](library/functions#index-3) + [formatted literal](reference/lexical_analysis#index-24) + [formatting, printf](library/stdtypes#index-33) + [immutable sequences](reference/datamodel#index-18) + [interpolated literal](reference/lexical_analysis#index-24) + [interpolation, printf](library/stdtypes#index-33) + [item](reference/expressions#index-43) + [methods](library/stdtypes#index-30) + [module](library/locale#index-6) + [object](library/stdtypes#index-26), [[1]](reference/expressions#index-42), [[2]](reference/expressions#index-45) + [object representation](extending/newtypes#index-3) + [PyObject\_Str (C function)](c-api/object#index-2) + [str (built-in class)](library/stdtypes#index-28) + [str() (built-in function)](library/functions#index-10) + [text sequence type](library/stdtypes#index-26) * [STRING (in module token)](library/token#token.STRING) * [string (module)](library/string#module-string) + [(re.Match attribute)](library/re#re.Match.string) * [string literal](reference/lexical_analysis#index-16) * [string\_at() (in module ctypes)](library/ctypes#ctypes.string_at) * [StringIO (class in io)](library/io#io.StringIO) * [stringprep (module)](library/stringprep#module-stringprep) * [strings, documentation](tutorial/controlflow#index-1), [[1]](tutorial/controlflow#index-4) * [strip() (bytearray method)](library/stdtypes#bytearray.strip) + [(bytes method)](library/stdtypes#bytes.strip) + [(str method)](library/stdtypes#str.strip) * [strip\_dirs() (pstats.Stats method)](library/profile#pstats.Stats.strip_dirs) * [stripspaces (curses.textpad.Textbox attribute)](library/curses#curses.textpad.Textbox.stripspaces) * [strptime() (datetime.datetime class method)](library/datetime#datetime.datetime.strptime) + [(in module time)](library/time#time.strptime) * [strsignal() (in module signal)](library/signal#signal.strsignal) * [strtobool() (in module distutils.util)](distutils/apiref#distutils.util.strtobool) * struct + [module](library/socket#index-14) * [Struct (class in struct)](library/struct#struct.Struct) * [struct (module)](library/struct#module-struct) * [struct\_time (class in time)](library/time#time.struct_time) * [Structure (class in ctypes)](library/ctypes#ctypes.Structure) * structures + [C](library/struct#index-0) * [strxfrm() (in module locale)](library/locale#locale.strxfrm) * [STType (in module parser)](library/parser#parser.STType) * style + [coding](tutorial/controlflow#index-8) * [Style (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Style) * [Sub (class in ast)](library/ast#ast.Sub) * [sub() (in module operator)](library/operator#operator.sub) + [(in module re)](library/re#re.sub) + [(re.Pattern method)](library/re#re.Pattern.sub) * [sub\_commands (distutils.cmd.Command attribute)](distutils/apiref#distutils.cmd.Command.sub_commands) * subclassing + [immutable types](reference/datamodel#index-68) * [subdirs (filecmp.dircmp attribute)](library/filecmp#filecmp.dircmp.subdirs) * [SubElement() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.SubElement) * [submit() (concurrent.futures.Executor method)](library/concurrent.futures#concurrent.futures.Executor.submit) * [submodule\_search\_locations (importlib.machinery.ModuleSpec attribute)](library/importlib#importlib.machinery.ModuleSpec.submodule_search_locations) * [subn() (in module re)](library/re#re.subn) + [(re.Pattern method)](library/re#re.Pattern.subn) * [subnet\_of() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.subnet_of) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.subnet_of) * [subnets() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.subnets) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.subnets) * [Subnormal (class in decimal)](library/decimal#decimal.Subnormal) * [suboffsets (memoryview attribute)](library/stdtypes#memoryview.suboffsets) * [subpad() (curses.window method)](library/curses#curses.window.subpad) * [subprocess (module)](library/subprocess#module-subprocess) * [subprocess\_exec() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.subprocess_exec) * [subprocess\_shell() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.subprocess_shell) * [SubprocessError](library/subprocess#subprocess.SubprocessError) * [SubprocessProtocol (class in asyncio)](library/asyncio-protocol#asyncio.SubprocessProtocol) * [SubprocessTransport (class in asyncio)](library/asyncio-protocol#asyncio.SubprocessTransport) * [subscribe() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.subscribe) * subscript + [assignment](library/stdtypes#index-22) + [operation](library/stdtypes#index-19) * [Subscript (class in ast)](library/ast#ast.Subscript) * [subscription](reference/datamodel#index-15), [[1]](reference/datamodel#index-22), [[2]](reference/datamodel#index-29), [[3]](reference/expressions#index-41) + [assignment](reference/simple_stmts#index-9) * [subsequent\_indent (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.subsequent_indent) * [subst\_vars() (in module distutils.util)](distutils/apiref#distutils.util.subst_vars) * [substitute() (string.Template method)](library/string#string.Template.substitute) * [subTest() (unittest.TestCase method)](library/unittest#unittest.TestCase.subTest) * [subtract() (collections.Counter method)](library/collections#collections.Counter.subtract) + [(decimal.Context method)](library/decimal#decimal.Context.subtract) * [subtraction](reference/expressions#index-70) * [subtype (email.headerregistry.ContentTypeHeader attribute)](library/email.headerregistry#email.headerregistry.ContentTypeHeader.subtype) * [subwin() (curses.window method)](library/curses#curses.window.subwin) * [successful() (multiprocessing.pool.AsyncResult method)](library/multiprocessing#multiprocessing.pool.AsyncResult.successful) * [suffix\_map (in module mimetypes)](library/mimetypes#mimetypes.suffix_map) + [(mimetypes.MimeTypes attribute)](library/mimetypes#mimetypes.MimeTypes.suffix_map) * [suite](reference/compound_stmts#index-1) * [suite() (in module parser)](library/parser#parser.suite) * [suiteClass (unittest.TestLoader attribute)](library/unittest#unittest.TestLoader.suiteClass) * [sum() (built-in function)](library/functions#sum) * [sum\_list()](c-api/intro#index-13) * [sum\_sequence()](c-api/intro#index-14), [[1]](c-api/intro#index-19) * [summarize() (doctest.DocTestRunner method)](library/doctest#doctest.DocTestRunner.summarize) * [summarize\_address\_range() (in module ipaddress)](library/ipaddress#ipaddress.summarize_address_range) * [sunau (module)](https://docs.python.org/3.9/library/sunau.html#module-sunau) * [super (pyclbr.Class attribute)](library/pyclbr#pyclbr.Class.super) * [super() (built-in function)](library/functions#super) * [supernet() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.supernet) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.supernet) * [supernet\_of() (ipaddress.IPv4Network method)](library/ipaddress#ipaddress.IPv4Network.supernet_of) + [(ipaddress.IPv6Network method)](library/ipaddress#ipaddress.IPv6Network.supernet_of) * [supports\_bytes\_environ (in module os)](library/os#os.supports_bytes_environ) * [supports\_dir\_fd (in module os)](library/os#os.supports_dir_fd) * [supports\_effective\_ids (in module os)](library/os#os.supports_effective_ids) * [supports\_fd (in module os)](library/os#os.supports_fd) * [supports\_follow\_symlinks (in module os)](library/os#os.supports_follow_symlinks) * [supports\_unicode\_filenames (in module os.path)](library/os.path#os.path.supports_unicode_filenames) * [SupportsAbs (class in typing)](library/typing#typing.SupportsAbs) * [SupportsBytes (class in typing)](library/typing#typing.SupportsBytes) * [SupportsComplex (class in typing)](library/typing#typing.SupportsComplex) * [SupportsFloat (class in typing)](library/typing#typing.SupportsFloat) * [SupportsIndex (class in typing)](library/typing#typing.SupportsIndex) * [SupportsInt (class in typing)](library/typing#typing.SupportsInt) * [SupportsRound (class in typing)](library/typing#typing.SupportsRound) * [suppress() (in module contextlib)](library/contextlib#contextlib.suppress) * [SuppressCrashReport (class in test.support)](library/test#test.support.SuppressCrashReport) * surrogateescape + [error handler's name](library/codecs#index-1) * surrogatepass + [error handler's name](library/codecs#index-4) * [SW\_HIDE (in module subprocess)](library/subprocess#subprocess.SW_HIDE) * [swap\_attr() (in module test.support)](library/test#test.support.swap_attr) * [swap\_item() (in module test.support)](library/test#test.support.swap_item) * [swapcase() (bytearray method)](library/stdtypes#bytearray.swapcase) + [(bytes method)](library/stdtypes#bytes.swapcase) + [(str method)](library/stdtypes#str.swapcase) * [sym\_name (in module symbol)](library/symbol#symbol.sym_name) * [Symbol (class in symtable)](library/symtable#symtable.Symbol) * [symbol (module)](library/symbol#module-symbol) * [SymbolTable (class in symtable)](library/symtable#symtable.SymbolTable) * [symlink() (in module os)](library/os#os.symlink) * [symlink\_to() (pathlib.Path method)](library/pathlib#pathlib.Path.symlink_to) * [symmetric\_difference() (frozenset method)](library/stdtypes#frozenset.symmetric_difference) * [symmetric\_difference\_update() (frozenset method)](library/stdtypes#frozenset.symmetric_difference_update) * [symtable (module)](library/symtable#module-symtable) * [symtable() (in module symtable)](library/symtable#symtable.symtable) * [sync() (dbm.dumb.dumbdbm method)](library/dbm#dbm.dumb.dumbdbm.sync) + [(dbm.gnu.gdbm method)](library/dbm#dbm.gnu.gdbm.sync) + [(in module os)](library/os#os.sync) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.sync) + [(shelve.Shelf method)](library/shelve#shelve.Shelf.sync) * [syncdown() (curses.window method)](library/curses#curses.window.syncdown) * [synchronized() (in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.synchronized) * [SyncManager (class in multiprocessing.managers)](library/multiprocessing#multiprocessing.managers.SyncManager) * [syncok() (curses.window method)](library/curses#curses.window.syncok) * [syncup() (curses.window method)](library/curses#curses.window.syncup) * [syntax](reference/introduction#index-0) * [SyntaxErr](library/xml.dom#xml.dom.SyntaxErr) * [SyntaxError](library/exceptions#SyntaxError) * [SyntaxWarning](library/exceptions#SyntaxWarning) * sys + [module](c-api/init#index-16), [[1]](c-api/init#index-42), [[2]](c-api/intro#index-23), [[3]](library/functions#index-7), [[4]](reference/compound_stmts#index-12), [[5]](reference/toplevel_components#index-2), [[6]](tutorial/modules#index-4) * [sys (module)](library/sys#module-sys) * [sys.exc\_info](reference/datamodel#index-62) * [sys.last\_traceback](reference/datamodel#index-62) * [sys.meta\_path](reference/import#index-10) * [sys.modules](reference/import#index-7) * [sys.path](reference/import#index-17) * [sys.path\_hooks](reference/import#index-17) * [sys.path\_importer\_cache](reference/import#index-17) * [sys.stderr](reference/datamodel#index-53) * [sys.stdin](reference/datamodel#index-53) * [sys.stdout](reference/datamodel#index-53) * [sys\_exc (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-sys_exc) * [sys\_version (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.sys_version) * [sysconf() (in module os)](library/os#os.sysconf) * [sysconf\_names (in module os)](library/os#os.sysconf_names) * [sysconfig (module)](library/sysconfig#module-sysconfig) * [syslog (module)](library/syslog#module-syslog) * [syslog() (in module syslog)](library/syslog#syslog.syslog) * [SysLogHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.SysLogHandler) * [system() (in module os)](library/os#os.system) + [(in module platform)](library/platform#platform.system) * [system\_alias() (in module platform)](library/platform#platform.system_alias) * [system\_must\_validate\_cert() (in module test.support)](library/test#test.support.system_must_validate_cert) * [SystemError](library/exceptions#SystemError) + [(built-in exception)](c-api/module#index-4), [[1]](c-api/module#index-5) * [SystemExit](library/exceptions#SystemExit) + [(built-in exception)](reference/executionmodel#index-15) * [systemId (xml.dom.DocumentType attribute)](library/xml.dom#xml.dom.DocumentType.systemId) * [SystemRandom (class in random)](library/random#random.SystemRandom) + [(class in secrets)](library/secrets#secrets.SystemRandom) * [SystemRoot](library/subprocess#index-3) | T - | | | | --- | --- | | * [T\_FMT (in module locale)](library/locale#locale.T_FMT) * [T\_FMT\_AMPM (in module locale)](library/locale#locale.T_FMT_AMPM) * [tab](reference/lexical_analysis#index-8) * [tab() (tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.tab) * [TabError](library/exceptions#TabError) * [tabnanny (module)](library/tabnanny#module-tabnanny) * [tabs() (tkinter.ttk.Notebook method)](library/tkinter.ttk#tkinter.ttk.Notebook.tabs) * [tabsize (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.tabsize) * tabular + [data](library/csv#index-0) * [tag (xml.etree.ElementTree.Element attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.tag) * [tag\_bind() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.tag_bind) * [tag\_configure() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.tag_configure) * [tag\_has() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.tag_has) * [tagName (xml.dom.Element attribute)](library/xml.dom#xml.dom.Element.tagName) * [tail (xml.etree.ElementTree.Element attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.tail) * [take\_snapshot() (in module tracemalloc)](library/tracemalloc#tracemalloc.take_snapshot) * [takewhile() (in module itertools)](library/itertools#itertools.takewhile) * [tan() (in module cmath)](library/cmath#cmath.tan) + [(in module math)](library/math#math.tan) * [tanh() (in module cmath)](library/cmath#cmath.tanh) + [(in module math)](library/math#math.tanh) * [TarError](library/tarfile#tarfile.TarError) * [TarFile (class in tarfile)](library/tarfile#tarfile.TarFile) * [tarfile (module)](library/tarfile#module-tarfile) * tarfile command line option + [--create <tarfile> <source1> ... <sourceN>](library/tarfile#cmdoption-tarfile-create) + [--extract <tarfile> [<output\_dir>]](library/tarfile#cmdoption-tarfile-extract) + [--list <tarfile>](library/tarfile#cmdoption-tarfile-list) + [--test <tarfile>](library/tarfile#cmdoption-tarfile-test) + [--verbose](library/tarfile#cmdoption-tarfile-v) + [-c <tarfile> <source1> ... <sourceN>](library/tarfile#cmdoption-tarfile-c) + [-e <tarfile> [<output\_dir>]](library/tarfile#cmdoption-tarfile-e) + [-l <tarfile>](library/tarfile#cmdoption-tarfile-l) + [-t <tarfile>](library/tarfile#cmdoption-tarfile-t) + [-v](library/tarfile#cmdoption-tarfile-v) * [target](reference/simple_stmts#index-5) + [deletion](reference/simple_stmts#index-21) + [list](reference/compound_stmts#index-6), [[1]](reference/simple_stmts#index-5) + [list assignment](reference/simple_stmts#index-6) + [list, deletion](reference/simple_stmts#index-21) + [loop control](reference/simple_stmts#index-31) * [target (xml.dom.ProcessingInstruction attribute)](library/xml.dom#xml.dom.ProcessingInstruction.target) * [TarInfo (class in tarfile)](library/tarfile#tarfile.TarInfo) * [Task (class in asyncio)](library/asyncio-task#asyncio.Task) * [task\_done() (asyncio.Queue method)](library/asyncio-queue#asyncio.Queue.task_done) + [(multiprocessing.JoinableQueue method)](library/multiprocessing#multiprocessing.JoinableQueue.task_done) + [(queue.Queue method)](library/queue#queue.Queue.task_done) * [tau (in module cmath)](library/cmath#cmath.tau) + [(in module math)](library/math#math.tau) * [tb\_frame (traceback attribute)](reference/datamodel#index-63) * [tb\_lasti (traceback attribute)](reference/datamodel#index-63) * [tb\_lineno (traceback attribute)](reference/datamodel#index-63) * [tb\_locals (unittest.TestResult attribute)](library/unittest#unittest.TestResult.tb_locals) * [tb\_next (traceback attribute)](reference/datamodel#index-64) * [tbreak (pdb command)](library/pdb#pdbcommand-tbreak) * [tcdrain() (in module termios)](library/termios#termios.tcdrain) * [tcflow() (in module termios)](library/termios#termios.tcflow) * [tcflush() (in module termios)](library/termios#termios.tcflush) * [tcgetattr() (in module termios)](library/termios#termios.tcgetattr) * [tcgetpgrp() (in module os)](library/os#os.tcgetpgrp) * [Tcl() (in module tkinter)](library/tkinter#tkinter.Tcl) * [TCL\_LIBRARY](faq/gui#index-0) * [TCPServer (class in socketserver)](library/socketserver#socketserver.TCPServer) * [tcsendbreak() (in module termios)](library/termios#termios.tcsendbreak) * [tcsetattr() (in module termios)](library/termios#termios.tcsetattr) * [tcsetpgrp() (in module os)](library/os#os.tcsetpgrp) * [tearDown() (unittest.TestCase method)](library/unittest#unittest.TestCase.tearDown) * [tearDownClass() (unittest.TestCase method)](library/unittest#unittest.TestCase.tearDownClass) * [tee() (in module itertools)](library/itertools#itertools.tee) * [tell() (aifc.aifc method)](library/aifc#aifc.aifc.tell) + [(chunk.Chunk method)](library/chunk#chunk.Chunk.tell) + [(io.IOBase method)](library/io#io.IOBase.tell) + [(io.TextIOBase method)](library/io#io.TextIOBase.tell) + [(mmap.mmap method)](library/mmap#mmap.mmap.tell) + [(sunau.AU\_read method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_read.tell) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.tell) + [(wave.Wave\_read method)](library/wave#wave.Wave_read.tell) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.tell) * [Telnet (class in telnetlib)](library/telnetlib#telnetlib.Telnet) * [telnetlib (module)](library/telnetlib#module-telnetlib) * [TEMP](library/tempfile#index-2) * [temp\_cwd() (in module test.support)](library/test#test.support.temp_cwd) * [temp\_dir() (in module test.support)](library/test#test.support.temp_dir) * [temp\_umask() (in module test.support)](library/test#test.support.temp_umask) * [tempdir (in module tempfile)](library/tempfile#tempfile.tempdir) * [tempfile (module)](library/tempfile#module-tempfile) * [Template (class in pipes)](library/pipes#pipes.Template) + [(class in string)](library/string#string.Template) * [template (string.Template attribute)](library/string#string.Template.template) * temporary + [file](library/tempfile#index-0) + [file name](library/tempfile#index-0) * [TemporaryDirectory() (in module tempfile)](library/tempfile#tempfile.TemporaryDirectory) * [TemporaryFile() (in module tempfile)](library/tempfile#tempfile.TemporaryFile) * [teredo (ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.teredo) * [TERM](library/curses#index-1), [[1]](library/curses#index-2) * [termattrs() (in module curses)](library/curses#curses.termattrs) * [terminal\_size (class in os)](library/os#os.terminal_size) * [terminate() (asyncio.subprocess.Process method)](library/asyncio-subprocess#asyncio.subprocess.Process.terminate) + [(asyncio.SubprocessTransport method)](library/asyncio-protocol#asyncio.SubprocessTransport.terminate) + [(multiprocessing.pool.Pool method)](library/multiprocessing#multiprocessing.pool.Pool.terminate) + [(multiprocessing.Process method)](library/multiprocessing#multiprocessing.Process.terminate) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.terminate) * [termination model](reference/executionmodel#index-14) * [terminator (logging.StreamHandler attribute)](library/logging.handlers#logging.StreamHandler.terminator) * [termios (module)](library/termios#module-termios) * [termname() (in module curses)](library/curses#curses.termname) * ternary + [operator](reference/expressions#index-87) * [ternaryfunc (C type)](c-api/typeobj#c.ternaryfunc) * test + [identity](reference/expressions#index-81) + [membership](reference/expressions#index-80) * [test (doctest.DocTestFailure attribute)](library/doctest#doctest.DocTestFailure.test) + [(doctest.UnexpectedException attribute)](library/doctest#doctest.UnexpectedException.test) + [(module)](library/test#module-test) * [test() (in module cgi)](library/cgi#cgi.test) * [test.support (module)](library/test#module-test.support) * [test.support.bytecode\_helper (module)](library/test#module-test.support.bytecode_helper) * [test.support.script\_helper (module)](library/test#module-test.support.script_helper) * [test.support.socket\_helper (module)](library/test#module-test.support.socket_helper) * [TEST\_DATA\_DIR (in module test.support)](library/test#test.support.TEST_DATA_DIR) * [TEST\_HOME\_DIR (in module test.support)](library/test#test.support.TEST_HOME_DIR) * [TEST\_HTTP\_URL (in module test.support)](library/test#test.support.TEST_HTTP_URL) * [TEST\_SUPPORT\_DIR (in module test.support)](library/test#test.support.TEST_SUPPORT_DIR) * [TestCase (class in unittest)](library/unittest#unittest.TestCase) * [TestFailed](library/test#test.support.TestFailed) * [testfile() (in module doctest)](library/doctest#doctest.testfile) * [TESTFN (in module test.support)](library/test#test.support.TESTFN) * [TESTFN\_ENCODING (in module test.support)](library/test#test.support.TESTFN_ENCODING) * [TESTFN\_NONASCII (in module test.support)](library/test#test.support.TESTFN_NONASCII) * [TESTFN\_UNDECODABLE (in module test.support)](library/test#test.support.TESTFN_UNDECODABLE) * [TESTFN\_UNENCODABLE (in module test.support)](library/test#test.support.TESTFN_UNENCODABLE) * [TESTFN\_UNICODE (in module test.support)](library/test#test.support.TESTFN_UNICODE) * [TestLoader (class in unittest)](library/unittest#unittest.TestLoader) * [testMethodPrefix (unittest.TestLoader attribute)](library/unittest#unittest.TestLoader.testMethodPrefix) * [testmod() (in module doctest)](library/doctest#doctest.testmod) * [testNamePatterns (unittest.TestLoader attribute)](library/unittest#unittest.TestLoader.testNamePatterns) * [TestResult (class in unittest)](library/unittest#unittest.TestResult) * [tests (in module imghdr)](library/imghdr#imghdr.tests) * [testsource() (in module doctest)](library/doctest#doctest.testsource) * [testsRun (unittest.TestResult attribute)](library/unittest#unittest.TestResult.testsRun) * [TestSuite (class in unittest)](library/unittest#unittest.TestSuite) * [testzip() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.testzip) * [Text (class in typing)](library/typing#typing.Text) * [text (in module msilib)](library/msilib#msilib.text) + [(SyntaxError attribute)](library/exceptions#SyntaxError.text) + [(traceback.TracebackException attribute)](library/traceback#traceback.TracebackException.text) + [(xml.etree.ElementTree.Element attribute)](library/xml.etree.elementtree#xml.etree.ElementTree.Element.text) * [**text encoding**](glossary#term-text-encoding) * [**text file**](glossary#term-text-file) * [text mode](library/functions#index-7) * [text() (in module cgitb)](library/cgitb#cgitb.text) + [(msilib.Dialog method)](library/msilib#msilib.Dialog.text) * [text\_factory (sqlite3.Connection attribute)](library/sqlite3#sqlite3.Connection.text_factory) * [Textbox (class in curses.textpad)](library/curses#curses.textpad.Textbox) * [TextCalendar (class in calendar)](library/calendar#calendar.TextCalendar) * [textdomain() (in module gettext)](library/gettext#gettext.textdomain) + [(in module locale)](library/locale#locale.textdomain) * [TextFile (class in distutils.text\_file)](distutils/apiref#distutils.text_file.TextFile) * [textinput() (in module turtle)](library/turtle#turtle.textinput) * [TextIO (class in typing)](library/typing#typing.TextIO) * [TextIOBase (class in io)](library/io#io.TextIOBase) * [TextIOWrapper (class in io)](library/io#io.TextIOWrapper) * [TextTestResult (class in unittest)](library/unittest#unittest.TextTestResult) * [TextTestRunner (class in unittest)](library/unittest#unittest.TextTestRunner) * [textwrap (module)](library/textwrap#module-textwrap) * [TextWrapper (class in textwrap)](library/textwrap#textwrap.TextWrapper) * [theme\_create() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.theme_create) * [theme\_names() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.theme_names) * [theme\_settings() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.theme_settings) * [theme\_use() (tkinter.ttk.Style method)](library/tkinter.ttk#tkinter.ttk.Style.theme_use) * [THOUSEP (in module locale)](library/locale#locale.THOUSEP) * [Thread (class in threading)](library/threading#threading.Thread) * [thread() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.thread) * [thread\_info (in module sys)](library/sys#sys.thread_info) * [thread\_time() (in module time)](library/time#time.thread_time) * [thread\_time\_ns() (in module time)](library/time#time.thread_time_ns) * [ThreadedChildWatcher (class in asyncio)](library/asyncio-policy#asyncio.ThreadedChildWatcher) * [threading (module)](library/threading#module-threading) * [threading\_cleanup() (in module test.support)](library/test#test.support.threading_cleanup) * [threading\_setup() (in module test.support)](library/test#test.support.threading_setup) * [ThreadingHTTPServer (class in http.server)](library/http.server#http.server.ThreadingHTTPServer) * [ThreadingMixIn (class in socketserver)](library/socketserver#socketserver.ThreadingMixIn) * [ThreadingTCPServer (class in socketserver)](library/socketserver#socketserver.ThreadingTCPServer) * [ThreadingUDPServer (class in socketserver)](library/socketserver#socketserver.ThreadingUDPServer) * [ThreadPool (class in multiprocessing.pool)](library/multiprocessing#multiprocessing.pool.ThreadPool) * [ThreadPoolExecutor (class in concurrent.futures)](library/concurrent.futures#concurrent.futures.ThreadPoolExecutor) * threads + [POSIX](library/_thread#index-1) * [threadsafety (in module sqlite3)](library/sqlite3#sqlite3.threadsafety) * [throw (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-throw) * [throw() (coroutine method)](reference/datamodel#coroutine.throw) + [(generator method)](reference/expressions#generator.throw) * [ticket\_lifetime\_hint (ssl.SSLSession attribute)](library/ssl#ssl.SSLSession.ticket_lifetime_hint) * [tigetflag() (in module curses)](library/curses#curses.tigetflag) * [tigetnum() (in module curses)](library/curses#curses.tigetnum) * [tigetstr() (in module curses)](library/curses#curses.tigetstr) * [TILDE (in module token)](library/token#token.TILDE) * [tilt() (in module turtle)](library/turtle#turtle.tilt) * [tiltangle() (in module turtle)](library/turtle#turtle.tiltangle) * [time (class in datetime)](library/datetime#datetime.time) + [(module)](library/time#module-time) + [(ssl.SSLSession attribute)](library/ssl#ssl.SSLSession.time) * [time() (asyncio.loop method)](library/asyncio-eventloop#asyncio.loop.time) + [(datetime.datetime method)](library/datetime#datetime.datetime.time) + [(in module time)](library/time#time.time) * [Time2Internaldate() (in module imaplib)](library/imaplib#imaplib.Time2Internaldate) * [time\_ns() (in module time)](library/time#time.time_ns) * [timedelta (class in datetime)](library/datetime#datetime.timedelta) * [TimedRotatingFileHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.TimedRotatingFileHandler) * [timegm() (in module calendar)](library/calendar#calendar.timegm) * [timeit (module)](library/timeit#module-timeit) * timeit command line option + [--help](library/timeit#cmdoption-timeit-h) + [--number=N](library/timeit#cmdoption-timeit-n) + [--process](library/timeit#cmdoption-timeit-p) + [--repeat=N](library/timeit#cmdoption-timeit-r) + [--setup=S](library/timeit#cmdoption-timeit-s) + [--unit=U](library/timeit#cmdoption-timeit-u) + [--verbose](library/timeit#cmdoption-timeit-v) + [-h](library/timeit#cmdoption-timeit-h) + [-n N](library/timeit#cmdoption-timeit-n) + [-p](library/timeit#cmdoption-timeit-p) + [-r N](library/timeit#cmdoption-timeit-r) + [-s S](library/timeit#cmdoption-timeit-s) + [-u](library/timeit#cmdoption-timeit-u) + [-v](library/timeit#cmdoption-timeit-v) * [timeit() (in module timeit)](library/timeit#timeit.timeit) + [(timeit.Timer method)](library/timeit#timeit.Timer.timeit) * [timeout](library/socket#socket.timeout) + [(socketserver.BaseServer attribute)](library/socketserver#socketserver.BaseServer.timeout) + [(ssl.SSLSession attribute)](library/ssl#ssl.SSLSession.timeout) + [(subprocess.TimeoutExpired attribute)](library/subprocess#subprocess.TimeoutExpired.timeout) * [timeout() (curses.window method)](library/curses#curses.window.timeout) * [TIMEOUT\_MAX (in module \_thread)](library/_thread#_thread.TIMEOUT_MAX) + [(in module threading)](library/threading#threading.TIMEOUT_MAX) * [TimeoutError](library/asyncio-exceptions#asyncio.TimeoutError), [[1]](library/concurrent.futures#concurrent.futures.TimeoutError), [[2]](library/exceptions#TimeoutError), [[3]](library/multiprocessing#multiprocessing.TimeoutError) * [TimeoutExpired](library/subprocess#subprocess.TimeoutExpired) * [Timer (class in threading)](library/threading#threading.Timer) + [(class in timeit)](library/timeit#timeit.Timer) * [TimerHandle (class in asyncio)](library/asyncio-eventloop#asyncio.TimerHandle) * [times() (in module os)](library/os#os.times) * [TIMESTAMP (py\_compile.PycInvalidationMode attribute)](library/py_compile#py_compile.PycInvalidationMode.TIMESTAMP) * [timestamp() (datetime.datetime method)](library/datetime#datetime.datetime.timestamp) * [timetuple() (datetime.date method)](library/datetime#datetime.date.timetuple) + [(datetime.datetime method)](library/datetime#datetime.datetime.timetuple) * [timetz() (datetime.datetime method)](library/datetime#datetime.datetime.timetz) * [timezone (class in datetime)](library/datetime#datetime.timezone) + [(in module time)](library/time#time.timezone) * [title() (bytearray method)](library/stdtypes#bytearray.title) + [(bytes method)](library/stdtypes#bytes.title) + [(in module turtle)](library/turtle#turtle.title) + [(str method)](library/stdtypes#str.title) * [Tix](library/tkinter.tix#index-0) * [tix\_addbitmapdir() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_addbitmapdir) * [tix\_cget() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_cget) * [tix\_configure() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_configure) * [tix\_filedialog() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_filedialog) * [tix\_getbitmap() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_getbitmap) * [tix\_getimage() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_getimage) | * [tix\_option\_get() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_option_get) * [tix\_resetoptions() (tkinter.tix.tixCommand method)](library/tkinter.tix#tkinter.tix.tixCommand.tix_resetoptions) * [tixCommand (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.tixCommand) * [Tk](library/tk#index-0) + [(class in tkinter)](library/tkinter#tkinter.Tk) + [(class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Tk) * [tk (tkinter.Tk attribute)](library/tkinter#tkinter.Tk.tk) * [Tk Option Data Types](library/tkinter#index-5) * [TK\_LIBRARY](faq/gui#index-1) * [Tkinter](library/tk#index-0) * [tkinter (module)](library/tkinter#module-tkinter) * [tkinter.colorchooser (module)](library/tkinter.colorchooser#module-tkinter.colorchooser) * [tkinter.commondialog (module)](library/dialog#module-tkinter.commondialog) * [tkinter.dnd (module)](library/tkinter.dnd#module-tkinter.dnd) * [tkinter.filedialog (module)](library/dialog#module-tkinter.filedialog) * [tkinter.font (module)](library/tkinter.font#module-tkinter.font) * [tkinter.messagebox (module)](library/tkinter.messagebox#module-tkinter.messagebox) * [tkinter.scrolledtext (module)](library/tkinter.scrolledtext#module-tkinter.scrolledtext) * [tkinter.simpledialog (module)](library/dialog#module-tkinter.simpledialog) * [tkinter.tix (module)](library/tkinter.tix#module-tkinter.tix) * [tkinter.ttk (module)](library/tkinter.ttk#module-tkinter.ttk) * [TList (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.TList) * [TLS](library/ssl#index-1) * [TLSv1 (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.TLSv1) * [TLSv1\_1 (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.TLSv1_1) * [TLSv1\_2 (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.TLSv1_2) * [TLSv1\_3 (ssl.TLSVersion attribute)](library/ssl#ssl.TLSVersion.TLSv1_3) * [TLSVersion (class in ssl)](library/ssl#ssl.TLSVersion) * [TMP](library/tempfile#index-3) * [TMPDIR](library/tempfile#index-1) * [to\_bytes() (int method)](library/stdtypes#int.to_bytes) * [to\_eng\_string() (decimal.Context method)](library/decimal#decimal.Context.to_eng_string) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.to_eng_string) * [to\_integral() (decimal.Decimal method)](library/decimal#decimal.Decimal.to_integral) * [to\_integral\_exact() (decimal.Context method)](library/decimal#decimal.Context.to_integral_exact) + [(decimal.Decimal method)](library/decimal#decimal.Decimal.to_integral_exact) * [to\_integral\_value() (decimal.Decimal method)](library/decimal#decimal.Decimal.to_integral_value) * [to\_sci\_string() (decimal.Context method)](library/decimal#decimal.Context.to_sci_string) * [to\_thread() (in module asyncio)](library/asyncio-task#asyncio.to_thread) * [ToASCII() (in module encodings.idna)](library/codecs#encodings.idna.ToASCII) * [tobuf() (tarfile.TarInfo method)](library/tarfile#tarfile.TarInfo.tobuf) * [tobytes() (array.array method)](library/array#array.array.tobytes) + [(memoryview method)](library/stdtypes#memoryview.tobytes) * [today() (datetime.date class method)](library/datetime#datetime.date.today) + [(datetime.datetime class method)](library/datetime#datetime.datetime.today) * [tofile() (array.array method)](library/array#array.array.tofile) * [tok\_name (in module token)](library/token#token.tok_name) * [token](reference/lexical_analysis#index-0) * [Token (class in contextvars)](library/contextvars#contextvars.Token) * [token (module)](library/token#module-token) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.token) * [token\_bytes() (in module secrets)](library/secrets#secrets.token_bytes) * [token\_hex() (in module secrets)](library/secrets#secrets.token_hex) * [token\_urlsafe() (in module secrets)](library/secrets#secrets.token_urlsafe) * [TokenError](library/tokenize#tokenize.TokenError) * [tokenize (module)](library/tokenize#module-tokenize) * tokenize command line option + [--exact](library/tokenize#cmdoption-tokenize-e) + [--help](library/tokenize#cmdoption-tokenize-h) + [-e](library/tokenize#cmdoption-tokenize-e) + [-h](library/tokenize#cmdoption-tokenize-h) * [tokenize() (in module tokenize)](library/tokenize#tokenize.tokenize) * [tolist() (array.array method)](library/array#array.array.tolist) + [(memoryview method)](library/stdtypes#memoryview.tolist) + [(parser.ST method)](library/parser#parser.ST.tolist) * [tomono() (in module audioop)](library/audioop#audioop.tomono) * [toordinal() (datetime.date method)](library/datetime#datetime.date.toordinal) + [(datetime.datetime method)](library/datetime#datetime.datetime.toordinal) * [top() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.top) + [(poplib.POP3 method)](library/poplib#poplib.POP3.top) * [top\_panel() (in module curses.panel)](library/curses.panel#curses.panel.top_panel) * [TopologicalSorter (class in graphlib)](library/graphlib#graphlib.TopologicalSorter) * [toprettyxml() (xml.dom.minidom.Node method)](library/xml.dom.minidom#xml.dom.minidom.Node.toprettyxml) * [toreadonly() (memoryview method)](library/stdtypes#memoryview.toreadonly) * [tostereo() (in module audioop)](library/audioop#audioop.tostereo) * [tostring() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.tostring) * [tostringlist() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.tostringlist) * [total\_changes (sqlite3.Connection attribute)](library/sqlite3#sqlite3.Connection.total_changes) * [total\_nframe (tracemalloc.Traceback attribute)](library/tracemalloc#tracemalloc.Traceback.total_nframe) * [total\_ordering() (in module functools)](library/functools#functools.total_ordering) * [total\_seconds() (datetime.timedelta method)](library/datetime#datetime.timedelta.total_seconds) * [totuple() (parser.ST method)](library/parser#parser.ST.totuple) * [touch() (pathlib.Path method)](library/pathlib#pathlib.Path.touch) * [touchline() (curses.window method)](library/curses#curses.window.touchline) * [touchwin() (curses.window method)](library/curses#curses.window.touchwin) * [tounicode() (array.array method)](library/array#array.array.tounicode) * [ToUnicode() (in module encodings.idna)](library/codecs#encodings.idna.ToUnicode) * [towards() (in module turtle)](library/turtle#turtle.towards) * [toxml() (xml.dom.minidom.Node method)](library/xml.dom.minidom#xml.dom.minidom.Node.toxml) * [tparm() (in module curses)](library/curses#curses.tparm) * trace + [stack](reference/datamodel#index-62) * [Trace (class in trace)](library/trace#trace.Trace) + [(class in tracemalloc)](library/tracemalloc#tracemalloc.Trace) * [trace (module)](library/trace#module-trace) * trace command line option + [--count](library/trace#cmdoption-trace-c) + [--coverdir=<dir>](library/trace#cmdoption-trace-coverdir) + [--file=<file>](library/trace#cmdoption-trace-f) + [--help](library/trace#cmdoption-trace-help) + [--ignore-dir=<dir>](library/trace#cmdoption-trace-ignore-dir) + [--ignore-module=<mod>](library/trace#cmdoption-trace-ignore-module) + [--listfuncs](library/trace#cmdoption-trace-l) + [--missing](library/trace#cmdoption-trace-m) + [--no-report](library/trace#cmdoption-trace-no-report) + [--report](library/trace#cmdoption-trace-r) + [--summary](library/trace#cmdoption-trace-s) + [--timing](library/trace#cmdoption-trace-g) + [--trace](library/trace#cmdoption-trace-t) + [--trackcalls](library/trace#cmdoption-trace-trackcalls) + [--version](library/trace#cmdoption-trace-version) + [-c](library/trace#cmdoption-trace-c) + [-C](library/trace#cmdoption-trace-coverdir) + [-f](library/trace#cmdoption-trace-f) + [-g](library/trace#cmdoption-trace-g) + [-l](library/trace#cmdoption-trace-l) + [-m](library/trace#cmdoption-trace-m) + [-r](library/trace#cmdoption-trace-r) + [-R](library/trace#cmdoption-trace-no-report) + [-s](library/trace#cmdoption-trace-s) + [-t](library/trace#cmdoption-trace-t) + [-T](library/trace#cmdoption-trace-trackcalls) * [trace function](library/sys#index-11), [[1]](library/sys#index-28), [[2]](library/threading#index-0) * [trace() (in module inspect)](library/inspect#inspect.trace) * [trace\_dispatch() (bdb.Bdb method)](library/bdb#bdb.Bdb.trace_dispatch) * traceback + [object](library/sys#index-8), [[1]](library/traceback#index-0), [[2]](reference/compound_stmts#index-12), [[3]](reference/datamodel#index-62), [[4]](reference/simple_stmts#index-28) * [Traceback (class in tracemalloc)](library/tracemalloc#tracemalloc.Traceback) * [traceback (module)](library/traceback#module-traceback) + [(tracemalloc.Statistic attribute)](library/tracemalloc#tracemalloc.Statistic.traceback) + [(tracemalloc.StatisticDiff attribute)](library/tracemalloc#tracemalloc.StatisticDiff.traceback) + [(tracemalloc.Trace attribute)](library/tracemalloc#tracemalloc.Trace.traceback) * [traceback\_limit (tracemalloc.Snapshot attribute)](library/tracemalloc#tracemalloc.Snapshot.traceback_limit) + [(wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.traceback_limit) * [TracebackException (class in traceback)](library/traceback#traceback.TracebackException) * [tracebacklimit (in module sys)](library/sys#sys.tracebacklimit) * tracebacks + [in CGI scripts](library/cgitb#index-0) * [TracebackType (class in types)](library/types#types.TracebackType) * [tracemalloc (module)](library/tracemalloc#module-tracemalloc) * [tracer() (in module turtle)](library/turtle#turtle.tracer) * [traces (tracemalloc.Snapshot attribute)](library/tracemalloc#tracemalloc.Snapshot.traces) * trailing + [comma](reference/expressions#index-94) * [transfercmd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.transfercmd) * [transient\_internet() (in module test.support.socket\_helper)](library/test#test.support.socket_helper.transient_internet) * [TransientResource (class in test.support)](library/test#test.support.TransientResource) * [translate() (bytearray method)](library/stdtypes#bytearray.translate) + [(bytes method)](library/stdtypes#bytes.translate) + [(in module fnmatch)](library/fnmatch#fnmatch.translate) + [(str method)](library/stdtypes#str.translate) * [translation() (in module gettext)](library/gettext#gettext.translation) * [transport (asyncio.StreamWriter attribute)](library/asyncio-stream#asyncio.StreamWriter.transport) * [Transport (class in asyncio)](library/asyncio-protocol#asyncio.Transport) * [Transport Layer Security](library/ssl#index-1) * [Traversable (class in importlib.abc)](library/importlib#importlib.abc.Traversable) * [TraversableResources (class in importlib.abc)](library/importlib#importlib.abc.TraversableResources) * [traverseproc (C type)](c-api/gcsupport#c.traverseproc) * [Tree (class in tkinter.tix)](library/tkinter.tix#tkinter.tix.Tree) * [TreeBuilder (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.TreeBuilder) * [Treeview (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Treeview) * [triangular() (in module random)](library/random#random.triangular) * [triple-quoted string](reference/lexical_analysis#index-17), [**[1]**](glossary#term-triple-quoted-string) * [True](library/stdtypes#index-4), [[1]](library/stdtypes#index-62), [[2]](reference/datamodel#index-11) * [true](library/stdtypes#index-2) * [True (built-in variable)](library/constants#True) * [truediv() (in module operator)](library/operator#operator.truediv) * [trunc() (in module math)](library/math#math.trunc), [[1]](library/stdtypes#index-15) * [truncate() (in module os)](library/os#os.truncate) + [(io.IOBase method)](library/io#io.IOBase.truncate) * truth + [value](library/stdtypes#index-1) * [truth() (in module operator)](library/operator#operator.truth) * try + [statement](library/exceptions#index-0), [[1]](reference/datamodel#index-63), [**[2]**](reference/compound_stmts#index-10) * [Try (class in ast)](library/ast#ast.Try) * [ttk](library/tkinter.ttk#index-0) * tty + [I/O control](library/termios#index-0) * [tty (module)](library/tty#module-tty) * [ttyname() (in module os)](library/os#os.ttyname) * tuple + [built-in function](c-api/list#index-2), [[1]](c-api/sequence#index-1) + [empty](reference/datamodel#index-20), [[1]](reference/expressions#index-9) + [object](c-api/tuple#index-0), [[1]](library/stdtypes#index-20), [[2]](library/stdtypes#index-24), [[3]](reference/datamodel#index-20), [[4]](reference/expressions#index-42), [[5]](reference/expressions#index-45), [[6]](reference/expressions#index-91) + [singleton](reference/datamodel#index-20) * [tuple (built-in class)](library/stdtypes#tuple) * [Tuple (class in ast)](library/ast#ast.Tuple) + [(in module typing)](library/typing#typing.Tuple) * [tuple2st() (in module parser)](library/parser#parser.tuple2st) * [tuple\_params (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-tuple_params) * [Turtle (class in turtle)](library/turtle#turtle.Turtle) * [turtle (module)](library/turtle#module-turtle) * [turtledemo (module)](library/turtle#module-turtledemo) * [turtles() (in module turtle)](library/turtle#turtle.turtles) * [TurtleScreen (class in turtle)](library/turtle#turtle.TurtleScreen) * [turtlesize() (in module turtle)](library/turtle#turtle.turtlesize) * [type](reference/datamodel#index-4), [**[1]**](glossary#term-type) + [Boolean](library/functions#index-0) + [built-in function](c-api/object#index-7), [[1]](library/stdtypes#index-60), [[2]](reference/datamodel#index-1), [[3]](reference/datamodel#index-82) + [data](reference/datamodel#index-4) + [hierarchy](reference/datamodel#index-4) + [immutable data](reference/expressions#index-7) + [object](c-api/intro#index-8), [[1]](c-api/type#index-0), [[2]](library/functions#index-11) + [operations on dictionary](library/stdtypes#index-50) + [operations on list](library/stdtypes#index-22) * [type (built-in class)](library/functions#type) * [Type (class in typing)](library/typing#typing.Type) * [type (optparse.Option attribute)](library/optparse#optparse.Option.type) + [(socket.socket attribute)](library/socket#socket.socket.type) + [(tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.type) + [(urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.type) * [**type alias**](glossary#term-type-alias) * [**type hint**](glossary#term-type-hint) * [type of an object](reference/datamodel#index-1) * [type\_check\_only() (in module typing)](library/typing#typing.type_check_only) * [TYPE\_CHECKER (optparse.Option attribute)](library/optparse#optparse.Option.TYPE_CHECKER) * [TYPE\_CHECKING (in module typing)](library/typing#typing.TYPE_CHECKING) * [type\_comment (ast.arg attribute)](library/ast#ast.arg.type_comment) + [(ast.Assign attribute)](library/ast#ast.Assign.type_comment) + [(ast.For attribute)](library/ast#ast.For.type_comment) + [(ast.FunctionDef attribute)](library/ast#ast.FunctionDef.type_comment) + [(ast.With attribute)](library/ast#ast.With.type_comment) * [TYPE\_COMMENT (in module token)](library/token#token.TYPE_COMMENT) * [TYPE\_IGNORE (in module token)](library/token#token.TYPE_IGNORE) * [typeahead() (in module curses)](library/curses#curses.typeahead) * [typecode (array.array attribute)](library/array#array.array.typecode) * [typecodes (in module array)](library/array#array.typecodes) * [TYPED\_ACTIONS (optparse.Option attribute)](library/optparse#optparse.Option.TYPED_ACTIONS) * [typed\_subpart\_iterator() (in module email.iterators)](library/email.iterators#email.iterators.typed_subpart_iterator) * [TypedDict (class in typing)](library/typing#typing.TypedDict) * [TypeError](library/exceptions#TypeError) + [exception](reference/expressions#index-63) * types + [built-in](library/stdtypes#index-0) + [immutable sequence](library/stdtypes#index-20) + [module](library/stdtypes#index-60) + [mutable sequence](library/stdtypes#index-21) + [operations on integer](library/stdtypes#index-16) + [operations on mapping](library/stdtypes#index-50) + [operations on numeric](library/stdtypes#index-14) + [operations on sequence](library/stdtypes#index-19), [[1]](library/stdtypes#index-22) * [types (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-types) + [(module)](library/types#module-types) * [TYPES (optparse.Option attribute)](library/optparse#optparse.Option.TYPES) * [types, internal](reference/datamodel#index-54) * [types\_map (in module mimetypes)](library/mimetypes#mimetypes.types_map) + [(mimetypes.MimeTypes attribute)](library/mimetypes#mimetypes.MimeTypes.types_map) * [types\_map\_inv (mimetypes.MimeTypes attribute)](library/mimetypes#mimetypes.MimeTypes.types_map_inv) * [TypeVar (class in typing)](library/typing#typing.TypeVar) * [typing (module)](library/typing#module-typing) * [TZ](library/time#index-13), [[1]](library/time#index-14), [[2]](library/time#index-15), [[3]](library/time#index-16), [[4]](library/time#index-17), [[5]](library/time#index-18) * [tzinfo (class in datetime)](library/datetime#datetime.tzinfo) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.tzinfo) + [(datetime.time attribute)](library/datetime#datetime.time.tzinfo) * [tzname (in module time)](library/time#time.tzname) * [tzname() (datetime.datetime method)](library/datetime#datetime.datetime.tzname) + [(datetime.time method)](library/datetime#datetime.time.tzname) + [(datetime.timezone method)](library/datetime#datetime.timezone.tzname) + [(datetime.tzinfo method)](library/datetime#datetime.tzinfo.tzname) * [TZPATH (in module zoneinfo)](library/zoneinfo#zoneinfo.TZPATH) * [tzset() (in module time)](library/time#time.tzset) | U - | | | | --- | --- | | * u" + [string literal](reference/lexical_analysis#index-16) * u' + [string literal](reference/lexical_analysis#index-16) * [u-LAW](library/aifc#index-2), [[1]](library/audioop#index-1), [[2]](library/sndhdr#index-0) * [UAdd (class in ast)](library/ast#ast.UAdd) * [ucd\_3\_2\_0 (in module unicodedata)](library/unicodedata#unicodedata.ucd_3_2_0) * [udata (select.kevent attribute)](library/select#select.kevent.udata) * [UDPServer (class in socketserver)](library/socketserver#socketserver.UDPServer) * [UF\_APPEND (in module stat)](library/stat#stat.UF_APPEND) * [UF\_COMPRESSED (in module stat)](library/stat#stat.UF_COMPRESSED) * [UF\_HIDDEN (in module stat)](library/stat#stat.UF_HIDDEN) * [UF\_IMMUTABLE (in module stat)](library/stat#stat.UF_IMMUTABLE) * [UF\_NODUMP (in module stat)](library/stat#stat.UF_NODUMP) * [UF\_NOUNLINK (in module stat)](library/stat#stat.UF_NOUNLINK) * [UF\_OPAQUE (in module stat)](library/stat#stat.UF_OPAQUE) * [UID (class in plistlib)](library/plistlib#plistlib.UID) * [uid (tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.uid) * [uid() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.uid) * [uidl() (poplib.POP3 method)](library/poplib#poplib.POP3.uidl) * [ulaw2lin() (in module audioop)](library/audioop#audioop.ulaw2lin) * [ULONG\_MAX](c-api/long#index-4) * [ulp() (in module math)](library/math#math.ulp) * [umask() (in module os)](library/os#os.umask) * [unalias (pdb command)](library/pdb#pdbcommand-unalias) * [uname (tarfile.TarInfo attribute)](library/tarfile#tarfile.TarInfo.uname) * [uname() (in module os)](library/os#os.uname) + [(in module platform)](library/platform#platform.uname) * unary + [arithmetic operation](reference/expressions#index-59) + [bitwise operation](reference/expressions#index-59) * [UNARY\_INVERT (opcode)](library/dis#opcode-UNARY_INVERT) * [UNARY\_NEGATIVE (opcode)](library/dis#opcode-UNARY_NEGATIVE) * [UNARY\_NOT (opcode)](library/dis#opcode-UNARY_NOT) * [UNARY\_POSITIVE (opcode)](library/dis#opcode-UNARY_POSITIVE) * [unaryfunc (C type)](c-api/typeobj#c.unaryfunc) * [UnaryOp (class in ast)](library/ast#ast.UnaryOp) * unbinding + [name](reference/simple_stmts#index-22) * [UnboundLocalError](library/exceptions#UnboundLocalError), [[1]](reference/executionmodel#index-9) * [unbuffered I/O](library/functions#index-7) * UNC paths + [and os.makedirs()](library/os#index-22) * [UNCHECKED\_HASH (py\_compile.PycInvalidationMode attribute)](library/py_compile#py_compile.PycInvalidationMode.UNCHECKED_HASH) * [unconsumed\_tail (zlib.Decompress attribute)](library/zlib#zlib.Decompress.unconsumed_tail) * [unctrl() (in module curses)](library/curses#curses.unctrl) + [(in module curses.ascii)](library/curses.ascii#curses.ascii.unctrl) * [undefine\_macro() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.undefine_macro) * [Underflow (class in decimal)](library/decimal#decimal.Underflow) * [undisplay (pdb command)](library/pdb#pdbcommand-undisplay) * [undo() (in module turtle)](library/turtle#turtle.undo) * [undobufferentries() (in module turtle)](library/turtle#turtle.undobufferentries) * [undoc\_header (cmd.Cmd attribute)](library/cmd#cmd.Cmd.undoc_header) * [unescape() (in module html)](library/html#html.unescape) + [(in module xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.unescape) * [UnexpectedException](library/doctest#doctest.UnexpectedException) * [unexpectedSuccesses (unittest.TestResult attribute)](library/unittest#unittest.TestResult.unexpectedSuccesses) * [unfreeze() (in module gc)](library/gc#gc.unfreeze) * [unget\_wch() (in module curses)](library/curses#curses.unget_wch) * [ungetch() (in module curses)](library/curses#curses.ungetch) + [(in module msvcrt)](library/msvcrt#msvcrt.ungetch) * [ungetmouse() (in module curses)](library/curses#curses.ungetmouse) * [ungetwch() (in module msvcrt)](library/msvcrt#msvcrt.ungetwch) * [unhexlify() (in module binascii)](library/binascii#binascii.unhexlify) * [Unicode](library/codecs#index-0), [[1]](library/unicodedata#index-0), [[2]](reference/datamodel#index-19) + [database](library/unicodedata#index-0) * [unicode (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-unicode) * [Unicode Consortium](reference/lexical_analysis#index-17) * [unicodedata (module)](library/unicodedata#module-unicodedata) * [UnicodeDecodeError](library/exceptions#UnicodeDecodeError) * [UnicodeEncodeError](library/exceptions#UnicodeEncodeError) * [UnicodeError](library/exceptions#UnicodeError) * [UnicodeTranslateError](library/exceptions#UnicodeTranslateError) * [UnicodeWarning](library/exceptions#UnicodeWarning) * [unidata\_version (in module unicodedata)](library/unicodedata#unicodedata.unidata_version) * [unified\_diff() (in module difflib)](library/difflib#difflib.unified_diff) * [uniform() (in module random)](library/random#random.uniform) * [UnimplementedFileMode](library/http.client#http.client.UnimplementedFileMode) * [Union (class in ctypes)](library/ctypes#ctypes.Union) + [(in module typing)](library/typing#typing.Union) * [union() (frozenset method)](library/stdtypes#frozenset.union) * [unique() (in module enum)](library/enum#enum.unique) * [unittest (module)](library/unittest#module-unittest) * unittest command line option + [--buffer](library/unittest#cmdoption-unittest-b) + [--catch](library/unittest#cmdoption-unittest-c) + [--failfast](library/unittest#cmdoption-unittest-f) + [--locals](library/unittest#cmdoption-unittest-locals) + [-b](library/unittest#cmdoption-unittest-b) + [-c](library/unittest#cmdoption-unittest-c) + [-f](library/unittest#cmdoption-unittest-f) + [-k](library/unittest#cmdoption-unittest-k) * unittest-discover command line option + [--pattern pattern](library/unittest#cmdoption-unittest-discover-p) + [--start-directory directory](library/unittest#cmdoption-unittest-discover-s) + [--top-level-directory directory](library/unittest#cmdoption-unittest-discover-t) + [--verbose](library/unittest#cmdoption-unittest-discover-v) + [-p](library/unittest#cmdoption-unittest-discover-p) + [-s](library/unittest#cmdoption-unittest-discover-s) + [-t](library/unittest#cmdoption-unittest-discover-t) + [-v](library/unittest#cmdoption-unittest-discover-v) * [unittest.mock (module)](library/unittest.mock#module-unittest.mock) * [**universal newlines**](glossary#term-universal-newlines) + [bytearray.splitlines method](library/stdtypes#index-42) + [bytes.splitlines method](library/stdtypes#index-42) + [csv.reader function](library/csv#index-3) + [importlib.abc.InspectLoader.get\_source method](library/importlib#index-16) + [io.IncrementalNewlineDecoder class](library/io#index-2) + [io.TextIOWrapper class](library/io#index-1) + [open() built-in function](library/functions#index-6) + [str.splitlines method](library/stdtypes#index-32) + [subprocess module](library/subprocess#index-1) + [What's new](https://docs.python.org/3.9/whatsnew/2.3.html#index-8), [[1]](https://docs.python.org/3.9/whatsnew/2.4.html#index-7), [[2]](https://docs.python.org/3.9/whatsnew/2.5.html#index-20), [[3]](https://docs.python.org/3.9/whatsnew/2.6.html#index-13) * [UNIX](reference/toplevel_components#index-4) + [file control](library/fcntl#index-0) + [I/O control](library/fcntl#index-0) * [unix\_dialect (class in csv)](library/csv#csv.unix_dialect) * [unix\_shell (in module test.support)](library/test#test.support.unix_shell) * [UnixDatagramServer (class in socketserver)](library/socketserver#socketserver.UnixDatagramServer) * [UnixStreamServer (class in socketserver)](library/socketserver#socketserver.UnixStreamServer) * [unknown (uuid.SafeUUID attribute)](library/uuid#uuid.SafeUUID.unknown) * [unknown\_decl() (html.parser.HTMLParser method)](library/html.parser#html.parser.HTMLParser.unknown_decl) * [unknown\_open() (urllib.request.BaseHandler method)](library/urllib.request#urllib.request.BaseHandler.unknown_open) + [(urllib.request.UnknownHandler method)](library/urllib.request#urllib.request.UnknownHandler.unknown_open) * [UnknownHandler (class in urllib.request)](library/urllib.request#urllib.request.UnknownHandler) * [UnknownProtocol](library/http.client#http.client.UnknownProtocol) * [UnknownTransferEncoding](library/http.client#http.client.UnknownTransferEncoding) * [unlink() (in module os)](library/os#os.unlink) + [(in module test.support)](library/test#test.support.unlink) + [(multiprocessing.shared\_memory.SharedMemory method)](library/multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory.unlink) + [(pathlib.Path method)](library/pathlib#pathlib.Path.unlink) + [(xml.dom.minidom.Node method)](library/xml.dom.minidom#xml.dom.minidom.Node.unlink) * [unload() (in module test.support)](library/test#test.support.unload) * [unlock() (mailbox.Babyl method)](library/mailbox#mailbox.Babyl.unlock) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.unlock) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.unlock) + [(mailbox.mbox method)](library/mailbox#mailbox.mbox.unlock) + [(mailbox.MH method)](library/mailbox#mailbox.MH.unlock) + [(mailbox.MMDF method)](library/mailbox#mailbox.MMDF.unlock) * [unpack() (in module struct)](library/struct#struct.unpack) + [(struct.Struct method)](library/struct#struct.Struct.unpack) * [unpack\_archive() (in module shutil)](library/shutil#shutil.unpack_archive) * [unpack\_array() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_array) * [unpack\_bytes() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_bytes) * [unpack\_double() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_double) * [UNPACK\_EX (opcode)](library/dis#opcode-UNPACK_EX) * [unpack\_farray() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_farray) * [unpack\_float() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_float) * [unpack\_fopaque() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_fopaque) * [unpack\_from() (in module struct)](library/struct#struct.unpack_from) + [(struct.Struct method)](library/struct#struct.Struct.unpack_from) * [unpack\_fstring() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_fstring) * [unpack\_list() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_list) * [unpack\_opaque() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_opaque) * [UNPACK\_SEQUENCE (opcode)](library/dis#opcode-UNPACK_SEQUENCE) * [unpack\_string() (xdrlib.Unpacker method)](library/xdrlib#xdrlib.Unpacker.unpack_string) * [Unpacker (class in xdrlib)](library/xdrlib#xdrlib.Unpacker) * unpacking + [dictionary](reference/expressions#index-18) + [in function calls](reference/expressions#index-49) + [iterable](reference/expressions#index-92) | * [unparse() (in module ast)](library/ast#ast.unparse) * [unparsedEntityDecl() (xml.sax.handler.DTDHandler method)](library/xml.sax.handler#xml.sax.handler.DTDHandler.unparsedEntityDecl) * [UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler) * [Unpickler (class in pickle)](library/pickle#pickle.Unpickler) * [UnpicklingError](library/pickle#pickle.UnpicklingError) * [unquote() (in module email.utils)](library/email.utils#email.utils.unquote) + [(in module urllib.parse)](library/urllib.parse#urllib.parse.unquote) * [unquote\_plus() (in module urllib.parse)](library/urllib.parse#urllib.parse.unquote_plus) * [unquote\_to\_bytes() (in module urllib.parse)](library/urllib.parse#urllib.parse.unquote_to_bytes) * [unraisablehook() (in module sys)](library/sys#sys.unraisablehook) * [unreachable object](reference/datamodel#index-2) * [unreadline() (distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.unreadline) * [unrecognized escape sequence](reference/lexical_analysis#index-23) * [unregister() (in module atexit)](library/atexit#atexit.unregister) + [(in module faulthandler)](library/faulthandler#faulthandler.unregister) + [(select.devpoll method)](library/select#select.devpoll.unregister) + [(select.epoll method)](library/select#select.epoll.unregister) + [(select.poll method)](library/select#select.poll.unregister) + [(selectors.BaseSelector method)](library/selectors#selectors.BaseSelector.unregister) * [unregister\_archive\_format() (in module shutil)](library/shutil#shutil.unregister_archive_format) * [unregister\_dialect() (in module csv)](library/csv#csv.unregister_dialect) * [unregister\_unpack\_format() (in module shutil)](library/shutil#shutil.unregister_unpack_format) * [unsafe (uuid.SafeUUID attribute)](library/uuid#uuid.SafeUUID.unsafe) * [unselect() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.unselect) * [unset() (test.support.EnvironmentVarGuard method)](library/test#test.support.EnvironmentVarGuard.unset) * [unsetenv() (in module os)](library/os#os.unsetenv) * [UnstructuredHeader (class in email.headerregistry)](library/email.headerregistry#email.headerregistry.UnstructuredHeader) * [unsubscribe() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.unsubscribe) * [UnsupportedOperation](library/io#io.UnsupportedOperation) * [until (pdb command)](library/pdb#pdbcommand-until) * [untokenize() (in module tokenize)](library/tokenize#tokenize.untokenize) * [untouchwin() (curses.window method)](library/curses#curses.window.untouchwin) * [unused\_data (bz2.BZ2Decompressor attribute)](library/bz2#bz2.BZ2Decompressor.unused_data) + [(lzma.LZMADecompressor attribute)](library/lzma#lzma.LZMADecompressor.unused_data) + [(zlib.Decompress attribute)](library/zlib#zlib.Decompress.unused_data) * [unverifiable (urllib.request.Request attribute)](library/urllib.request#urllib.request.Request.unverifiable) * [unwrap() (in module inspect)](library/inspect#inspect.unwrap) + [(in module urllib.parse)](library/urllib.parse#urllib.parse.unwrap) + [(ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.unwrap) * [up (pdb command)](library/pdb#pdbcommand-up) * [up() (in module turtle)](library/turtle#turtle.up) * [update() (collections.Counter method)](library/collections#collections.Counter.update) + [(dict method)](library/stdtypes#dict.update) + [(frozenset method)](library/stdtypes#frozenset.update) + [(hashlib.hash method)](library/hashlib#hashlib.hash.update) + [(hmac.HMAC method)](library/hmac#hmac.HMAC.update) + [(http.cookies.Morsel method)](library/http.cookies#http.cookies.Morsel.update) + [(in module turtle)](library/turtle#turtle.update) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.update) + [(mailbox.Maildir method)](library/mailbox#mailbox.Maildir.update) + [(trace.CoverageResults method)](library/trace#trace.CoverageResults.update) * [update\_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth method)](library/urllib.request#urllib.request.HTTPPasswordMgrWithPriorAuth.update_authenticated) * [update\_lines\_cols() (in module curses)](library/curses#curses.update_lines_cols) * [update\_panels() (in module curses.panel)](library/curses.panel#curses.panel.update_panels) * [update\_visible() (mailbox.BabylMessage method)](library/mailbox#mailbox.BabylMessage.update_visible) * [update\_wrapper() (in module functools)](library/functools#functools.update_wrapper) * [upgrade\_dependencies() (venv.EnvBuilder method)](library/venv#venv.EnvBuilder.upgrade_dependencies) * [upper() (bytearray method)](library/stdtypes#bytearray.upper) + [(bytes method)](library/stdtypes#bytes.upper) + [(str method)](library/stdtypes#str.upper) * [urandom() (in module os)](library/os#os.urandom) * [URL](library/cgi#index-0), [[1]](library/http.server#index-0), [[2]](library/urllib.parse#index-0), [[3]](library/urllib.robotparser#index-0) + [parsing](library/urllib.parse#index-0) + [relative](library/urllib.parse#index-0) * [url (http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.url) + [(urllib.response.addinfourl attribute)](library/urllib.request#urllib.response.addinfourl.url) + [(xmlrpc.client.ProtocolError attribute)](library/xmlrpc.client#xmlrpc.client.ProtocolError.url) * [url2pathname() (in module urllib.request)](library/urllib.request#urllib.request.url2pathname) * [urlcleanup() (in module urllib.request)](library/urllib.request#urllib.request.urlcleanup) * [urldefrag() (in module urllib.parse)](library/urllib.parse#urllib.parse.urldefrag) * [urlencode() (in module urllib.parse)](library/urllib.parse#urllib.parse.urlencode) * [URLError](library/urllib.error#urllib.error.URLError) * [urljoin() (in module urllib.parse)](library/urllib.parse#urllib.parse.urljoin) * [urllib (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-urllib) + [(module)](library/urllib#module-urllib) * [urllib.error (module)](library/urllib.error#module-urllib.error) * [urllib.parse (module)](library/urllib.parse#module-urllib.parse) * urllib.request + [module](library/http.client#index-1) * [urllib.request (module)](library/urllib.request#module-urllib.request) * [urllib.response (module)](library/urllib.request#module-urllib.response) * [urllib.robotparser (module)](library/urllib.robotparser#module-urllib.robotparser) * [urlopen() (in module urllib.request)](library/urllib.request#urllib.request.urlopen) * [URLopener (class in urllib.request)](library/urllib.request#urllib.request.URLopener) * [urlparse() (in module urllib.parse)](library/urllib.parse#urllib.parse.urlparse) * [urlretrieve() (in module urllib.request)](library/urllib.request#urllib.request.urlretrieve) * [urlsafe\_b64decode() (in module base64)](library/base64#base64.urlsafe_b64decode) * [urlsafe\_b64encode() (in module base64)](library/base64#base64.urlsafe_b64encode) * [urlsplit() (in module urllib.parse)](library/urllib.parse#urllib.parse.urlsplit) * [urlunparse() (in module urllib.parse)](library/urllib.parse#urllib.parse.urlunparse) * [urlunsplit() (in module urllib.parse)](library/urllib.parse#urllib.parse.urlunsplit) * [urn (uuid.UUID attribute)](library/uuid#uuid.UUID.urn) * [use\_default\_colors() (in module curses)](library/curses#curses.use_default_colors) * [use\_env() (in module curses)](library/curses#curses.use_env) * [use\_rawinput (cmd.Cmd attribute)](library/cmd#cmd.Cmd.use_rawinput) * [UseForeignDTD() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.UseForeignDTD) * [USER](library/getpass#index-1) * user + [effective id](library/os#index-2) + [id](library/os#index-10) + [id, setting](library/os#index-13) * [user() (poplib.POP3 method)](library/poplib#poplib.POP3.user) * user-defined + [function](reference/datamodel#index-33) + [function call](reference/expressions#index-52) + [method](reference/datamodel#index-35) * user-defined function + [object](reference/compound_stmts#index-19), [[1]](reference/datamodel#index-33), [[2]](reference/expressions#index-52) * user-defined method + [object](reference/datamodel#index-35) * [USER\_BASE](https://docs.python.org/3.9/whatsnew/2.7.html#index-9) + [(in module site)](library/site#site.USER_BASE) * [user\_call() (bdb.Bdb method)](library/bdb#bdb.Bdb.user_call) * [user\_exception() (bdb.Bdb method)](library/bdb#bdb.Bdb.user_exception) * [user\_line() (bdb.Bdb method)](library/bdb#bdb.Bdb.user_line) * [user\_return() (bdb.Bdb method)](library/bdb#bdb.Bdb.user_return) * [USER\_SITE (in module site)](library/site#site.USER_SITE) * usercustomize + [module](library/site#index-6) * [UserDict (class in collections)](library/collections#collections.UserDict) * [UserList (class in collections)](library/collections#collections.UserList) * [USERNAME](library/getpass#index-3), [[1]](library/os#index-5) * [username (email.headerregistry.Address attribute)](library/email.headerregistry#email.headerregistry.Address.username) * [USERPROFILE](install/index#index-6), [[1]](library/os.path#index-4), [[2]](https://docs.python.org/3.9/whatsnew/3.8.html#index-13), [[3]](https://docs.python.org/3.9/whatsnew/3.8.html#index-20), [[4]](https://docs.python.org/3.9/whatsnew/changelog.html#index-53) * [userptr() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.userptr) * [UserString (class in collections)](library/collections#collections.UserString) * [UserWarning](library/exceptions#UserWarning) * [USTAR\_FORMAT (in module tarfile)](library/tarfile#tarfile.USTAR_FORMAT) * [USub (class in ast)](library/ast#ast.USub) * [UTC](library/time#index-4) * [utc (datetime.timezone attribute)](library/datetime#datetime.timezone.utc) * [utcfromtimestamp() (datetime.datetime class method)](library/datetime#datetime.datetime.utcfromtimestamp) * [utcnow() (datetime.datetime class method)](library/datetime#datetime.datetime.utcnow) * [utcoffset() (datetime.datetime method)](library/datetime#datetime.datetime.utcoffset) + [(datetime.time method)](library/datetime#datetime.time.utcoffset) + [(datetime.timezone method)](library/datetime#datetime.timezone.utcoffset) + [(datetime.tzinfo method)](library/datetime#datetime.tzinfo.utcoffset) * [utctimetuple() (datetime.datetime method)](library/datetime#datetime.datetime.utctimetuple) * [utf8 (email.policy.EmailPolicy attribute)](library/email.policy#email.policy.EmailPolicy.utf8) * [utf8() (poplib.POP3 method)](library/poplib#poplib.POP3.utf8) * [utf8\_enabled (imaplib.IMAP4 attribute)](library/imaplib#imaplib.IMAP4.utf8_enabled) * [utime() (in module os)](library/os#os.utime) * uu + [module](library/binascii#index-0) * [uu (module)](library/uu#module-uu) * [UUID (class in uuid)](library/uuid#uuid.UUID) * [uuid (module)](library/uuid#module-uuid) * [uuid1](library/uuid#index-6) * [uuid1() (in module uuid)](library/uuid#uuid.uuid1) * [uuid3](library/uuid#index-7) * [uuid3() (in module uuid)](library/uuid#uuid.uuid3) * [uuid4](library/uuid#index-8) * [uuid4() (in module uuid)](library/uuid#uuid.uuid4) * [uuid5](library/uuid#index-9) * [uuid5() (in module uuid)](library/uuid#uuid.uuid5) * [UuidCreate() (in module msilib)](library/msilib#msilib.UuidCreate) | V - | | | | --- | --- | | * [v4\_int\_to\_packed() (in module ipaddress)](library/ipaddress#ipaddress.v4_int_to_packed) * [v6\_int\_to\_packed() (in module ipaddress)](library/ipaddress#ipaddress.v6_int_to_packed) * [valid\_signals() (in module signal)](library/signal#signal.valid_signals) * [validator() (in module wsgiref.validate)](library/wsgiref#wsgiref.validate.validator) * value + [default parameter](reference/compound_stmts#index-22) + [truth](library/stdtypes#index-1) * [value (ctypes.\_SimpleCData attribute)](library/ctypes#ctypes._SimpleCData.value) + [(http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.value) + [(http.cookies.Morsel attribute)](library/http.cookies#http.cookies.Morsel.value) + [(xml.dom.Attr attribute)](library/xml.dom#xml.dom.Attr.value) * [value of an object](reference/datamodel#index-1) * [Value() (in module multiprocessing)](library/multiprocessing#multiprocessing.Value) + [(in module multiprocessing.sharedctypes)](library/multiprocessing#multiprocessing.sharedctypes.Value) + [(multiprocessing.managers.SyncManager method)](library/multiprocessing#multiprocessing.managers.SyncManager.Value) * [value\_decode() (http.cookies.BaseCookie method)](library/http.cookies#http.cookies.BaseCookie.value_decode) * [value\_encode() (http.cookies.BaseCookie method)](library/http.cookies#http.cookies.BaseCookie.value_encode) * [ValueError](library/exceptions#ValueError) + [exception](reference/expressions#index-72) * [valuerefs() (weakref.WeakValueDictionary method)](library/weakref#weakref.WeakValueDictionary.valuerefs) * values + [Boolean](library/stdtypes#index-62) + [writing](reference/simple_stmts#index-3) * [values() (contextvars.Context method)](library/contextvars#contextvars.Context.values) + [(dict method)](library/stdtypes#dict.values) + [(email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.values) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.values) + [(mailbox.Mailbox method)](library/mailbox#mailbox.Mailbox.values) + [(types.MappingProxyType method)](library/types#types.MappingProxyType.values) * [ValuesView (class in collections.abc)](library/collections.abc#collections.abc.ValuesView) + [(class in typing)](library/typing#typing.ValuesView) * [var (contextvars.Token attribute)](library/contextvars#contextvars.Token.var) * variable + [free](reference/executionmodel#index-6) * [**variable annotation**](glossary#term-variable-annotation) * [variance (statistics.NormalDist attribute)](library/statistics#statistics.NormalDist.variance) * [variance() (in module statistics)](library/statistics#statistics.variance) * [variant (uuid.UUID attribute)](library/uuid#uuid.UUID.variant) * [vars() (built-in function)](library/functions#vars) * [VBAR (in module token)](library/token#token.VBAR) * [vbar (tkinter.scrolledtext.ScrolledText attribute)](library/tkinter.scrolledtext#tkinter.scrolledtext.ScrolledText.vbar) * [VBAREQUAL (in module token)](library/token#token.VBAREQUAL) * [Vec2D (class in turtle)](library/turtle#turtle.Vec2D) * [vectorcallfunc (C type)](c-api/call#c.vectorcallfunc) * [venv (module)](library/venv#module-venv) * [VERBOSE (in module re)](library/re#re.VERBOSE) | * [verbose (in module tabnanny)](library/tabnanny#tabnanny.verbose) + [(in module test.support)](library/test#test.support.verbose) * [verify() (smtplib.SMTP method)](library/smtplib#smtplib.SMTP.verify) * [verify\_client\_post\_handshake() (ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.verify_client_post_handshake) * [verify\_code (ssl.SSLCertVerificationError attribute)](library/ssl#ssl.SSLCertVerificationError.verify_code) * [VERIFY\_CRL\_CHECK\_CHAIN (in module ssl)](library/ssl#ssl.VERIFY_CRL_CHECK_CHAIN) * [VERIFY\_CRL\_CHECK\_LEAF (in module ssl)](library/ssl#ssl.VERIFY_CRL_CHECK_LEAF) * [VERIFY\_DEFAULT (in module ssl)](library/ssl#ssl.VERIFY_DEFAULT) * [verify\_flags (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.verify_flags) * [verify\_message (ssl.SSLCertVerificationError attribute)](library/ssl#ssl.SSLCertVerificationError.verify_message) * [verify\_mode (ssl.SSLContext attribute)](library/ssl#ssl.SSLContext.verify_mode) * [verify\_request() (socketserver.BaseServer method)](library/socketserver#socketserver.BaseServer.verify_request) * [VERIFY\_X509\_STRICT (in module ssl)](library/ssl#ssl.VERIFY_X509_STRICT) * [VERIFY\_X509\_TRUSTED\_FIRST (in module ssl)](library/ssl#ssl.VERIFY_X509_TRUSTED_FIRST) * [VerifyFlags (class in ssl)](library/ssl#ssl.VerifyFlags) * [VerifyMode (class in ssl)](library/ssl#ssl.VerifyMode) * [version (email.headerregistry.MIMEVersionHeader attribute)](library/email.headerregistry#email.headerregistry.MIMEVersionHeader.version) + [(http.client.HTTPResponse attribute)](library/http.client#http.client.HTTPResponse.version) + [(http.cookiejar.Cookie attribute)](library/http.cookiejar#http.cookiejar.Cookie.version) + [(in module curses)](library/curses#curses.version) + [(in module marshal)](library/marshal#marshal.version) + [(in module sqlite3)](library/sqlite3#sqlite3.version) + [(in module sys)](c-api/init#index-25), [[1]](c-api/init#index-28), [[2]](c-api/init#index-29), [[3]](library/sys#sys.version) + [(ipaddress.IPv4Address attribute)](library/ipaddress#ipaddress.IPv4Address.version) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.version) + [(ipaddress.IPv6Address attribute)](library/ipaddress#ipaddress.IPv6Address.version) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.version) + [(urllib.request.URLopener attribute)](library/urllib.request#urllib.request.URLopener.version) + [(uuid.UUID attribute)](library/uuid#uuid.UUID.version) * [version() (in module ensurepip)](library/ensurepip#ensurepip.version) + [(in module platform)](library/platform#platform.version) + [(ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.version) * [version\_info (in module sqlite3)](library/sqlite3#sqlite3.version_info) + [(in module sys)](library/sys#sys.version_info) * [version\_string() (http.server.BaseHTTPRequestHandler method)](library/http.server#http.server.BaseHTTPRequestHandler.version_string) * [vformat() (string.Formatter method)](library/string#string.Formatter.vformat) * virtual + [Environments](library/venv#index-0) * [**virtual environment**](glossary#term-virtual-environment) * [**virtual machine**](glossary#term-virtual-machine) * [VIRTUAL\_ENV](library/venv#index-2) * [visit() (ast.NodeVisitor method)](library/ast#ast.NodeVisitor.visit) * [visitproc (C type)](c-api/gcsupport#c.visitproc) * [vline() (curses.window method)](library/curses#curses.window.vline) * [voidcmd() (ftplib.FTP method)](library/ftplib#ftplib.FTP.voidcmd) * [volume (zipfile.ZipInfo attribute)](library/zipfile#zipfile.ZipInfo.volume) * [vonmisesvariate() (in module random)](library/random#random.vonmisesvariate) | W - | | | | --- | --- | | * [W\_OK (in module os)](library/os#os.W_OK) * [wait() (asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.wait) + [(asyncio.Event method)](library/asyncio-sync#asyncio.Event.wait) + [(asyncio.subprocess.Process method)](library/asyncio-subprocess#asyncio.subprocess.Process.wait) + [(in module asyncio)](library/asyncio-task#asyncio.wait) + [(in module concurrent.futures)](library/concurrent.futures#concurrent.futures.wait) + [(in module multiprocessing.connection)](library/multiprocessing#multiprocessing.connection.wait) + [(in module os)](library/os#os.wait) + [(multiprocessing.pool.AsyncResult method)](library/multiprocessing#multiprocessing.pool.AsyncResult.wait) + [(subprocess.Popen method)](library/subprocess#subprocess.Popen.wait) + [(threading.Barrier method)](library/threading#threading.Barrier.wait) + [(threading.Condition method)](library/threading#threading.Condition.wait) + [(threading.Event method)](library/threading#threading.Event.wait) * [wait3() (in module os)](library/os#os.wait3) * [wait4() (in module os)](library/os#os.wait4) * [wait\_closed() (asyncio.Server method)](library/asyncio-eventloop#asyncio.Server.wait_closed) + [(asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.wait_closed) * [wait\_for() (asyncio.Condition method)](library/asyncio-sync#asyncio.Condition.wait_for) + [(in module asyncio)](library/asyncio-task#asyncio.wait_for) + [(threading.Condition method)](library/threading#threading.Condition.wait_for) * [wait\_process() (in module test.support)](library/test#test.support.wait_process) * [wait\_threads\_exit() (in module test.support)](library/test#test.support.wait_threads_exit) * [waitid() (in module os)](library/os#os.waitid) * [waitpid() (in module os)](library/os#os.waitpid) * [waitstatus\_to\_exitcode() (in module os)](library/os#os.waitstatus_to_exitcode) * [walk() (email.message.EmailMessage method)](library/email.message#email.message.EmailMessage.walk) + [(email.message.Message method)](library/email.compat32-message#email.message.Message.walk) + [(in module ast)](library/ast#ast.walk) + [(in module os)](library/os#os.walk) * [walk\_packages() (in module pkgutil)](library/pkgutil#pkgutil.walk_packages) * [walk\_stack() (in module traceback)](library/traceback#traceback.walk_stack) * [walk\_tb() (in module traceback)](library/traceback#traceback.walk_tb) * [want (doctest.Example attribute)](library/doctest#doctest.Example.want) * [warn() (distutils.ccompiler.CCompiler method)](distutils/apiref#distutils.ccompiler.CCompiler.warn) + [(distutils.text\_file.TextFile method)](distutils/apiref#distutils.text_file.TextFile.warn) + [(in module warnings)](library/warnings#warnings.warn) * [warn\_explicit() (in module warnings)](library/warnings#warnings.warn_explicit) * [Warning](library/exceptions#Warning), [[1]](library/sqlite3#sqlite3.Warning) * [warning() (in module logging)](library/logging#logging.warning) + [(logging.Logger method)](library/logging#logging.Logger.warning) + [(xml.sax.handler.ErrorHandler method)](library/xml.sax.handler#xml.sax.handler.ErrorHandler.warning) * [warnings](library/warnings#index-0) + [(module)](library/warnings#module-warnings) * [WarningsRecorder (class in test.support)](library/test#test.support.WarningsRecorder) * [warnoptions (in module sys)](library/sys#sys.warnoptions) * [wasSuccessful() (unittest.TestResult method)](library/unittest#unittest.TestResult.wasSuccessful) * [WatchedFileHandler (class in logging.handlers)](library/logging.handlers#logging.handlers.WatchedFileHandler) * [wave (module)](library/wave#module-wave) * [WCONTINUED (in module os)](library/os#os.WCONTINUED) * [WCOREDUMP() (in module os)](library/os#os.WCOREDUMP) * [WeakKeyDictionary (class in weakref)](library/weakref#weakref.WeakKeyDictionary) * [WeakMethod (class in weakref)](library/weakref#weakref.WeakMethod) * [weakref (module)](library/weakref#module-weakref) * [WeakSet (class in weakref)](library/weakref#weakref.WeakSet) * [WeakValueDictionary (class in weakref)](library/weakref#weakref.WeakValueDictionary) * [webbrowser (module)](library/webbrowser#module-webbrowser) * [weekday() (datetime.date method)](library/datetime#datetime.date.weekday) + [(datetime.datetime method)](library/datetime#datetime.datetime.weekday) + [(in module calendar)](library/calendar#calendar.weekday) * [weekheader() (in module calendar)](library/calendar#calendar.weekheader) * [weibullvariate() (in module random)](library/random#random.weibullvariate) * [WEXITED (in module os)](library/os#os.WEXITED) * [WEXITSTATUS() (in module os)](library/os#os.WEXITSTATUS) * [wfile (http.server.BaseHTTPRequestHandler attribute)](library/http.server#http.server.BaseHTTPRequestHandler.wfile) * [what() (in module imghdr)](library/imghdr#imghdr.what) + [(in module sndhdr)](library/sndhdr#sndhdr.what) * [whathdr() (in module sndhdr)](library/sndhdr#sndhdr.whathdr) * [whatis (pdb command)](library/pdb#pdbcommand-whatis) * [when() (asyncio.TimerHandle method)](library/asyncio-eventloop#asyncio.TimerHandle.when) * [where (pdb command)](library/pdb#pdbcommand-where) * [which() (in module shutil)](library/shutil#shutil.which) * [whichdb() (in module dbm)](library/dbm#dbm.whichdb) * while + [statement](library/stdtypes#index-1), [[1]](reference/simple_stmts#index-30), [[2]](reference/simple_stmts#index-33), [**[3]**](reference/compound_stmts#index-4) * [While (class in ast)](library/ast#ast.While) * [whitespace (in module string)](library/string#string.whitespace) + [(shlex.shlex attribute)](library/shlex#shlex.shlex.whitespace) * [whitespace\_split (shlex.shlex attribute)](library/shlex#shlex.shlex.whitespace_split) * [Widget (class in tkinter.ttk)](library/tkinter.ttk#tkinter.ttk.Widget) * [width (textwrap.TextWrapper attribute)](library/textwrap#textwrap.TextWrapper.width) * [width() (in module turtle)](library/turtle#turtle.width) * [WIFCONTINUED() (in module os)](library/os#os.WIFCONTINUED) * [WIFEXITED() (in module os)](library/os#os.WIFEXITED) * [WIFSIGNALED() (in module os)](library/os#os.WIFSIGNALED) * [WIFSTOPPED() (in module os)](library/os#os.WIFSTOPPED) * [win32\_edition() (in module platform)](library/platform#platform.win32_edition) * [win32\_is\_iot() (in module platform)](library/platform#platform.win32_is_iot) * [win32\_ver() (in module platform)](library/platform#platform.win32_ver) * [WinDLL (class in ctypes)](library/ctypes#ctypes.WinDLL) * [window manager (widgets)](library/tkinter#index-4) * [window() (curses.panel.Panel method)](library/curses.panel#curses.panel.Panel.window) * [window\_height() (in module turtle)](library/turtle#turtle.window_height) * [window\_width() (in module turtle)](library/turtle#turtle.window_width) * [Windows](reference/toplevel_components#index-4) * [Windows ini file](library/configparser#index-0) * [WindowsError](library/exceptions#WindowsError) * [WindowsPath (class in pathlib)](library/pathlib#pathlib.WindowsPath) * [WindowsProactorEventLoopPolicy (class in asyncio)](library/asyncio-policy#asyncio.WindowsProactorEventLoopPolicy) * [WindowsRegistryFinder (class in importlib.machinery)](library/importlib#importlib.machinery.WindowsRegistryFinder) * [WindowsSelectorEventLoopPolicy (class in asyncio)](library/asyncio-policy#asyncio.WindowsSelectorEventLoopPolicy) * [winerror (OSError attribute)](library/exceptions#OSError.winerror) * [WinError() (in module ctypes)](library/ctypes#ctypes.WinError) * [WINFUNCTYPE() (in module ctypes)](library/ctypes#ctypes.WINFUNCTYPE) * [winreg (module)](library/winreg#module-winreg) * [WinSock](library/select#index-2) * [winsound (module)](library/winsound#module-winsound) * [winver (in module sys)](library/sys#sys.winver) * with + [statement](reference/datamodel#index-102), [**[1]**](reference/compound_stmts#index-16) * [With (class in ast)](library/ast#ast.With) * [WITH\_EXCEPT\_START (opcode)](library/dis#opcode-WITH_EXCEPT_START) | * [with\_hostmask (ipaddress.IPv4Interface attribute)](library/ipaddress#ipaddress.IPv4Interface.with_hostmask) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.with_hostmask) + [(ipaddress.IPv6Interface attribute)](library/ipaddress#ipaddress.IPv6Interface.with_hostmask) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.with_hostmask) * [with\_name() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.with_name) * [with\_netmask (ipaddress.IPv4Interface attribute)](library/ipaddress#ipaddress.IPv4Interface.with_netmask) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.with_netmask) + [(ipaddress.IPv6Interface attribute)](library/ipaddress#ipaddress.IPv6Interface.with_netmask) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.with_netmask) * [with\_prefixlen (ipaddress.IPv4Interface attribute)](library/ipaddress#ipaddress.IPv4Interface.with_prefixlen) + [(ipaddress.IPv4Network attribute)](library/ipaddress#ipaddress.IPv4Network.with_prefixlen) + [(ipaddress.IPv6Interface attribute)](library/ipaddress#ipaddress.IPv6Interface.with_prefixlen) + [(ipaddress.IPv6Network attribute)](library/ipaddress#ipaddress.IPv6Network.with_prefixlen) * [with\_pymalloc() (in module test.support)](library/test#test.support.with_pymalloc) * [with\_stem() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.with_stem) * [with\_suffix() (pathlib.PurePath method)](library/pathlib#pathlib.PurePath.with_suffix) * [with\_traceback() (BaseException method)](library/exceptions#BaseException.with_traceback) * [withitem (class in ast)](library/ast#ast.withitem) * [WNOHANG (in module os)](library/os#os.WNOHANG) * [WNOWAIT (in module os)](library/os#os.WNOWAIT) * [wordchars (shlex.shlex attribute)](library/shlex#shlex.shlex.wordchars) * [World Wide Web](library/internet#index-0), [[1]](library/urllib.parse#index-0), [[2]](library/urllib.robotparser#index-0) * [wrap() (in module textwrap)](library/textwrap#textwrap.wrap) + [(textwrap.TextWrapper method)](library/textwrap#textwrap.TextWrapper.wrap) * [wrap\_bio() (ssl.SSLContext method)](library/ssl#ssl.SSLContext.wrap_bio) * [wrap\_future() (in module asyncio)](library/asyncio-future#asyncio.wrap_future) * [wrap\_socket() (in module ssl)](library/ssl#ssl.wrap_socket) + [(ssl.SSLContext method)](library/ssl#ssl.SSLContext.wrap_socket) * [wrap\_text() (in module distutils.fancy\_getopt)](distutils/apiref#distutils.fancy_getopt.wrap_text) * [wrapper() (in module curses)](library/curses#curses.wrapper) * [WrapperDescriptorType (in module types)](library/types#types.WrapperDescriptorType) * [wraps() (in module functools)](library/functools#functools.wraps) * [WRITABLE (in module tkinter)](library/tkinter#tkinter.WRITABLE) * [writable() (asyncore.dispatcher method)](library/asyncore#asyncore.dispatcher.writable) + [(io.IOBase method)](library/io#io.IOBase.writable) * [write() (asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.write) + [(asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.write) + [(code.InteractiveInterpreter method)](library/code#code.InteractiveInterpreter.write) + [(codecs.StreamWriter method)](library/codecs#codecs.StreamWriter.write) + [(configparser.ConfigParser method)](library/configparser#configparser.ConfigParser.write) + [(email.generator.BytesGenerator method)](library/email.generator#email.generator.BytesGenerator.write) + [(email.generator.Generator method)](library/email.generator#email.generator.Generator.write) + [(in module os)](library/os#os.write) + [(in module turtle)](library/turtle#turtle.write) + [(io.BufferedIOBase method)](library/io#io.BufferedIOBase.write) + [(io.BufferedWriter method)](library/io#io.BufferedWriter.write) + [(io.RawIOBase method)](library/io#io.RawIOBase.write) + [(io.TextIOBase method)](library/io#io.TextIOBase.write) + [(mmap.mmap method)](library/mmap#mmap.mmap.write) + [(ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.write) + [(ssl.MemoryBIO method)](library/ssl#ssl.MemoryBIO.write) + [(ssl.SSLSocket method)](library/ssl#ssl.SSLSocket.write) + [(telnetlib.Telnet method)](library/telnetlib#telnetlib.Telnet.write) + [(xml.etree.ElementTree.ElementTree method)](library/xml.etree.elementtree#xml.etree.ElementTree.ElementTree.write) + [(zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.write) * [write\_byte() (mmap.mmap method)](library/mmap#mmap.mmap.write_byte) * [write\_bytes() (pathlib.Path method)](library/pathlib#pathlib.Path.write_bytes) * [write\_docstringdict() (in module turtle)](library/turtle#turtle.write_docstringdict) * [write\_eof() (asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.write_eof) + [(asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.write_eof) + [(ssl.MemoryBIO method)](library/ssl#ssl.MemoryBIO.write_eof) * [write\_file() (in module distutils.file\_util)](distutils/apiref#distutils.file_util.write_file) * [write\_history\_file() (in module readline)](library/readline#readline.write_history_file) * [WRITE\_RESTRICTED](extending/newtypes#index-4) * [write\_results() (trace.CoverageResults method)](library/trace#trace.CoverageResults.write_results) * [write\_text() (pathlib.Path method)](library/pathlib#pathlib.Path.write_text) * [write\_through (io.TextIOWrapper attribute)](library/io#io.TextIOWrapper.write_through) * [writeall() (ossaudiodev.oss\_audio\_device method)](library/ossaudiodev#ossaudiodev.oss_audio_device.writeall) * [writeframes() (aifc.aifc method)](library/aifc#aifc.aifc.writeframes) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.writeframes) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.writeframes) * [writeframesraw() (aifc.aifc method)](library/aifc#aifc.aifc.writeframesraw) + [(sunau.AU\_write method)](https://docs.python.org/3.9/library/sunau.html#sunau.AU_write.writeframesraw) + [(wave.Wave\_write method)](library/wave#wave.Wave_write.writeframesraw) * [writeheader() (csv.DictWriter method)](library/csv#csv.DictWriter.writeheader) * [writelines() (asyncio.StreamWriter method)](library/asyncio-stream#asyncio.StreamWriter.writelines) + [(asyncio.WriteTransport method)](library/asyncio-protocol#asyncio.WriteTransport.writelines) + [(codecs.StreamWriter method)](library/codecs#codecs.StreamWriter.writelines) + [(io.IOBase method)](library/io#io.IOBase.writelines) * [writepy() (zipfile.PyZipFile method)](library/zipfile#zipfile.PyZipFile.writepy) * [writer (formatter.formatter attribute)](https://docs.python.org/3.9/library/formatter.html#formatter.formatter.writer) * [writer() (in module csv)](library/csv#csv.writer) * [writerow() (csv.csvwriter method)](library/csv#csv.csvwriter.writerow) * [writerows() (csv.csvwriter method)](library/csv#csv.csvwriter.writerows) * [writestr() (zipfile.ZipFile method)](library/zipfile#zipfile.ZipFile.writestr) * [WriteTransport (class in asyncio)](library/asyncio-protocol#asyncio.WriteTransport) * [writev() (in module os)](library/os#os.writev) * [writexml() (xml.dom.minidom.Node method)](library/xml.dom.minidom#xml.dom.minidom.Node.writexml) * writing + [values](reference/simple_stmts#index-3) * [WrongDocumentErr](library/xml.dom#xml.dom.WrongDocumentErr) * [ws\_comma (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-ws_comma) * [wsgi\_file\_wrapper (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.wsgi_file_wrapper) * [wsgi\_multiprocess (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.wsgi_multiprocess) * [wsgi\_multithread (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.wsgi_multithread) * [wsgi\_run\_once (wsgiref.handlers.BaseHandler attribute)](library/wsgiref#wsgiref.handlers.BaseHandler.wsgi_run_once) * [wsgiref (module)](library/wsgiref#module-wsgiref) * [wsgiref.handlers (module)](library/wsgiref#module-wsgiref.handlers) * [wsgiref.headers (module)](library/wsgiref#module-wsgiref.headers) * [wsgiref.simple\_server (module)](library/wsgiref#module-wsgiref.simple_server) * [wsgiref.util (module)](library/wsgiref#module-wsgiref.util) * [wsgiref.validate (module)](library/wsgiref#module-wsgiref.validate) * [WSGIRequestHandler (class in wsgiref.simple\_server)](library/wsgiref#wsgiref.simple_server.WSGIRequestHandler) * [WSGIServer (class in wsgiref.simple\_server)](library/wsgiref#wsgiref.simple_server.WSGIServer) * [wShowWindow (subprocess.STARTUPINFO attribute)](library/subprocess#subprocess.STARTUPINFO.wShowWindow) * [WSTOPPED (in module os)](library/os#os.WSTOPPED) * [WSTOPSIG() (in module os)](library/os#os.WSTOPSIG) * [wstring\_at() (in module ctypes)](library/ctypes#ctypes.wstring_at) * [WTERMSIG() (in module os)](library/os#os.WTERMSIG) * [WUNTRACED (in module os)](library/os#os.WUNTRACED) * [WWW](library/internet#index-0), [[1]](library/urllib.parse#index-0), [[2]](library/urllib.robotparser#index-0) + [server](library/cgi#index-0), [[1]](library/http.server#index-0) | X - | | | | --- | --- | | * [X (in module re)](library/re#re.X) * [X509 certificate](library/ssl#index-18) * [X\_OK (in module os)](library/os#os.X_OK) * [xatom() (imaplib.IMAP4 method)](library/imaplib#imaplib.IMAP4.xatom) * [XATTR\_CREATE (in module os)](library/os#os.XATTR_CREATE) * [XATTR\_REPLACE (in module os)](library/os#os.XATTR_REPLACE) * [XATTR\_SIZE\_MAX (in module os)](library/os#os.XATTR_SIZE_MAX) * [xcor() (in module turtle)](library/turtle#turtle.xcor) * [XDR](library/xdrlib#index-0) * [xdrlib (module)](library/xdrlib#module-xdrlib) * [xhdr() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.xhdr) * [XHTML](library/html.parser#index-0) * [XHTML\_NAMESPACE (in module xml.dom)](library/xml.dom#xml.dom.XHTML_NAMESPACE) * [xml (module)](library/xml#module-xml) * [XML() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.XML) * [xml.dom (module)](library/xml.dom#module-xml.dom) * [xml.dom.minidom (module)](library/xml.dom.minidom#module-xml.dom.minidom) * [xml.dom.pulldom (module)](library/xml.dom.pulldom#module-xml.dom.pulldom) * [xml.etree.ElementInclude.default\_loader() (built-in function)](library/xml.etree.elementtree#xml.etree.ElementInclude.default_loader) * [xml.etree.ElementInclude.include() (built-in function)](library/xml.etree.elementtree#xml.etree.ElementInclude.include) * [xml.etree.ElementTree (module)](library/xml.etree.elementtree#module-xml.etree.ElementTree) * [xml.parsers.expat (module)](library/pyexpat#module-xml.parsers.expat) * [xml.parsers.expat.errors (module)](library/pyexpat#module-xml.parsers.expat.errors) * [xml.parsers.expat.model (module)](library/pyexpat#module-xml.parsers.expat.model) * [xml.sax (module)](library/xml.sax#module-xml.sax) * [xml.sax.handler (module)](library/xml.sax.handler#module-xml.sax.handler) * [xml.sax.saxutils (module)](library/xml.sax.utils#module-xml.sax.saxutils) * [xml.sax.xmlreader (module)](library/xml.sax.reader#module-xml.sax.xmlreader) * [XML\_ERROR\_ABORTED (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_ABORTED) * [XML\_ERROR\_ASYNC\_ENTITY (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY) * [XML\_ERROR\_ATTRIBUTE\_EXTERNAL\_ENTITY\_REF (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF) * [XML\_ERROR\_BAD\_CHAR\_REF (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF) * [XML\_ERROR\_BINARY\_ENTITY\_REF (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF) * [XML\_ERROR\_CANT\_CHANGE\_FEATURE\_ONCE\_PARSING (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING) * [XML\_ERROR\_DUPLICATE\_ATTRIBUTE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE) * [XML\_ERROR\_ENTITY\_DECLARED\_IN\_PE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE) * [XML\_ERROR\_EXTERNAL\_ENTITY\_HANDLING (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING) * [XML\_ERROR\_FEATURE\_REQUIRES\_XML\_DTD (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD) * [XML\_ERROR\_FINISHED (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_FINISHED) * [XML\_ERROR\_INCOMPLETE\_PE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE) * [XML\_ERROR\_INCORRECT\_ENCODING (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING) * [XML\_ERROR\_INVALID\_TOKEN (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN) * [XML\_ERROR\_JUNK\_AFTER\_DOC\_ELEMENT (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT) | * [XML\_ERROR\_MISPLACED\_XML\_PI (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI) * [XML\_ERROR\_NO\_ELEMENTS (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS) * [XML\_ERROR\_NO\_MEMORY (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_NO_MEMORY) * [XML\_ERROR\_NOT\_STANDALONE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE) * [XML\_ERROR\_NOT\_SUSPENDED (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED) * [XML\_ERROR\_PARAM\_ENTITY\_REF (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF) * [XML\_ERROR\_PARTIAL\_CHAR (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR) * [XML\_ERROR\_PUBLICID (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_PUBLICID) * [XML\_ERROR\_RECURSIVE\_ENTITY\_REF (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF) * [XML\_ERROR\_SUSPEND\_PE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE) * [XML\_ERROR\_SUSPENDED (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_SUSPENDED) * [XML\_ERROR\_SYNTAX (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_SYNTAX) * [XML\_ERROR\_TAG\_MISMATCH (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH) * [XML\_ERROR\_TEXT\_DECL (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_TEXT_DECL) * [XML\_ERROR\_UNBOUND\_PREFIX (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX) * [XML\_ERROR\_UNCLOSED\_CDATA\_SECTION (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION) * [XML\_ERROR\_UNCLOSED\_TOKEN (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN) * [XML\_ERROR\_UNDECLARING\_PREFIX (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX) * [XML\_ERROR\_UNDEFINED\_ENTITY (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY) * [XML\_ERROR\_UNEXPECTED\_STATE (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE) * [XML\_ERROR\_UNKNOWN\_ENCODING (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING) * [XML\_ERROR\_XML\_DECL (in module xml.parsers.expat.errors)](library/pyexpat#xml.parsers.expat.errors.XML_ERROR_XML_DECL) * [XML\_NAMESPACE (in module xml.dom)](library/xml.dom#xml.dom.XML_NAMESPACE) * xmlcharrefreplace + [error handler's name](library/codecs#index-3) * [xmlcharrefreplace\_errors() (in module codecs)](library/codecs#codecs.xmlcharrefreplace_errors) * [XmlDeclHandler() (xml.parsers.expat.xmlparser method)](library/pyexpat#xml.parsers.expat.xmlparser.XmlDeclHandler) * [XMLFilterBase (class in xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.XMLFilterBase) * [XMLGenerator (class in xml.sax.saxutils)](library/xml.sax.utils#xml.sax.saxutils.XMLGenerator) * [XMLID() (in module xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLID) * [XMLNS\_NAMESPACE (in module xml.dom)](library/xml.dom#xml.dom.XMLNS_NAMESPACE) * [XMLParser (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLParser) * [XMLParserType (in module xml.parsers.expat)](library/pyexpat#xml.parsers.expat.XMLParserType) * [XMLPullParser (class in xml.etree.ElementTree)](library/xml.etree.elementtree#xml.etree.ElementTree.XMLPullParser) * [XMLReader (class in xml.sax.xmlreader)](library/xml.sax.reader#xml.sax.xmlreader.XMLReader) * [xmlrpc.client (module)](library/xmlrpc.client#module-xmlrpc.client) * [xmlrpc.server (module)](library/xmlrpc.server#module-xmlrpc.server) * xor + [bitwise](reference/expressions#index-75) * [xor() (in module operator)](library/operator#operator.xor) * [xover() (nntplib.NNTP method)](library/nntplib#nntplib.NNTP.xover) * [xrange (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-xrange) * [xreadlines (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-xreadlines) * [xview() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.xview) | Y - | | | | --- | --- | | * [ycor() (in module turtle)](library/turtle#turtle.ycor) * [year (datetime.date attribute)](library/datetime#datetime.date.year) + [(datetime.datetime attribute)](library/datetime#datetime.datetime.year) * [Year 2038](library/time#index-2) * [yeardatescalendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.yeardatescalendar) * [yeardays2calendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.yeardays2calendar) * [yeardayscalendar() (calendar.Calendar method)](library/calendar#calendar.Calendar.yeardayscalendar) * [YESEXPR (in module locale)](library/locale#locale.YESEXPR) * yield + [examples](reference/expressions#index-34) + [expression](reference/expressions#index-23) + [keyword](reference/expressions#index-23) + [statement](reference/simple_stmts#index-26) + [yield from (in What's New)](https://docs.python.org/3.9/whatsnew/3.3.html#index-11) | * [Yield (class in ast)](library/ast#ast.Yield) * [YIELD\_FROM (opcode)](library/dis#opcode-YIELD_FROM) * [YIELD\_VALUE (opcode)](library/dis#opcode-YIELD_VALUE) * [YieldFrom (class in ast)](library/ast#ast.YieldFrom) * [yiq\_to\_rgb() (in module colorsys)](library/colorsys#colorsys.yiq_to_rgb) * [yview() (tkinter.ttk.Treeview method)](library/tkinter.ttk#tkinter.ttk.Treeview.yview) | Z - | | | | --- | --- | | * [**Zen of Python**](glossary#term-zen-of-python) * [ZeroDivisionError](library/exceptions#ZeroDivisionError) + [exception](reference/expressions#index-67) * [zfill() (bytearray method)](library/stdtypes#bytearray.zfill) + [(bytes method)](library/stdtypes#bytes.zfill) + [(str method)](library/stdtypes#str.zfill) * [zip (2to3 fixer)](https://docs.python.org/3.9/library/2to3.html#2to3fixer-zip) * [zip() (built-in function)](library/functions#zip) * [ZIP\_BZIP2 (in module zipfile)](library/zipfile#zipfile.ZIP_BZIP2) * [ZIP\_DEFLATED (in module zipfile)](library/zipfile#zipfile.ZIP_DEFLATED) * [zip\_longest() (in module itertools)](library/itertools#itertools.zip_longest) * [ZIP\_LZMA (in module zipfile)](library/zipfile#zipfile.ZIP_LZMA) * [ZIP\_STORED (in module zipfile)](library/zipfile#zipfile.ZIP_STORED) * [zipapp (module)](library/zipapp#module-zipapp) * zipapp command line option + [--compress](library/zipapp#cmdoption-zipapp-c) + [--help](library/zipapp#cmdoption-zipapp-h) + [--info](library/zipapp#cmdoption-zipapp-info) + [--main=<mainfn>](library/zipapp#cmdoption-zipapp-m) + [--output=<output>](library/zipapp#cmdoption-zipapp-o) + [--python=<interpreter>](library/zipapp#cmdoption-zipapp-p) + [-c](library/zipapp#cmdoption-zipapp-c) + [-h](library/zipapp#cmdoption-zipapp-h) + [-m <mainfn>](library/zipapp#cmdoption-zipapp-m) + [-o <output>](library/zipapp#cmdoption-zipapp-o) + [-p <interpreter>](library/zipapp#cmdoption-zipapp-p) | * [ZipFile (class in zipfile)](library/zipfile#zipfile.ZipFile) * [zipfile (module)](library/zipfile#module-zipfile) * zipfile command line option + [--create <zipfile> <source1> ... <sourceN>](library/zipfile#cmdoption-zipfile-create) + [--extract <zipfile> <output\_dir>](library/zipfile#cmdoption-zipfile-extract) + [--list <zipfile>](library/zipfile#cmdoption-zipfile-list) + [--test <zipfile>](library/zipfile#cmdoption-zipfile-test) + [-c <zipfile> <source1> ... <sourceN>](library/zipfile#cmdoption-zipfile-c) + [-e <zipfile> <output\_dir>](library/zipfile#cmdoption-zipfile-e) + [-l <zipfile>](library/zipfile#cmdoption-zipfile-l) + [-t <zipfile>](library/zipfile#cmdoption-zipfile-t) * [zipimport (module)](library/zipimport#module-zipimport) * [zipimporter (class in zipimport)](library/zipimport#zipimport.zipimporter) * [ZipImportError](library/zipimport#zipimport.ZipImportError) * [ZipInfo (class in zipfile)](library/zipfile#zipfile.ZipInfo) * [zlib (module)](library/zlib#module-zlib) * [ZLIB\_RUNTIME\_VERSION (in module zlib)](library/zlib#zlib.ZLIB_RUNTIME_VERSION) * [ZLIB\_VERSION (in module zlib)](library/zlib#zlib.ZLIB_VERSION) * [ZoneInfo (class in zoneinfo)](library/zoneinfo#zoneinfo.ZoneInfo) * [zoneinfo (module)](library/zoneinfo#module-zoneinfo) * [ZoneInfoNotFoundError](library/zoneinfo#zoneinfo.ZoneInfoNotFoundError) * [zscore() (statistics.NormalDist method)](library/statistics#statistics.NormalDist.zscore) |
programming_docs
python Distributing Python Modules (Legacy version) Distributing Python Modules (Legacy version) ============================================ Authors Greg Ward, Anthony Baxter Email [[email protected]](mailto:distutils-sig%40python.org) See also [Distributing Python Modules](../distributing/index#distributing-index) The up to date module distribution documentations Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. Note This guide only covers the basic tools for building and distributing extensions that are provided as part of this version of Python. Third party tools offer easier to use and more secure alternatives. Refer to the [quick recommendations section](https://packaging.python.org/guides/tool-recommendations/) in the Python Packaging User Guide for more information. This document describes the Python Distribution Utilities (“Distutils”) from the module developer’s point of view, describing the underlying capabilities that `setuptools` builds on to allow Python developers to make Python modules and extensions readily available to a wider audience. * [1. An Introduction to Distutils](introduction) + [1.1. Concepts & Terminology](introduction#concepts-terminology) + [1.2. A Simple Example](introduction#a-simple-example) + [1.3. General Python terminology](introduction#general-python-terminology) + [1.4. Distutils-specific terminology](introduction#distutils-specific-terminology) * [2. Writing the Setup Script](setupscript) + [2.1. Listing whole packages](setupscript#listing-whole-packages) + [2.2. Listing individual modules](setupscript#listing-individual-modules) + [2.3. Describing extension modules](setupscript#describing-extension-modules) + [2.4. Relationships between Distributions and Packages](setupscript#relationships-between-distributions-and-packages) + [2.5. Installing Scripts](setupscript#installing-scripts) + [2.6. Installing Package Data](setupscript#installing-package-data) + [2.7. Installing Additional Files](setupscript#installing-additional-files) + [2.8. Additional meta-data](setupscript#additional-meta-data) + [2.9. Debugging the setup script](setupscript#debugging-the-setup-script) * [3. Writing the Setup Configuration File](configfile) * [4. Creating a Source Distribution](sourcedist) + [4.1. Specifying the files to distribute](sourcedist#specifying-the-files-to-distribute) + [4.2. Manifest-related options](sourcedist#manifest-related-options) * [5. Creating Built Distributions](builtdist) + [5.1. Creating RPM packages](builtdist#creating-rpm-packages) + [5.2. Creating Windows Installers](builtdist#creating-windows-installers) + [5.3. Cross-compiling on Windows](builtdist#cross-compiling-on-windows) + [5.4. Vista User Access Control (UAC)](builtdist#vista-user-access-control-uac) * [6. Distutils Examples](examples) + [6.1. Pure Python distribution (by module)](examples#pure-python-distribution-by-module) + [6.2. Pure Python distribution (by package)](examples#pure-python-distribution-by-package) + [6.3. Single extension module](examples#single-extension-module) + [6.4. Checking a package](examples#checking-a-package) + [6.5. Reading the metadata](examples#reading-the-metadata) * [7. Extending Distutils](extending) + [7.1. Integrating new commands](extending#integrating-new-commands) + [7.2. Adding new distribution types](extending#adding-new-distribution-types) * [8. Command Reference](commandref) + [8.1. Installing modules: the **install** command family](commandref#installing-modules-the-install-command-family) + [8.2. Creating a source distribution: the **sdist** command](commandref#creating-a-source-distribution-the-sdist-command) * [9. API Reference](apiref) + [9.1. `distutils.core` — Core Distutils functionality](apiref#module-distutils.core) + [9.2. `distutils.ccompiler` — CCompiler base class](apiref#module-distutils.ccompiler) + [9.3. `distutils.unixccompiler` — Unix C Compiler](apiref#module-distutils.unixccompiler) + [9.4. `distutils.msvccompiler` — Microsoft Compiler](apiref#module-distutils.msvccompiler) + [9.5. `distutils.bcppcompiler` — Borland Compiler](apiref#module-distutils.bcppcompiler) + [9.6. `distutils.cygwincompiler` — Cygwin Compiler](apiref#module-distutils.cygwinccompiler) + [9.7. `distutils.archive_util` — Archiving utilities](apiref#module-distutils.archive_util) + [9.8. `distutils.dep_util` — Dependency checking](apiref#module-distutils.dep_util) + [9.9. `distutils.dir_util` — Directory tree operations](apiref#module-distutils.dir_util) + [9.10. `distutils.file_util` — Single file operations](apiref#module-distutils.file_util) + [9.11. `distutils.util` — Miscellaneous other utility functions](apiref#module-distutils.util) + [9.12. `distutils.dist` — The Distribution class](apiref#module-distutils.dist) + [9.13. `distutils.extension` — The Extension class](apiref#module-distutils.extension) + [9.14. `distutils.debug` — Distutils debug mode](apiref#module-distutils.debug) + [9.15. `distutils.errors` — Distutils exceptions](apiref#module-distutils.errors) + [9.16. `distutils.fancy_getopt` — Wrapper around the standard getopt module](apiref#module-distutils.fancy_getopt) + [9.17. `distutils.filelist` — The FileList class](apiref#module-distutils.filelist) + [9.18. `distutils.log` — Simple **PEP 282**-style logging](apiref#module-distutils.log) + [9.19. `distutils.spawn` — Spawn a sub-process](apiref#module-distutils.spawn) + [9.20. `distutils.sysconfig` — System configuration information](apiref#module-distutils.sysconfig) + [9.21. `distutils.text_file` — The TextFile class](apiref#module-distutils.text_file) + [9.22. `distutils.version` — Version number classes](apiref#module-distutils.version) + [9.23. `distutils.cmd` — Abstract base class for Distutils commands](apiref#module-distutils.cmd) + [9.24. Creating a new Distutils command](apiref#creating-a-new-distutils-command) + [9.25. `distutils.command` — Individual Distutils commands](apiref#module-distutils.command) + [9.26. `distutils.command.bdist` — Build a binary installer](apiref#module-distutils.command.bdist) + [9.27. `distutils.command.bdist_packager` — Abstract base class for packagers](apiref#module-distutils.command.bdist_packager) + [9.28. `distutils.command.bdist_dumb` — Build a “dumb” installer](apiref#module-distutils.command.bdist_dumb) + [9.29. `distutils.command.bdist_msi` — Build a Microsoft Installer binary package](apiref#module-distutils.command.bdist_msi) + [9.30. `distutils.command.bdist_rpm` — Build a binary distribution as a Redhat RPM and SRPM](apiref#module-distutils.command.bdist_rpm) + [9.31. `distutils.command.bdist_wininst` — Build a Windows installer](apiref#module-distutils.command.bdist_wininst) + [9.32. `distutils.command.sdist` — Build a source distribution](apiref#module-distutils.command.sdist) + [9.33. `distutils.command.build` — Build all files of a package](apiref#module-distutils.command.build) + [9.34. `distutils.command.build_clib` — Build any C libraries in a package](apiref#module-distutils.command.build_clib) + [9.35. `distutils.command.build_ext` — Build any extensions in a package](apiref#module-distutils.command.build_ext) + [9.36. `distutils.command.build_py` — Build the .py/.pyc files of a package](apiref#module-distutils.command.build_py) + [9.37. `distutils.command.build_scripts` — Build the scripts of a package](apiref#module-distutils.command.build_scripts) + [9.38. `distutils.command.clean` — Clean a package build area](apiref#module-distutils.command.clean) + [9.39. `distutils.command.config` — Perform package configuration](apiref#module-distutils.command.config) + [9.40. `distutils.command.install` — Install a package](apiref#module-distutils.command.install) + [9.41. `distutils.command.install_data` — Install data files from a package](apiref#module-distutils.command.install_data) + [9.42. `distutils.command.install_headers` — Install C/C++ header files from a package](apiref#module-distutils.command.install_headers) + [9.43. `distutils.command.install_lib` — Install library files from a package](apiref#module-distutils.command.install_lib) + [9.44. `distutils.command.install_scripts` — Install script files from a package](apiref#module-distutils.command.install_scripts) + [9.45. `distutils.command.register` — Register a module with the Python Package Index](apiref#module-distutils.command.register) + [9.46. `distutils.command.check` — Check the meta-data of a package](apiref#module-distutils.command.check) python Writing the Setup Script Writing the Setup Script ========================= Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. The setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing. As we saw in section [A Simple Example](introduction#distutils-simple-example) above, the setup script consists mainly of a call to `setup()`, and most information supplied to the Distutils by the module developer is supplied as keyword arguments to `setup()`. Here’s a slightly more involved example, which we’ll follow for the next couple of sections: the Distutils’ own setup script. (Keep in mind that although the Distutils are included with Python 1.6 and later, they also have an independent existence so that Python 1.5.2 users can use them to install other module distributions. The Distutils’ own setup script, shown here, is used to install the package into Python 1.5.2.) ``` #!/usr/bin/env python from distutils.core import setup setup(name='Distutils', version='1.0', description='Python Distribution Utilities', author='Greg Ward', author_email='[email protected]', url='https://www.python.org/sigs/distutils-sig/', packages=['distutils', 'distutils.command'], ) ``` There are only two differences between this and the trivial one-file distribution presented in section [A Simple Example](introduction#distutils-simple-example): more metadata, and the specification of pure Python modules by package, rather than by module. This is important since the Distutils consist of a couple of dozen modules split into (so far) two packages; an explicit list of every module would be tedious to generate and difficult to maintain. For more information on the additional meta-data, see section [Additional meta-data](#meta-data). Note that any pathnames (files or directories) supplied in the setup script should be written using the Unix convention, i.e. slash-separated. The Distutils will take care of converting this platform-neutral representation into whatever is appropriate on your current platform before actually using the pathname. This makes your setup script portable across operating systems, which of course is one of the major goals of the Distutils. In this spirit, all pathnames in this document are slash-separated. This, of course, only applies to pathnames given to Distutils functions. If you, for example, use standard Python functions such as [`glob.glob()`](../library/glob#glob.glob "glob.glob") or [`os.listdir()`](../library/os#os.listdir "os.listdir") to specify files, you should be careful to write portable code instead of hardcoding path separators: ``` glob.glob(os.path.join('mydir', 'subdir', '*.html')) os.listdir(os.path.join('mydir', 'subdir')) ``` 2.1. Listing whole packages ---------------------------- The `packages` option tells the Distutils to process (build, distribute, install, etc.) all pure Python modules found in each package mentioned in the `packages` list. In order to do this, of course, there has to be a correspondence between package names and directories in the filesystem. The default correspondence is the most obvious one, i.e. package [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") is found in the directory `distutils` relative to the distribution root. Thus, when you say `packages = ['foo']` in your setup script, you are promising that the Distutils will find a file `foo/__init__.py` (which might be spelled differently on your system, but you get the idea) relative to the directory where your setup script lives. If you break this promise, the Distutils will issue a warning but still process the broken package anyway. If you use a different convention to lay out your source directory, that’s no problem: you just have to supply the `package_dir` option to tell the Distutils about your convention. For example, say you keep all Python source under `lib`, so that modules in the “root package” (i.e., not in any package at all) are in `lib`, modules in the `foo` package are in `lib/foo`, and so forth. Then you would put ``` package_dir = {'': 'lib'} ``` in your setup script. The keys to this dictionary are package names, and an empty package name stands for the root package. The values are directory names relative to your distribution root. In this case, when you say `packages = ['foo']`, you are promising that the file `lib/foo/__init__.py` exists. Another possible convention is to put the `foo` package right in `lib`, the `foo.bar` package in `lib/bar`, etc. This would be written in the setup script as ``` package_dir = {'foo': 'lib'} ``` A `package: dir` entry in the `package_dir` dictionary implicitly applies to all packages below *package*, so the `foo.bar` case is automatically handled here. In this example, having `packages = ['foo', 'foo.bar']` tells the Distutils to look for `lib/__init__.py` and `lib/bar/__init__.py`. (Keep in mind that although `package_dir` applies recursively, you must explicitly list all packages in `packages`: the Distutils will *not* recursively scan your source tree looking for any directory with an `__init__.py` file.) 2.2. Listing individual modules -------------------------------- For a small module distribution, you might prefer to list all modules rather than listing packages—especially the case of a single module that goes in the “root package” (i.e., no package at all). This simplest case was shown in section [A Simple Example](introduction#distutils-simple-example); here is a slightly more involved example: ``` py_modules = ['mod1', 'pkg.mod2'] ``` This describes two modules, one of them in the “root” package, the other in the `pkg` package. Again, the default package/directory layout implies that these two modules can be found in `mod1.py` and `pkg/mod2.py`, and that `pkg/__init__.py` exists as well. And again, you can override the package/directory correspondence using the `package_dir` option. 2.3. Describing extension modules ---------------------------------- Just as writing Python extension modules is a bit more complicated than writing pure Python modules, describing them to the Distutils is a bit more complicated. Unlike pure modules, it’s not enough just to list modules or packages and expect the Distutils to go out and find the right files; you have to specify the extension name, source file(s), and any compile/link requirements (include directories, libraries to link with, etc.). All of this is done through another keyword argument to `setup()`, the `ext_modules` option. `ext_modules` is just a list of [`Extension`](apiref#distutils.core.Extension "distutils.core.Extension") instances, each of which describes a single extension module. Suppose your distribution includes a single extension, called `foo` and implemented by `foo.c`. If no additional instructions to the compiler/linker are needed, describing this extension is quite simple: ``` Extension('foo', ['foo.c']) ``` The `Extension` class can be imported from [`distutils.core`](apiref#module-distutils.core "distutils.core: The core Distutils functionality") along with `setup()`. Thus, the setup script for a module distribution that contains only this one extension and nothing else might be: ``` from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` The `Extension` class (actually, the underlying extension-building machinery implemented by the **build\_ext** command) supports a great deal of flexibility in describing Python extensions, which is explained in the following sections. ### 2.3.1. Extension names and packages The first argument to the [`Extension`](apiref#distutils.core.Extension "distutils.core.Extension") constructor is always the name of the extension, including any package names. For example, ``` Extension('foo', ['src/foo1.c', 'src/foo2.c']) ``` describes an extension that lives in the root package, while ``` Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c']) ``` describes the same extension in the `pkg` package. The source files and resulting object code are identical in both cases; the only difference is where in the filesystem (and therefore where in Python’s namespace hierarchy) the resulting extension lives. If you have a number of extensions all in the same package (or all under the same base package), use the `ext_package` keyword argument to `setup()`. For example, ``` setup(..., ext_package='pkg', ext_modules=[Extension('foo', ['foo.c']), Extension('subpkg.bar', ['bar.c'])], ) ``` will compile `foo.c` to the extension `pkg.foo`, and `bar.c` to `pkg.subpkg.bar`. ### 2.3.2. Extension source files The second argument to the [`Extension`](apiref#distutils.core.Extension "distutils.core.Extension") constructor is a list of source files. Since the Distutils currently only support C, C++, and Objective-C extensions, these are normally C/C++/Objective-C source files. (Be sure to use appropriate extensions to distinguish C++ source files: `.cc` and `.cpp` seem to be recognized by both Unix and Windows compilers.) However, you can also include SWIG interface (`.i`) files in the list; the **build\_ext** command knows how to deal with SWIG extensions: it will run SWIG on the interface file and compile the resulting C/C++ file into your extension. This warning notwithstanding, options to SWIG can be currently passed like this: ``` setup(..., ext_modules=[Extension('_foo', ['foo.i'], swig_opts=['-modern', '-I../include'])], py_modules=['foo'], ) ``` Or on the commandline like this: ``` > python setup.py build_ext --swig-opts="-modern -I../include" ``` On some platforms, you can include non-source files that are processed by the compiler and included in your extension. Currently, this just means Windows message text (`.mc`) files and resource definition (`.rc`) files for Visual C++. These will be compiled to binary resource (`.res`) files and linked into the executable. ### 2.3.3. Preprocessor options Three optional arguments to [`Extension`](apiref#distutils.core.Extension "distutils.core.Extension") will help if you need to specify include directories to search or preprocessor macros to define/undefine: `include_dirs`, `define_macros`, and `undef_macros`. For example, if your extension requires header files in the `include` directory under your distribution root, use the `include_dirs` option: ``` Extension('foo', ['foo.c'], include_dirs=['include']) ``` You can specify absolute directories there; if you know that your extension will only be built on Unix systems with X11R6 installed to `/usr`, you can get away with ``` Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11']) ``` You should avoid this sort of non-portable usage if you plan to distribute your code: it’s probably better to write C code like ``` #include <X11/Xlib.h> ``` If you need to include header files from some other Python extension, you can take advantage of the fact that header files are installed in a consistent way by the Distutils **install\_headers** command. For example, the Numerical Python header files are installed (on a standard Unix installation) to `/usr/local/include/python1.5/Numerical`. (The exact location will differ according to your platform and Python installation.) Since the Python include directory—`/usr/local/include/python1.5` in this case—is always included in the search path when building Python extensions, the best approach is to write C code like ``` #include <Numerical/arrayobject.h> ``` If you must put the `Numerical` include directory right into your header search path, though, you can find that directory using the Distutils [`distutils.sysconfig`](apiref#module-distutils.sysconfig "distutils.sysconfig: Low-level access to configuration information of the Python interpreter.") module: ``` from distutils.sysconfig import get_python_inc incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical') setup(..., Extension(..., include_dirs=[incdir]), ) ``` Even though this is quite portable—it will work on any Python installation, regardless of platform—it’s probably easier to just write your C code in the sensible way. You can define and undefine pre-processor macros with the `define_macros` and `undef_macros` options. `define_macros` takes a list of `(name, value)` tuples, where `name` is the name of the macro to define (a string) and `value` is its value: either a string or `None`. (Defining a macro `FOO` to `None` is the equivalent of a bare `#define FOO` in your C source: with most compilers, this sets `FOO` to the string `1`.) `undef_macros` is just a list of macros to undefine. For example: ``` Extension(..., define_macros=[('NDEBUG', '1'), ('HAVE_STRFTIME', None)], undef_macros=['HAVE_FOO', 'HAVE_BAR']) ``` is the equivalent of having this at the top of every C source file: ``` #define NDEBUG 1 #define HAVE_STRFTIME #undef HAVE_FOO #undef HAVE_BAR ``` ### 2.3.4. Library options You can also specify the libraries to link against when building your extension, and the directories to search for those libraries. The `libraries` option is a list of libraries to link against, `library_dirs` is a list of directories to search for libraries at link-time, and `runtime_library_dirs` is a list of directories to search for shared (dynamically loaded) libraries at run-time. For example, if you need to link against libraries known to be in the standard library search path on target systems ``` Extension(..., libraries=['gdbm', 'readline']) ``` If you need to link with libraries in a non-standard location, you’ll have to include the location in `library_dirs`: ``` Extension(..., library_dirs=['/usr/X11R6/lib'], libraries=['X11', 'Xt']) ``` (Again, this sort of non-portable construct should be avoided if you intend to distribute your code.) ### 2.3.5. Other options There are still some other options which can be used to handle special cases. The `optional` option is a boolean; if it is true, a build failure in the extension will not abort the build process, but instead simply not install the failing extension. The `extra_objects` option is a list of object files to be passed to the linker. These files must not have extensions, as the default extension for the compiler is used. `extra_compile_args` and `extra_link_args` can be used to specify additional command line options for the respective compiler and linker command lines. `export_symbols` is only useful on Windows. It can contain a list of symbols (functions or variables) to be exported. This option is not needed when building compiled extensions: Distutils will automatically add `initmodule` to the list of exported symbols. The `depends` option is a list of files that the extension depends on (for example header files). The build command will call the compiler on the sources to rebuild extension if any on this files has been modified since the previous build. 2.4. Relationships between Distributions and Packages ------------------------------------------------------ A distribution may relate to packages in three specific ways: 1. It can require packages or modules. 2. It can provide packages or modules. 3. It can obsolete packages or modules. These relationships can be specified using keyword arguments to the [`distutils.core.setup()`](apiref#distutils.core.setup "distutils.core.setup") function. Dependencies on other Python modules and packages can be specified by supplying the *requires* keyword argument to `setup()`. The value must be a list of strings. Each string specifies a package that is required, and optionally what versions are sufficient. To specify that any version of a module or package is required, the string should consist entirely of the module or package name. Examples include `'mymodule'` and `'xml.parsers.expat'`. If specific versions are required, a sequence of qualifiers can be supplied in parentheses. Each qualifier may consist of a comparison operator and a version number. The accepted comparison operators are: ``` < > == <= >= != ``` These can be combined by using multiple qualifiers separated by commas (and optional whitespace). In this case, all of the qualifiers must be matched; a logical AND is used to combine the evaluations. Let’s look at a bunch of examples: | Requires Expression | Explanation | | --- | --- | | `==1.0` | Only version `1.0` is compatible | | `>1.0, !=1.5.1, <2.0` | Any version after `1.0` and before `2.0` is compatible, except `1.5.1` | Now that we can specify dependencies, we also need to be able to specify what we provide that other distributions can require. This is done using the *provides* keyword argument to `setup()`. The value for this keyword is a list of strings, each of which names a Python module or package, and optionally identifies the version. If the version is not specified, it is assumed to match that of the distribution. Some examples: | Provides Expression | Explanation | | --- | --- | | `mypkg` | Provide `mypkg`, using the distribution version | | `mypkg (1.1)` | Provide `mypkg` version 1.1, regardless of the distribution version | A package can declare that it obsoletes other packages using the *obsoletes* keyword argument. The value for this is similar to that of the *requires* keyword: a list of strings giving module or package specifiers. Each specifier consists of a module or package name optionally followed by one or more version qualifiers. Version qualifiers are given in parentheses after the module or package name. The versions identified by the qualifiers are those that are obsoleted by the distribution being described. If no qualifiers are given, all versions of the named module or package are understood to be obsoleted. 2.5. Installing Scripts ------------------------ So far we have been dealing with pure and non-pure Python modules, which are usually not run by themselves but imported by scripts. Scripts are files containing Python source code, intended to be started from the command line. Scripts don’t require Distutils to do anything very complicated. The only clever feature is that if the first line of the script starts with `#!` and contains the word “python”, the Distutils will adjust the first line to refer to the current interpreter location. By default, it is replaced with the current interpreter location. The `--executable` (or `-e`) option will allow the interpreter path to be explicitly overridden. The `scripts` option simply is a list of files to be handled in this way. From the PyXML setup script: ``` setup(..., scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] ) ``` Changed in version 3.1: All the scripts will also be added to the `MANIFEST` file if no template is provided. See [Specifying the files to distribute](sourcedist#manifest). 2.6. Installing Package Data ----------------------------- Often, additional files need to be installed into a package. These files are often data that’s closely related to the package’s implementation, or text files containing documentation that might be of interest to programmers using the package. These files are called *package data*. Package data can be added to packages using the `package_data` keyword argument to the `setup()` function. The value must be a mapping from package name to a list of relative path names that should be copied into the package. The paths are interpreted as relative to the directory containing the package (information from the `package_dir` mapping is used if appropriate); that is, the files are expected to be part of the package in the source directories. They may contain glob patterns as well. The path names may contain directory portions; any necessary directories will be created in the installation. For example, if a package should contain a subdirectory with several data files, the files can be arranged like this in the source tree: ``` setup.py src/ mypkg/ __init__.py module.py data/ tables.dat spoons.dat forks.dat ``` The corresponding call to `setup()` might be: ``` setup(..., packages=['mypkg'], package_dir={'mypkg': 'src/mypkg'}, package_data={'mypkg': ['data/*.dat']}, ) ``` Changed in version 3.1: All the files that match `package_data` will be added to the `MANIFEST` file if no template is provided. See [Specifying the files to distribute](sourcedist#manifest). 2.7. Installing Additional Files --------------------------------- The `data_files` option can be used to specify additional files needed by the module distribution: configuration files, message catalogs, data files, anything which doesn’t fit in the previous categories. `data_files` specifies a sequence of (*directory*, *files*) pairs in the following way: ``` setup(..., data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']), ('config', ['cfg/data.cfg'])], ) ``` Each (*directory*, *files*) pair in the sequence specifies the installation directory and the files to install there. Each file name in *files* is interpreted relative to the `setup.py` script at the top of the package source distribution. Note that you can specify the directory where the data files will be installed, but you cannot rename the data files themselves. The *directory* should be a relative path. It is interpreted relative to the installation prefix (Python’s `sys.prefix` for system installations; `site.USER_BASE` for user installations). Distutils allows *directory* to be an absolute installation path, but this is discouraged since it is incompatible with the wheel packaging format. No directory information from *files* is used to determine the final location of the installed file; only the name of the file is used. You can specify the `data_files` options as a simple sequence of files without specifying a target directory, but this is not recommended, and the **install** command will print a warning in this case. To install data files directly in the target directory, an empty string should be given as the directory. Changed in version 3.1: All the files that match `data_files` will be added to the `MANIFEST` file if no template is provided. See [Specifying the files to distribute](sourcedist#manifest). 2.8. Additional meta-data -------------------------- The setup script may include additional meta-data beyond the name and version. This information includes: | Meta-Data | Description | Value | Notes | | --- | --- | --- | --- | | `name` | name of the package | short string | (1) | | `version` | version of this release | short string | (1)(2) | | `author` | package author’s name | short string | (3) | | `author_email` | email address of the package author | email address | (3) | | `maintainer` | package maintainer’s name | short string | (3) | | `maintainer_email` | email address of the package maintainer | email address | (3) | | `url` | home page for the package | URL | (1) | | `description` | short, summary description of the package | short string | | | `long_description` | longer description of the package | long string | (4) | | `download_url` | location where the package may be downloaded | URL | | | `classifiers` | a list of classifiers | list of strings | (6)(7) | | `platforms` | a list of platforms | list of strings | (6)(8) | | `keywords` | a list of keywords | list of strings | (6)(8) | | `license` | license for the package | short string | (5) | Notes: 1. These fields are required. 2. It is recommended that versions take the form *major.minor[.patch[.sub]]*. 3. Either the author or the maintainer must be identified. If maintainer is provided, distutils lists it as the author in `PKG-INFO`. 4. The `long_description` field is used by PyPI when you publish a package, to build its project page. 5. The `license` field is a text indicating the license covering the package where the license is not a selection from the “License” Trove classifiers. See the `Classifier` field. Notice that there’s a `licence` distribution option which is deprecated but still acts as an alias for `license`. 6. This field must be a list. 7. The valid classifiers are listed on [PyPI](https://pypi.org/classifiers). 8. To preserve backward compatibility, this field also accepts a string. If you pass a comma-separated string `'foo, bar'`, it will be converted to `['foo', 'bar']`, Otherwise, it will be converted to a list of one string. ‘short string’ A single line of text, not more than 200 characters. ‘long string’ Multiple lines of plain text in reStructuredText format (see <http://docutils.sourceforge.net/>). ‘list of strings’ See below. Encoding the version information is an art in itself. Python packages generally adhere to the version format *major.minor[.patch][sub]*. The major number is 0 for initial, experimental releases of software. It is incremented for releases that represent major milestones in a package. The minor number is incremented when important new features are added to the package. The patch number increments when bug-fix releases are made. Additional trailing version information is sometimes used to indicate sub-releases. These are “a1,a2,…,aN” (for alpha releases, where functionality and API may change), “b1,b2,…,bN” (for beta releases, which only fix bugs) and “pr1,pr2,…,prN” (for final pre-release release testing). Some examples: 0.1.0 the first, experimental release of a package 1.0.1a2 the second alpha release of the first patch version of 1.0 `classifiers` must be specified in a list: ``` setup(..., classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Python Software Foundation License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Communications :: Email', 'Topic :: Office/Business', 'Topic :: Software Development :: Bug Tracking', ], ) ``` Changed in version 3.7: [`setup`](apiref#distutils.core.setup "distutils.core.setup") now warns when `classifiers`, `keywords` or `platforms` fields are not specified as a list or a string. 2.9. Debugging the setup script -------------------------------- Sometimes things go wrong, and the setup script doesn’t do what the developer wants. Distutils catches any exceptions when running the setup script, and print a simple error message before the script is terminated. The motivation for this behaviour is to not confuse administrators who don’t know much about Python and are trying to install a package. If they get a big long traceback from deep inside the guts of Distutils, they may think the package or the Python installation is broken because they don’t read all the way down to the bottom and see that it’s a permission problem. On the other hand, this doesn’t help the developer to find the cause of the failure. For this purpose, the `DISTUTILS_DEBUG` environment variable can be set to anything except an empty string, and distutils will now print detailed information about what it is doing, dump the full traceback when an exception occurs, and print the whole command line when an external program (like a C compiler) fails.
programming_docs
python API Reference API Reference ============== See also [New and changed setup.py arguments in setuptools](https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords) The `setuptools` project adds new capabilities to the `setup` function and other APIs, makes the API consistent across different Python versions, and is hence recommended over using `distutils` directly. Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. 9.1. distutils.core — Core Distutils functionality --------------------------------------------------- The [`distutils.core`](#module-distutils.core "distutils.core: The core Distutils functionality") module is the only module that needs to be installed to use the Distutils. It provides the [`setup()`](#distutils.core.setup "distutils.core.setup") (which is called from the setup script). Indirectly provides the `distutils.dist.Distribution` and [`distutils.cmd.Command`](#distutils.cmd.Command "distutils.cmd.Command") class. `distutils.core.setup(arguments)` The basic do-everything function that does most everything you could ever ask for from a Distutils method. The setup function takes a large number of arguments. These are laid out in the following table. | argument name | value | type | | --- | --- | --- | | *name* | The name of the package | a string | | *version* | The version number of the package; see [`distutils.version`](#module-distutils.version "distutils.version: Implements classes that represent module version numbers.") | a string | | *description* | A single line describing the package | a string | | *long\_description* | Longer description of the package | a string | | *author* | The name of the package author | a string | | *author\_email* | The email address of the package author | a string | | *maintainer* | The name of the current maintainer, if different from the author. Note that if the maintainer is provided, distutils will use it as the author in `PKG-INFO` | a string | | *maintainer\_email* | The email address of the current maintainer, if different from the author | a string | | *url* | A URL for the package (homepage) | a string | | *download\_url* | A URL to download the package | a string | | *packages* | A list of Python packages that distutils will manipulate | a list of strings | | *py\_modules* | A list of Python modules that distutils will manipulate | a list of strings | | *scripts* | A list of standalone script files to be built and installed | a list of strings | | *ext\_modules* | A list of Python extensions to be built | a list of instances of [`distutils.core.Extension`](#distutils.core.Extension "distutils.core.Extension") | | *classifiers* | A list of categories for the package | a list of strings; valid classifiers are listed on [PyPI](https://pypi.org/classifiers). | | *distclass* | the [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") class to use | a subclass of [`distutils.core.Distribution`](#distutils.core.Distribution "distutils.core.Distribution") | | *script\_name* | The name of the setup.py script - defaults to `sys.argv[0]` | a string | | *script\_args* | Arguments to supply to the setup script | a list of strings | | *options* | default options for the setup script | a dictionary | | *license* | The license for the package | a string | | *keywords* | Descriptive meta-data, see [**PEP 314**](https://www.python.org/dev/peps/pep-0314) | a list of strings or a comma-separated string | | *platforms* | | a list of strings or a comma-separated string | | *cmdclass* | A mapping of command names to [`Command`](#distutils.core.Command "distutils.core.Command") subclasses | a dictionary | | *data\_files* | A list of data files to install | a list | | *package\_dir* | A mapping of package to directory names | a dictionary | `distutils.core.run_setup(script_name[, script_args=None, stop_after='run'])` Run a setup script in a somewhat controlled environment, and return the `distutils.dist.Distribution` instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from *script* to [`setup()`](#distutils.core.setup "distutils.core.setup")), or the contents of the config files or command-line. *script\_name* is a file that will be read and run with [`exec()`](../library/functions#exec "exec"). `sys.argv[0]` will be replaced with *script* for the duration of the call. *script\_args* is a list of strings; if supplied, `sys.argv[1:]` will be replaced by *script\_args* for the duration of the call. *stop\_after* tells [`setup()`](#distutils.core.setup "distutils.core.setup") when to stop processing; possible values: | value | description | | --- | --- | | *init* | Stop after the [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") instance has been created and populated with the keyword arguments to [`setup()`](#distutils.core.setup "distutils.core.setup") | | *config* | Stop after config files have been parsed (and their data stored in the [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") instance) | | *commandline* | Stop after the command-line (`sys.argv[1:]` or *script\_args*) have been parsed (and the data stored in the [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") instance.) | | *run* | Stop after all commands have been run (the same as if [`setup()`](#distutils.core.setup "distutils.core.setup") had been called in the usual way). This is the default value. | In addition, the [`distutils.core`](#module-distutils.core "distutils.core: The core Distutils functionality") module exposed a number of classes that live elsewhere. * `Extension` from [`distutils.extension`](#module-distutils.extension "distutils.extension: Provides the Extension class, used to describe C/C++ extension modules in setup scripts") * [`Command`](#distutils.cmd.Command "distutils.cmd.Command") from [`distutils.cmd`](#module-distutils.cmd "distutils.cmd: Provides the abstract base class :class:`~distutils.cmd.Command`. This class is subclassed by the modules in the distutils.command subpackage.") * `Distribution` from [`distutils.dist`](#module-distutils.dist "distutils.dist: Provides the Distribution class, which represents the module distribution being built/installed/distributed") A short description of each of these follows, but see the relevant module for the full reference. `class distutils.core.Extension` The Extension class describes a single C or C++ extension module in a setup script. It accepts the following keyword arguments in its constructor: | argument name | value | type | | --- | --- | --- | | *name* | the full name of the extension, including any packages — ie. *not* a filename or pathname, but Python dotted name | a string | | *sources* | list of source filenames, relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the **build\_ext** command as source for a Python extension. | a list of strings | | *include\_dirs* | list of directories to search for C/C++ header files (in Unix form for portability) | a list of strings | | *define\_macros* | list of macros to define; each macro is defined using a 2-tuple `(name, value)`, where *value* is either the string to define it to or `None` to define it without a particular value (equivalent of `#define FOO` in source or `-DFOO` on Unix C compiler command line) | a list of tuples | | *undef\_macros* | list of macros to undefine explicitly | a list of strings | | *library\_dirs* | list of directories to search for C/C++ libraries at link time | a list of strings | | *libraries* | list of library names (not filenames or paths) to link against | a list of strings | | *runtime\_library\_dirs* | list of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded) | a list of strings | | *extra\_objects* | list of extra files to link with (eg. object files not implied by ‘sources’, static library that must be explicitly specified, binary resource files, etc.) | a list of strings | | *extra\_compile\_args* | any extra platform- and compiler-specific information to use when compiling the source files in ‘sources’. For platforms and compilers where a command line makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. | a list of strings | | *extra\_link\_args* | any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for ‘extra\_compile\_args’. | a list of strings | | *export\_symbols* | list of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: `init` + extension\_name. | a list of strings | | *depends* | list of files that the extension depends on | a list of strings | | *language* | extension language (i.e. `'c'`, `'c++'`, `'objc'`). Will be detected from the source extensions if not provided. | a string | | *optional* | specifies that a build failure in the extension should not abort the build process, but simply skip the extension. | a boolean | Changed in version 3.8: On Unix, C extensions are no longer linked to libpython except on Android and Cygwin. `class distutils.core.Distribution` A [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") describes how to build, install and package up a Python software package. See the [`setup()`](#distutils.core.setup "distutils.core.setup") function for a list of keyword arguments accepted by the Distribution constructor. [`setup()`](#distutils.core.setup "distutils.core.setup") creates a Distribution instance. Changed in version 3.7: [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") now warns if `classifiers`, `keywords` and `platforms` fields are not specified as a list or a string. `class distutils.core.Command` A [`Command`](#distutils.core.Command "distutils.core.Command") class (or rather, an instance of one of its subclasses) implement a single distutils command. 9.2. distutils.ccompiler — CCompiler base class ------------------------------------------------ This module provides the abstract base class for the [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") classes. A [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") instance can be used for all the compile and link steps needed to build a single project. Methods are provided to set options for the compiler — macro definitions, include directories, link path, libraries and the like. This module provides the following functions. `distutils.ccompiler.gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries)` Generate linker options for searching library directories and linking with specific libraries. *libraries* and *library\_dirs* are, respectively, lists of library names (not filenames!) and search directories. Returns a list of command-line options suitable for use with some compiler (depending on the two format strings passed in). `distutils.ccompiler.gen_preprocess_options(macros, include_dirs)` Generate C pre-processor options (`-D`, `-U`, `-I`) as used by at least two types of compilers: the typical Unix compiler and Visual C++. *macros* is the usual thing, a list of 1- or 2-tuples, where `(name,)` means undefine (`-U`) macro *name*, and `(name, value)` means define (`-D`) macro *name* to *value*. *include\_dirs* is just a list of directory names to be added to the header file search path (`-I`). Returns a list of command-line options suitable for either Unix compilers or Visual C++. `distutils.ccompiler.get_default_compiler(osname, platform)` Determine the default compiler to use for the given platform. *osname* should be one of the standard Python OS names (i.e. the ones returned by `os.name`) and *platform* the common value returned by `sys.platform` for the platform in question. The default values are `os.name` and `sys.platform` in case the parameters are not given. `distutils.ccompiler.new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0)` Factory function to generate an instance of some CCompiler subclass for the supplied platform/compiler combination. *plat* defaults to `os.name` (eg. `'posix'`, `'nt'`), and *compiler* defaults to the default compiler for that platform. Currently only `'posix'` and `'nt'` are supported, and the default compilers are “traditional Unix interface” (`UnixCCompiler` class) and Visual C++ (`MSVCCompiler` class). Note that it’s perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix—if you supply a value for *compiler*, *plat* is ignored. `distutils.ccompiler.show_compilers()` Print list of available compilers (used by the `--help-compiler` options to **build**, **build\_ext**, **build\_clib**). `class distutils.ccompiler.CCompiler([verbose=0, dry_run=0, force=0])` The abstract base class [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") defines the interface that must be implemented by real compiler classes. The class also has some utility methods used by several compiler classes. The basic idea behind a compiler abstraction class is that each instance can be used for all the compile/link steps in building a single project. Thus, attributes common to all of those compile and link steps — include directories, macros to define, libraries to link against, etc. — are attributes of the compiler instance. To allow for variability in how individual files are treated, most of those attributes may be varied on a per-compilation or per-link basis. The constructor for each subclass creates an instance of the Compiler object. Flags are *verbose* (show verbose output), *dry\_run* (don’t actually execute the steps) and *force* (rebuild everything, regardless of dependencies). All of these flags default to `0` (off). Note that you probably don’t want to instantiate [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") or one of its subclasses directly - use the `distutils.CCompiler.new_compiler()` factory function instead. The following methods allow you to manually alter compiler options for the instance of the Compiler class. `add_include_dir(dir)` Add *dir* to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to [`add_include_dir()`](#distutils.ccompiler.CCompiler.add_include_dir "distutils.ccompiler.CCompiler.add_include_dir"). `set_include_dirs(dirs)` Set the list of directories that will be searched to *dirs* (a list of strings). Overrides any preceding calls to [`add_include_dir()`](#distutils.ccompiler.CCompiler.add_include_dir "distutils.ccompiler.CCompiler.add_include_dir"); subsequent calls to [`add_include_dir()`](#distutils.ccompiler.CCompiler.add_include_dir "distutils.ccompiler.CCompiler.add_include_dir") add to the list passed to [`set_include_dirs()`](#distutils.ccompiler.CCompiler.set_include_dirs "distutils.ccompiler.CCompiler.set_include_dirs"). This does not affect any list of standard include directories that the compiler may search by default. `add_library(libname)` Add *libname* to the list of libraries that will be included in all links driven by this compiler object. Note that *libname* should \*not\* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform). The linker will be instructed to link against libraries in the order they were supplied to [`add_library()`](#distutils.ccompiler.CCompiler.add_library "distutils.ccompiler.CCompiler.add_library") and/or [`set_libraries()`](#distutils.ccompiler.CCompiler.set_libraries "distutils.ccompiler.CCompiler.set_libraries"). It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned. `set_libraries(libnames)` Set the list of libraries to be included in all links driven by this compiler object to *libnames* (a list of strings). This does not affect any standard system libraries that the linker may include by default. `add_library_dir(dir)` Add *dir* to the list of directories that will be searched for libraries specified to [`add_library()`](#distutils.ccompiler.CCompiler.add_library "distutils.ccompiler.CCompiler.add_library") and [`set_libraries()`](#distutils.ccompiler.CCompiler.set_libraries "distutils.ccompiler.CCompiler.set_libraries"). The linker will be instructed to search for libraries in the order they are supplied to [`add_library_dir()`](#distutils.ccompiler.CCompiler.add_library_dir "distutils.ccompiler.CCompiler.add_library_dir") and/or [`set_library_dirs()`](#distutils.ccompiler.CCompiler.set_library_dirs "distutils.ccompiler.CCompiler.set_library_dirs"). `set_library_dirs(dirs)` Set the list of library search directories to *dirs* (a list of strings). This does not affect any standard library search path that the linker may search by default. `add_runtime_library_dir(dir)` Add *dir* to the list of directories that will be searched for shared libraries at runtime. `set_runtime_library_dirs(dirs)` Set the list of directories to search for shared libraries at runtime to *dirs* (a list of strings). This does not affect any standard search path that the runtime linker may search by default. `define_macro(name[, value=None])` Define a preprocessor macro for all compilations driven by this compiler object. The optional parameter *value* should be a string; if it is not supplied, then the macro will be defined without an explicit value and the exact outcome depends on the compiler used. `undefine_macro(name)` Undefine a preprocessor macro for all compilations driven by this compiler object. If the same macro is defined by [`define_macro()`](#distutils.ccompiler.CCompiler.define_macro "distutils.ccompiler.CCompiler.define_macro") and undefined by [`undefine_macro()`](#distutils.ccompiler.CCompiler.undefine_macro "distutils.ccompiler.CCompiler.undefine_macro") the last call takes precedence (including multiple redefinitions or undefinitions). If the macro is redefined/undefined on a per-compilation basis (ie. in the call to [`compile()`](../library/functions#compile "compile")), then that takes precedence. `add_link_object(object)` Add *object* to the list of object files (or analogues, such as explicitly named library files or the output of “resource compilers”) to be included in every link driven by this compiler object. `set_link_objects(objects)` Set the list of object files (or analogues) to be included in every link to *objects*. This does not affect any standard object files that the linker may include by default (such as system libraries). The following methods implement methods for autodetection of compiler options, providing some functionality similar to GNU **autoconf**. `detect_language(sources)` Detect the language of a given file, or list of files. Uses the instance attributes `language_map` (a dictionary), and `language_order` (a list) to do the job. `find_library_file(dirs, lib[, debug=0])` Search the specified list of directories for a static or shared library file *lib* and return the full path to that file. If *debug* is true, look for a debugging version (if that makes sense on the current platform). Return `None` if *lib* wasn’t found in any of the specified directories. `has_function(funcname[, includes=None, include_dirs=None, libraries=None, library_dirs=None])` Return a boolean indicating whether *funcname* is supported on the current platform. The optional arguments can be used to augment the compilation environment by providing additional include files and paths and libraries and paths. `library_dir_option(dir)` Return the compiler option to add *dir* to the list of directories searched for libraries. `library_option(lib)` Return the compiler option to add *lib* to the list of libraries linked into the shared library or executable. `runtime_library_dir_option(dir)` Return the compiler option to add *dir* to the list of directories searched for runtime libraries. `set_executables(**args)` Define the executables (and options for them) that will be run to perform the various stages of compilation. The exact set of executables that may be specified here depends on the compiler class (via the ‘executables’ class attribute), but most will have: | attribute | description | | --- | --- | | *compiler* | the C/C++ compiler | | *linker\_so* | linker used to create shared objects and libraries | | *linker\_exe* | linker used to create binary executables | | *archiver* | static library creator | On platforms with a command-line (Unix, DOS/Windows), each of these is a string that will be split into executable name and (optional) list of arguments. (Splitting the string is done similarly to how Unix shells operate: words are delimited by spaces, but quotes and backslashes can override this. See [`distutils.util.split_quoted()`](#distutils.util.split_quoted "distutils.util.split_quoted").) The following methods invoke stages in the build process. `compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None])` Compile one or more source files. Generates object files (e.g. transforms a `.c` file to a `.o` file.) *sources* must be a list of filenames, most likely C/C++ files, but in reality anything that can be handled by a particular compiler and compiler class (eg. `MSVCCompiler` can handle resource files in *sources*). Return a list of object filenames, one per source filename in *sources*. Depending on the implementation, not all source files will necessarily be compiled, but all corresponding object filenames will be returned. If *output\_dir* is given, object files will be put under it, while retaining their original path component. That is, `foo/bar.c` normally compiles to `foo/bar.o` (for a Unix implementation); if *output\_dir* is *build*, then it would compile to `build/foo/bar.o`. *macros*, if given, must be a list of macro definitions. A macro definition is either a `(name, value)` 2-tuple or a `(name,)` 1-tuple. The former defines a macro; if the value is `None`, the macro is defined without an explicit value. The 1-tuple case undefines a macro. Later definitions/redefinitions/undefinitions take precedence. *include\_dirs*, if given, must be a list of strings, the directories to add to the default include file search path for this compilation only. *debug* is a boolean; if true, the compiler will be instructed to output debug symbols in (or alongside) the object file(s). *extra\_preargs* and *extra\_postargs* are implementation-dependent. On platforms that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most likely lists of strings: extra command-line arguments to prepend/append to the compiler command line. On other platforms, consult the implementation class documentation. In any event, they are intended as an escape hatch for those occasions when the abstract compiler framework doesn’t cut the mustard. *depends*, if given, is a list of filenames that all targets depend on. If a source file is older than any file in depends, then the source file will be recompiled. This supports dependency tracking, but only at a coarse granularity. Raises `CompileError` on failure. `create_static_lib(objects, output_libname[, output_dir=None, debug=0, target_lang=None])` Link a bunch of stuff together to create a static library file. The “bunch of stuff” consists of the list of object files supplied as *objects*, the extra object files supplied to [`add_link_object()`](#distutils.ccompiler.CCompiler.add_link_object "distutils.ccompiler.CCompiler.add_link_object") and/or [`set_link_objects()`](#distutils.ccompiler.CCompiler.set_link_objects "distutils.ccompiler.CCompiler.set_link_objects"), the libraries supplied to [`add_library()`](#distutils.ccompiler.CCompiler.add_library "distutils.ccompiler.CCompiler.add_library") and/or [`set_libraries()`](#distutils.ccompiler.CCompiler.set_libraries "distutils.ccompiler.CCompiler.set_libraries"), and the libraries supplied as *libraries* (if any). *output\_libname* should be a library name, not a filename; the filename will be inferred from the library name. *output\_dir* is the directory where the library file will be put. *debug* is a boolean; if true, debugging information will be included in the library (note that on most platforms, it is the compile step where this matters: the *debug* flag is included here just for consistency). *target\_lang* is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises `LibError` on failure. `link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])` Link a bunch of stuff together to create an executable or shared library file. The “bunch of stuff” consists of the list of object files supplied as *objects*. *output\_filename* should be a filename. If *output\_dir* is supplied, *output\_filename* is relative to it (i.e. *output\_filename* can provide directory components if needed). *libraries* is a list of libraries to link against. These are library names, not filenames, since they’re translated into filenames in a platform-specific way (eg. *foo* becomes `libfoo.a` on Unix and `foo.lib` on DOS/Windows). However, they can include a directory component, which means the linker will look in that specific directory rather than searching all the normal locations. *library\_dirs*, if supplied, should be a list of directories to search for libraries that were specified as bare library names (ie. no directory component). These are on top of the system default and those supplied to [`add_library_dir()`](#distutils.ccompiler.CCompiler.add_library_dir "distutils.ccompiler.CCompiler.add_library_dir") and/or [`set_library_dirs()`](#distutils.ccompiler.CCompiler.set_library_dirs "distutils.ccompiler.CCompiler.set_library_dirs"). *runtime\_library\_dirs* is a list of directories that will be embedded into the shared library and used to search for other shared libraries that \*it\* depends on at run-time. (This may only be relevant on Unix.) *export\_symbols* is a list of symbols that the shared library will export. (This appears to be relevant only on Windows.) *debug* is as for [`compile()`](../library/functions#compile "compile") and [`create_static_lib()`](#distutils.ccompiler.CCompiler.create_static_lib "distutils.ccompiler.CCompiler.create_static_lib"), with the slight distinction that it actually matters on most platforms (as opposed to [`create_static_lib()`](#distutils.ccompiler.CCompiler.create_static_lib "distutils.ccompiler.CCompiler.create_static_lib"), which includes a *debug* flag mostly for form’s sake). *extra\_preargs* and *extra\_postargs* are as for [`compile()`](../library/functions#compile "compile") (except of course that they supply command-line arguments for the particular linker being used). *target\_lang* is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises `LinkError` on failure. `link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None])` Link an executable. *output\_progname* is the name of the file executable, while *objects* are a list of object filenames to link in. Other arguments are as for the [`link()`](#distutils.ccompiler.CCompiler.link "distutils.ccompiler.CCompiler.link") method. `link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])` Link a shared library. *output\_libname* is the name of the output library, while *objects* is a list of object filenames to link in. Other arguments are as for the [`link()`](#distutils.ccompiler.CCompiler.link "distutils.ccompiler.CCompiler.link") method. `link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])` Link a shared object. *output\_filename* is the name of the shared object that will be created, while *objects* is a list of object filenames to link in. Other arguments are as for the [`link()`](#distutils.ccompiler.CCompiler.link "distutils.ccompiler.CCompiler.link") method. `preprocess(source[, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None])` Preprocess a single C/C++ source file, named in *source*. Output will be written to file named *output\_file*, or *stdout* if *output\_file* not supplied. *macros* is a list of macro definitions as for [`compile()`](../library/functions#compile "compile"), which will augment the macros set with [`define_macro()`](#distutils.ccompiler.CCompiler.define_macro "distutils.ccompiler.CCompiler.define_macro") and [`undefine_macro()`](#distutils.ccompiler.CCompiler.undefine_macro "distutils.ccompiler.CCompiler.undefine_macro"). *include\_dirs* is a list of directory names that will be added to the default list, in the same way as [`add_include_dir()`](#distutils.ccompiler.CCompiler.add_include_dir "distutils.ccompiler.CCompiler.add_include_dir"). Raises `PreprocessError` on failure. The following utility methods are defined by the [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") class, for use by the various concrete subclasses. `executable_filename(basename[, strip_dir=0, output_dir=''])` Returns the filename of the executable for the given *basename*. Typically for non-Windows platforms this is the same as the basename, while Windows will get a `.exe` added. `library_filename(libname[, lib_type='static', strip_dir=0, output_dir=''])` Returns the filename for the given library name on the current platform. On Unix a library with *lib\_type* of `'static'` will typically be of the form `liblibname.a`, while a *lib\_type* of `'dynamic'` will be of the form `liblibname.so`. `object_filenames(source_filenames[, strip_dir=0, output_dir=''])` Returns the name of the object files for the given source files. *source\_filenames* should be a list of filenames. `shared_object_filename(basename[, strip_dir=0, output_dir=''])` Returns the name of a shared object file for the given file name *basename*. `execute(func, args[, msg=None, level=1])` Invokes [`distutils.util.execute()`](#distutils.util.execute "distutils.util.execute"). This method invokes a Python function *func* with the given arguments *args*, after logging and taking into account the *dry\_run* flag. `spawn(cmd)` Invokes `distutils.util.spawn()`. This invokes an external process to run the given command. `mkpath(name[, mode=511])` Invokes [`distutils.dir_util.mkpath()`](#distutils.dir_util.mkpath "distutils.dir_util.mkpath"). This creates a directory and any missing ancestor directories. `move_file(src, dst)` Invokes [`distutils.file_util.move_file()`](#distutils.file_util.move_file "distutils.file_util.move_file"). Renames *src* to *dst*. `announce(msg[, level=1])` Write a message using `distutils.log.debug()`. `warn(msg)` Write a warning message *msg* to standard error. `debug_print(msg)` If the *debug* flag is set on this [`CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") instance, print *msg* to standard output, otherwise do nothing. 9.3. distutils.unixccompiler — Unix C Compiler ----------------------------------------------- This module provides the `UnixCCompiler` class, a subclass of `CCompiler` that handles the typical Unix-style command-line C compiler: * macros defined with `-Dname[=value]` * macros undefined with `-Uname` * include search directories specified with `-Idir` * libraries specified with `-llib` * library search directories specified with `-Ldir` * compile handled by **cc** (or similar) executable with `-c` option: compiles `.c` to `.o` * link static library handled by **ar** command (possibly with **ranlib**) * link shared library handled by **cc** `-shared` 9.4. distutils.msvccompiler — Microsoft Compiler ------------------------------------------------- This module provides `MSVCCompiler`, an implementation of the abstract `CCompiler` class for Microsoft Visual Studio. Typically, extension modules need to be compiled with the same compiler that was used to compile Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python 2.4 and 2.5, the compiler is Visual Studio .NET 2003. `MSVCCompiler` will normally choose the right compiler, linker etc. on its own. To override this choice, the environment variables *DISTUTILS\_USE\_SDK* and *MSSdk* must be both set. *MSSdk* indicates that the current environment has been setup by the SDK’s `SetEnv.Cmd` script, or that the environment variables had been registered when the SDK was installed; *DISTUTILS\_USE\_SDK* indicates that the distutils user has made an explicit choice to override the compiler selection by `MSVCCompiler`. 9.5. distutils.bcppcompiler — Borland Compiler ----------------------------------------------- This module provides `BorlandCCompiler`, a subclass of the abstract `CCompiler` class for the Borland C++ compiler. 9.6. `distutils.cygwincompiler` — Cygwin Compiler -------------------------------------------------- This module provides the `CygwinCCompiler` class, a subclass of `UnixCCompiler` that handles the Cygwin port of the GNU C compiler to Windows. It also contains the Mingw32CCompiler class which handles the mingw32 port of GCC (same as cygwin in no-cygwin mode). 9.7. distutils.archive\_util — Archiving utilities --------------------------------------------------- This module provides a few functions for creating archive files, such as tarballs or zipfiles. `distutils.archive_util.make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0])` Create an archive file (eg. `zip` or `tar`). *base\_name* is the name of the file to create, minus any format-specific extension; *format* is the archive format: one of `zip`, `tar`, `gztar`, `bztar`, `xztar`, or `ztar`. *root\_dir* is a directory that will be the root directory of the archive; ie. we typically `chdir` into *root\_dir* before creating the archive. *base\_dir* is the directory where we start archiving from; ie. *base\_dir* will be the common prefix of all files and directories in the archive. *root\_dir* and *base\_dir* both default to the current directory. Returns the name of the archive file. Changed in version 3.5: Added support for the `xztar` format. `distutils.archive_util.make_tarball(base_name, base_dir[, compress='gzip', verbose=0, dry_run=0])` ‘Create an (optional compressed) archive as a tar file from all files in and under *base\_dir*. *compress* must be `'gzip'` (the default), `'bzip2'`, `'xz'`, `'compress'`, or `None`. For the `'compress'` method the compression utility named by **compress** must be on the default program search path, so this is probably Unix-specific. The output tar file will be named `base_dir.tar`, possibly plus the appropriate compression extension (`.gz`, `.bz2`, `.xz` or `.Z`). Return the output filename. Changed in version 3.5: Added support for the `xz` compression. `distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])` Create a zip file from all files in and under *base\_dir*. The output zip file will be named *base\_name* + `.zip`. Uses either the [`zipfile`](../library/zipfile#module-zipfile "zipfile: Read and write ZIP-format archive files.") Python module (if available) or the InfoZIP `zip` utility (if installed and found on the default search path). If neither tool is available, raises `DistutilsExecError`. Returns the name of the output zip file. 9.8. distutils.dep\_util — Dependency checking ----------------------------------------------- This module provides functions for performing simple, timestamp-based dependency of files and groups of files; also, functions based entirely on such timestamp dependency analysis. `distutils.dep_util.newer(source, target)` Return true if *source* exists and is more recently modified than *target*, or if *source* exists and *target* doesn’t. Return false if both exist and *target* is the same age or newer than *source*. Raise `DistutilsFileError` if *source* does not exist. `distutils.dep_util.newer_pairwise(sources, targets)` Walk two filename lists in parallel, testing if each source is newer than its corresponding target. Return a pair of lists (*sources*, *targets*) where source is newer than target, according to the semantics of [`newer()`](#distutils.dep_util.newer "distutils.dep_util.newer"). `distutils.dep_util.newer_group(sources, target[, missing='error'])` Return true if *target* is out-of-date with respect to any file listed in *sources*. In other words, if *target* exists and is newer than every file in *sources*, return false; otherwise return true. *missing* controls what we do when a source file is missing; the default (`'error'`) is to blow up with an [`OSError`](../library/exceptions#OSError "OSError") from inside [`os.stat()`](../library/os#os.stat "os.stat"); if it is `'ignore'`, we silently drop any missing source files; if it is `'newer'`, any missing source files make us assume that *target* is out-of-date (this is handy in “dry-run” mode: it’ll make you pretend to carry out commands that wouldn’t work because inputs are missing, but that doesn’t matter because you’re not actually going to run the commands). 9.9. distutils.dir\_util — Directory tree operations ----------------------------------------------------- This module provides functions for operating on directories and trees of directories. `distutils.dir_util.mkpath(name[, mode=0o777, verbose=0, dry_run=0])` Create a directory and any missing ancestor directories. If the directory already exists (or if *name* is the empty string, which means the current directory, which of course exists), then do nothing. Raise `DistutilsFileError` if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If *verbose* is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created. `distutils.dir_util.create_tree(base_dir, files[, mode=0o777, verbose=0, dry_run=0])` Create all the empty directories under *base\_dir* needed to put *files* there. *base\_dir* is just the name of a directory which doesn’t necessarily exist yet; *files* is a list of filenames to be interpreted relative to *base\_dir*. *base\_dir* + the directory portion of every file in *files* will be created if it doesn’t already exist. *mode*, *verbose* and *dry\_run* flags are as for [`mkpath()`](#distutils.dir_util.mkpath "distutils.dir_util.mkpath"). `distutils.dir_util.copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0])` Copy an entire directory tree *src* to a new location *dst*. Both *src* and *dst* must be directory names. If *src* is not a directory, raise `DistutilsFileError`. If *dst* does not exist, it is created with [`mkpath()`](#distutils.dir_util.mkpath "distutils.dir_util.mkpath"). The end result of the copy is that every file in *src* is copied to *dst*, and directories under *src* are recursively copied to *dst*. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by *update* or *dry\_run*: it is simply the list of all files under *src*, with the names changed to be under *dst*. *preserve\_mode* and *preserve\_times* are the same as for [`distutils.file_util.copy_file()`](#distutils.file_util.copy_file "distutils.file_util.copy_file"); note that they only apply to regular files, not to directories. If *preserve\_symlinks* is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. *update* and *verbose* are the same as for `copy_file()`. Files in *src* that begin with `.nfs` are skipped (more information on these files is available in answer D2 of the [NFS FAQ page](http://nfs.sourceforge.net/#section_d)). Changed in version 3.3.1: NFS files are ignored. `distutils.dir_util.remove_tree(directory[, verbose=0, dry_run=0])` Recursively remove *directory* and all files and directories underneath it. Any errors are ignored (apart from being reported to `sys.stdout` if *verbose* is true). 9.10. distutils.file\_util — Single file operations ---------------------------------------------------- This module contains some utility functions for operating on individual files. `distutils.file_util.copy_file(src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0])` Copy file *src* to *dst*. If *dst* is a directory, then *src* is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If *preserve\_mode* is true (the default), the file’s mode (type and permission bits, or whatever is analogous on the current platform) is copied. If *preserve\_times* is true (the default), the last-modified and last-access times are copied as well. If *update* is true, *src* will only be copied if *dst* does not exist, or if *dst* does exist but is older than *src*. *link* allows you to make hard links (using [`os.link()`](../library/os#os.link "os.link")) or symbolic links (using [`os.symlink()`](../library/os#os.symlink "os.symlink")) instead of copying: set it to `'hard'` or `'sym'`; if it is `None` (the default), files are copied. Don’t set *link* on systems that don’t support it: [`copy_file()`](#distutils.file_util.copy_file "distutils.file_util.copy_file") doesn’t check if hard or symbolic linking is available. It uses `_copy_file_contents()` to copy file contents. Return a tuple `(dest_name, copied)`: *dest\_name* is the actual name of the output file, and *copied* is true if the file was copied (or would have been copied, if *dry\_run* true). `distutils.file_util.move_file(src, dst[, verbose, dry_run])` Move file *src* to *dst*. If *dst* is a directory, the file will be moved into it with the same name; otherwise, *src* is just renamed to *dst*. Returns the new full name of the file. Warning Handles cross-device moves on Unix using [`copy_file()`](#distutils.file_util.copy_file "distutils.file_util.copy_file"). What about other systems? `distutils.file_util.write_file(filename, contents)` Create a file called *filename* and write *contents* (a sequence of strings without line terminators) to it. 9.11. distutils.util — Miscellaneous other utility functions ------------------------------------------------------------- This module contains other assorted bits and pieces that don’t fit into any other utility module. `distutils.util.get_platform()` Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by ‘os.uname()’), although the exact information included depends on the OS; e.g., on Linux, the kernel version isn’t particularly important. Examples of returned values: * `linux-i586` * `linux-alpha` * `solaris-2.6-sun4u` For non-POSIX platforms, currently just returns `sys.platform`. For macOS systems the OS version reflects the minimal version on which binaries will run (that is, the value of `MACOSX_DEPLOYMENT_TARGET` during the build of Python), not the OS version of the current system. For universal binary builds on macOS the architecture value reflects the universal binary status instead of the architecture of the current processor. For 32-bit universal binaries the architecture is `fat`, for 64-bit universal binaries the architecture is `fat64`, and for 4-way universal binaries the architecture is `universal`. Starting from Python 2.7 and Python 3.2 the architecture `fat3` is used for a 3-way universal build (ppc, i386, x86\_64) and `intel` is used for a universal build with the i386 and x86\_64 architectures Examples of returned values on macOS: * `macosx-10.3-ppc` * `macosx-10.3-fat` * `macosx-10.5-universal` * `macosx-10.6-intel` For AIX, Python 3.9 and later return a string starting with “aix”, followed by additional fields (separated by `'-'`) that represent the combined values of AIX Version, Release and Technology Level (first field), Build Date (second field), and bit-size (third field). Python 3.8 and earlier returned only a single additional field with the AIX Version and Release. Examples of returned values on AIX: * `aix-5307-0747-32` # 32-bit build on AIX `oslevel -s`: 5300-07-00-0000 * `aix-7105-1731-64` # 64-bit build on AIX `oslevel -s`: 7100-05-01-1731 * `aix-7.2` # Legacy form reported in Python 3.8 and earlier Changed in version 3.9: The AIX platform string format now also includes the technology level, build date, and ABI bit-size. `distutils.util.convert_path(pathname)` Return ‘pathname’ as a name that will work on the native filesystem, i.e. split it on ‘/’ and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises [`ValueError`](../library/exceptions#ValueError "ValueError") on non-Unix-ish systems if *pathname* either starts or ends with a slash. `distutils.util.change_root(new_root, pathname)` Return *pathname* with *new\_root* prepended. If *pathname* is relative, this is equivalent to `os.path.join(new_root,pathname)` Otherwise, it requires making *pathname* relative and then joining the two, which is tricky on DOS/Windows. `distutils.util.check_environ()` Ensure that ‘os.environ’ has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes: * `HOME` - user’s home directory (Unix only) * `PLAT` - description of the current platform, including hardware and OS (see [`get_platform()`](#distutils.util.get_platform "distutils.util.get_platform")) `distutils.util.subst_vars(s, local_vars)` Perform shell/Perl-style variable substitution on *s*. Every occurrence of `$` followed by a name is considered a variable, and variable is substituted by the value found in the *local\_vars* dictionary, or in `os.environ` if it’s not in *local\_vars*. *os.environ* is first checked/augmented to guarantee that it contains certain values: see [`check_environ()`](#distutils.util.check_environ "distutils.util.check_environ"). Raise [`ValueError`](../library/exceptions#ValueError "ValueError") for any variables not found in either *local\_vars* or `os.environ`. Note that this is not a fully-fledged string interpolation function. A valid `$variable` can consist only of upper and lower case letters, numbers and an underscore. No { } or ( ) style quoting is available. `distutils.util.split_quoted(s)` Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words. `distutils.util.execute(func, args[, msg=None, verbose=0, dry_run=0])` Perform some action that affects the outside world (for instance, writing to the filesystem). Such actions are special because they are disabled by the *dry\_run* flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the “external action” being performed), and an optional message to print. `distutils.util.strtobool(val)` Convert a string representation of truth to true (1) or false (0). True values are `y`, `yes`, `t`, `true`, `on` and `1`; false values are `n`, `no`, `f`, `false`, `off` and `0`. Raises [`ValueError`](../library/exceptions#ValueError "ValueError") if *val* is anything else. `distutils.util.byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None])` Byte-compile a collection of Python source files to `.pyc` files in a `__pycache__` subdirectory (see [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) and [**PEP 488**](https://www.python.org/dev/peps/pep-0488)). *py\_files* is a list of files to compile; any files that don’t end in `.py` are silently skipped. *optimize* must be one of the following: * `0` - don’t optimize * `1` - normal optimization (like `python -O`) * `2` - extra optimization (like `python -OO`) If *force* is true, all files are recompiled regardless of timestamps. The source filename encoded in each [bytecode](../glossary#term-bytecode) file defaults to the filenames listed in *py\_files*; you can modify these with *prefix* and *basedir*. *prefix* is a string that will be stripped off of each source filename, and *base\_dir* is a directory name that will be prepended (after *prefix* is stripped). You can supply either or both (or neither) of *prefix* and *base\_dir*, as you wish. If *dry\_run* is true, doesn’t actually do anything that would affect the filesystem. Byte-compilation is either done directly in this interpreter process with the standard [`py_compile`](../library/py_compile#module-py_compile "py_compile: Generate byte-code files from Python source files.") module, or indirectly by writing a temporary script and executing it. Normally, you should let [`byte_compile()`](#distutils.util.byte_compile "distutils.util.byte_compile") figure out to use direct compilation or not (see the source for details). The *direct* flag is used by the script generated in indirect mode; unless you know what you’re doing, leave it set to `None`. Changed in version 3.2.3: Create `.pyc` files with an [`import magic tag`](../library/imp#imp.get_tag "imp.get_tag") in their name, in a `__pycache__` subdirectory instead of files without tag in the current directory. Changed in version 3.5: Create `.pyc` files according to [**PEP 488**](https://www.python.org/dev/peps/pep-0488). `distutils.util.rfc822_escape(header)` Return a version of *header* escaped for inclusion in an [**RFC 822**](https://tools.ietf.org/html/rfc822.html) header, by ensuring there are 8 spaces space after each newline. Note that it does no other modification of the string. 9.12. distutils.dist — The Distribution class ---------------------------------------------- This module provides the [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") class, which represents the module distribution being built/installed/distributed. 9.13. distutils.extension — The Extension class ------------------------------------------------ This module provides the `Extension` class, used to describe C/C++ extension modules in setup scripts. 9.14. distutils.debug — Distutils debug mode --------------------------------------------- This module provides the DEBUG flag. 9.15. distutils.errors — Distutils exceptions ---------------------------------------------- Provides exceptions used by the Distutils modules. Note that Distutils modules may raise standard exceptions; in particular, SystemExit is usually raised for errors that are obviously the end-user’s fault (eg. bad command-line arguments). This module is safe to use in `from ... import *` mode; it only exports symbols whose names start with `Distutils` and end with `Error`. 9.16. distutils.fancy\_getopt — Wrapper around the standard getopt module -------------------------------------------------------------------------- This module provides a wrapper around the standard [`getopt`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") module that provides the following additional features: * short and long options are tied together * options have help strings, so [`fancy_getopt()`](#distutils.fancy_getopt.fancy_getopt "distutils.fancy_getopt.fancy_getopt") could potentially create a complete usage summary * options set attributes of a passed-in object * boolean options can have “negative aliases” — eg. if `--quiet` is the “negative alias” of `--verbose`, then `--quiet` on the command line sets *verbose* to false. `distutils.fancy_getopt.fancy_getopt(options, negative_opt, object, args)` Wrapper function. *options* is a list of `(long_option, short_option, help_string)` 3-tuples as described in the constructor for [`FancyGetopt`](#distutils.fancy_getopt.FancyGetopt "distutils.fancy_getopt.FancyGetopt"). *negative\_opt* should be a dictionary mapping option names to option names, both the key and value should be in the *options* list. *object* is an object which will be used to store values (see the [`getopt()`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") method of the [`FancyGetopt`](#distutils.fancy_getopt.FancyGetopt "distutils.fancy_getopt.FancyGetopt") class). *args* is the argument list. Will use `sys.argv[1:]` if you pass `None` as *args*. `distutils.fancy_getopt.wrap_text(text, width)` Wraps *text* to less than *width* wide. `class distutils.fancy_getopt.FancyGetopt([option_table=None])` The option\_table is a list of 3-tuples: `(long_option, short_option, help_string)` If an option takes an argument, its *long\_option* should have `'='` appended; *short\_option* should just be a single character, no `':'` in any case. *short\_option* should be `None` if a *long\_option* doesn’t have a corresponding *short\_option*. All option tuples must have long options. The [`FancyGetopt`](#distutils.fancy_getopt.FancyGetopt "distutils.fancy_getopt.FancyGetopt") class provides the following methods: `FancyGetopt.getopt([args=None, object=None])` Parse command-line options in args. Store as attributes on *object*. If *args* is `None` or not supplied, uses `sys.argv[1:]`. If *object* is `None` or not supplied, creates a new `OptionDummy` instance, stores option values there, and returns a tuple `(args, object)`. If *object* is supplied, it is modified in place and [`getopt()`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") just returns *args*; in both cases, the returned *args* is a modified copy of the passed-in *args* list, which is left untouched. `FancyGetopt.get_option_order()` Returns the list of `(option, value)` tuples processed by the previous run of [`getopt()`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") Raises [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") if [`getopt()`](../library/getopt#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") hasn’t been called yet. `FancyGetopt.generate_help([header=None])` Generate help text (a list of strings, one per suggested line of output) from the option table for this [`FancyGetopt`](#distutils.fancy_getopt.FancyGetopt "distutils.fancy_getopt.FancyGetopt") object. If supplied, prints the supplied *header* at the top of the help. 9.17. distutils.filelist — The FileList class ---------------------------------------------- This module provides the `FileList` class, used for poking about the filesystem and building lists of files. 9.18. distutils.log — Simple [**PEP 282**](https://www.python.org/dev/peps/pep-0282)-style logging --------------------------------------------------------------------------------------------------- 9.19. distutils.spawn — Spawn a sub-process -------------------------------------------- This module provides the `spawn()` function, a front-end to various platform-specific functions for launching another program in a sub-process. Also provides `find_executable()` to search the path for a given executable name. 9.20. distutils.sysconfig — System configuration information ------------------------------------------------------------- The [`distutils.sysconfig`](#module-distutils.sysconfig "distutils.sysconfig: Low-level access to configuration information of the Python interpreter.") module provides access to Python’s low-level configuration information. The specific configuration variables available depend heavily on the platform and configuration. The specific variables depend on the build process for the specific version of Python being run; the variables are those found in the `Makefile` and configuration header that are installed with Python on Unix systems. The configuration header is called `pyconfig.h` for Python versions starting with 2.2, and `config.h` for earlier versions of Python. Some additional functions are provided which perform some useful manipulations for other parts of the [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") package. `distutils.sysconfig.PREFIX` The result of `os.path.normpath(sys.prefix)`. `distutils.sysconfig.EXEC_PREFIX` The result of `os.path.normpath(sys.exec_prefix)`. `distutils.sysconfig.get_config_var(name)` Return the value of a single variable. This is equivalent to `get_config_vars().get(name)`. `distutils.sysconfig.get_config_vars(...)` Return a set of variable definitions. If there are no arguments, this returns a dictionary mapping names of configuration variables to values. If arguments are provided, they should be strings, and the return value will be a sequence giving the associated values. If a given name does not have a corresponding value, `None` will be included for that variable. `distutils.sysconfig.get_config_h_filename()` Return the full path name of the configuration header. For Unix, this will be the header generated by the **configure** script; for other platforms the header will have been supplied directly by the Python source distribution. The file is a platform-specific text file. `distutils.sysconfig.get_makefile_filename()` Return the full path name of the `Makefile` used to build Python. For Unix, this will be a file generated by the **configure** script; the meaning for other platforms will vary. The file is a platform-specific text file, if it exists. This function is only useful on POSIX platforms. `distutils.sysconfig.get_python_inc([plat_specific[, prefix]])` Return the directory for either the general or platform-dependent C include files. If *plat\_specific* is true, the platform-dependent include directory is returned; if false or omitted, the platform-independent directory is returned. If *prefix* is given, it is used as either the prefix instead of [`PREFIX`](#distutils.sysconfig.PREFIX "distutils.sysconfig.PREFIX"), or as the exec-prefix instead of [`EXEC_PREFIX`](#distutils.sysconfig.EXEC_PREFIX "distutils.sysconfig.EXEC_PREFIX") if *plat\_specific* is true. `distutils.sysconfig.get_python_lib([plat_specific[, standard_lib[, prefix]]])` Return the directory for either the general or platform-dependent library installation. If *plat\_specific* is true, the platform-dependent include directory is returned; if false or omitted, the platform-independent directory is returned. If *prefix* is given, it is used as either the prefix instead of [`PREFIX`](#distutils.sysconfig.PREFIX "distutils.sysconfig.PREFIX"), or as the exec-prefix instead of [`EXEC_PREFIX`](#distutils.sysconfig.EXEC_PREFIX "distutils.sysconfig.EXEC_PREFIX") if *plat\_specific* is true. If *standard\_lib* is true, the directory for the standard library is returned rather than the directory for the installation of third-party extensions. The following function is only intended for use within the [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") package. `distutils.sysconfig.customize_compiler(compiler)` Do any platform-specific customization of a [`distutils.ccompiler.CCompiler`](#distutils.ccompiler.CCompiler "distutils.ccompiler.CCompiler") instance. This function is only needed on Unix at this time, but should be called consistently to support forward-compatibility. It inserts the information that varies across Unix flavors and is stored in Python’s `Makefile`. This information includes the selected compiler, compiler and linker options, and the extension used by the linker for shared objects. This function is even more special-purpose, and should only be used from Python’s own build procedures. `distutils.sysconfig.set_python_build()` Inform the [`distutils.sysconfig`](#module-distutils.sysconfig "distutils.sysconfig: Low-level access to configuration information of the Python interpreter.") module that it is being used as part of the build process for Python. This changes a lot of relative locations for files, allowing them to be located in the build area rather than in an installed Python. 9.21. distutils.text\_file — The TextFile class ------------------------------------------------ This module provides the [`TextFile`](#distutils.text_file.TextFile "distutils.text_file.TextFile") class, which gives an interface to text files that (optionally) takes care of stripping comments, ignoring blank lines, and joining lines with backslashes. `class distutils.text_file.TextFile([filename=None, file=None, **options])` This class provides a file-like object that takes care of all the things you commonly want to do when processing a text file that has some line-by-line syntax: strip comments (as long as `#` is your comment character), skip blank lines, join adjacent lines by escaping the newline (ie. backslash at end of line), strip leading and/or trailing whitespace. All of these are optional and independently controllable. The class provides a [`warn()`](#distutils.text_file.TextFile.warn "distutils.text_file.TextFile.warn") method so you can generate warning messages that report physical line number, even if the logical line in question spans multiple physical lines. Also provides [`unreadline()`](#distutils.text_file.TextFile.unreadline "distutils.text_file.TextFile.unreadline") for implementing line-at-a-time lookahead. [`TextFile`](#distutils.text_file.TextFile "distutils.text_file.TextFile") instances are create with either *filename*, *file*, or both. [`RuntimeError`](../library/exceptions#RuntimeError "RuntimeError") is raised if both are `None`. *filename* should be a string, and *file* a file object (or something that provides [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") and [`close()`](#distutils.text_file.TextFile.close "distutils.text_file.TextFile.close") methods). It is recommended that you supply at least *filename*, so that [`TextFile`](#distutils.text_file.TextFile "distutils.text_file.TextFile") can include it in warning messages. If *file* is not supplied, [`TextFile`](#distutils.text_file.TextFile "distutils.text_file.TextFile") creates its own using the [`open()`](../library/functions#open "open") built-in function. The options are all boolean, and affect the values returned by [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") | option name | description | default | | --- | --- | --- | | *strip\_comments* | strip from `'#'` to end-of-line, as well as any whitespace leading up to the `'#'`—unless it is escaped by a backslash | true | | *lstrip\_ws* | strip leading whitespace from each line before returning it | false | | *rstrip\_ws* | strip trailing whitespace (including line terminator!) from each line before returning it. | true | | *skip\_blanks* | skip lines that are empty \*after\* stripping comments and whitespace. (If both lstrip\_ws and rstrip\_ws are false, then some lines may consist of solely whitespace: these will \*not\* be skipped, even if *skip\_blanks* is true.) | true | | *join\_lines* | if a backslash is the last non-newline character on a line after stripping comments and whitespace, join the following line to it to form one logical line; if N consecutive lines end with a backslash, then N+1 physical lines will be joined to form one logical line. | false | | *collapse\_join* | strip leading whitespace from lines that are joined to their predecessor; only matters if `(join_lines and not lstrip_ws)` | false | Note that since *rstrip\_ws* can strip the trailing newline, the semantics of [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") must differ from those of the built-in file object’s [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") method! In particular, [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") returns `None` for end-of-file: an empty string might just be a blank line (or an all-whitespace line), if *rstrip\_ws* is true but *skip\_blanks* is not. `open(filename)` Open a new file *filename*. This overrides any *file* or *filename* constructor arguments. `close()` Close the current file and forget everything we know about it (including the filename and the current line number). `warn(msg[, line=None])` Print (to stderr) a warning message tied to the current logical line in the current file. If the current logical line in the file spans multiple physical lines, the warning refers to the whole range, such as `"lines 3-5"`. If *line* is supplied, it overrides the current line number; it may be a list or tuple to indicate a range of physical lines, or an integer for a single physical line. `readline()` Read and return a single logical line from the current file (or from an internal buffer if lines have previously been “unread” with [`unreadline()`](#distutils.text_file.TextFile.unreadline "distutils.text_file.TextFile.unreadline")). If the *join\_lines* option is true, this may involve reading multiple physical lines concatenated into a single string. Updates the current line number, so calling [`warn()`](#distutils.text_file.TextFile.warn "distutils.text_file.TextFile.warn") after [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") emits a warning about the physical line(s) just read. Returns `None` on end-of-file, since the empty string can occur if *rstrip\_ws* is true but *strip\_blanks* is not. `readlines()` Read and return the list of all logical lines remaining in the current file. This updates the current line number to the last line of the file. `unreadline(line)` Push *line* (a string) onto an internal buffer that will be checked by future [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)") calls. Handy for implementing a parser with line-at-a-time lookahead. Note that lines that are “unread” with [`unreadline()`](#distutils.text_file.TextFile.unreadline "distutils.text_file.TextFile.unreadline") are not subsequently re-cleansed (whitespace stripped, or whatever) when read with [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)"). If multiple calls are made to [`unreadline()`](#distutils.text_file.TextFile.unreadline "distutils.text_file.TextFile.unreadline") before a call to [`readline()`](../library/readline#module-readline "readline: GNU readline support for Python. (Unix)"), the lines will be returned most in most recent first order. 9.22. distutils.version — Version number classes ------------------------------------------------- 9.23. distutils.cmd — Abstract base class for Distutils commands ----------------------------------------------------------------- This module supplies the abstract base class [`Command`](#distutils.cmd.Command "distutils.cmd.Command"). `class distutils.cmd.Command(dist)` Abstract base class for defining command classes, the “worker bees” of the Distutils. A useful analogy for command classes is to think of them as subroutines with local variables called *options*. The options are declared in [`initialize_options()`](#distutils.cmd.Command.initialize_options "distutils.cmd.Command.initialize_options") and defined (given their final values) in [`finalize_options()`](#distutils.cmd.Command.finalize_options "distutils.cmd.Command.finalize_options"), both of which must be defined by every command class. The distinction between the two is necessary because option values might come from the outside world (command line, config file, …), and any options dependent on other options must be computed after these outside influences have been processed — hence [`finalize_options()`](#distutils.cmd.Command.finalize_options "distutils.cmd.Command.finalize_options"). The body of the subroutine, where it does all its work based on the values of its options, is the [`run()`](#distutils.cmd.Command.run "distutils.cmd.Command.run") method, which must also be implemented by every command class. The class constructor takes a single argument *dist*, a [`Distribution`](#distutils.core.Distribution "distutils.core.Distribution") instance. 9.24. Creating a new Distutils command --------------------------------------- This section outlines the steps to create a new Distutils command. A new command lives in a module in the [`distutils.command`](#module-distutils.command "distutils.command: Contains one module for each standard Distutils command.") package. There is a sample template in that directory called `command_template`. Copy this file to a new module with the same name as the new command you’re implementing. This module should implement a class with the same name as the module (and the command). So, for instance, to create the command `peel_banana` (so that users can run `setup.py peel_banana`), you’d copy `command_template` to `distutils/command/peel_banana.py`, then edit it so that it’s implementing the class `peel_banana`, a subclass of [`distutils.cmd.Command`](#distutils.cmd.Command "distutils.cmd.Command"). Subclasses of [`Command`](#distutils.cmd.Command "distutils.cmd.Command") must define the following methods. `Command.initialize_options()` Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, [`initialize_options()`](#distutils.cmd.Command.initialize_options "distutils.cmd.Command.initialize_options") implementations are just a bunch of `self.foo = None` assignments. `Command.finalize_options()` Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if *foo* depends on *bar*, then it is safe to set *foo* from *bar* as long as *foo* still has the same value it was assigned in [`initialize_options()`](#distutils.cmd.Command.initialize_options "distutils.cmd.Command.initialize_options"). `Command.run()` A command’s raison d’etre: carry out the action it exists to perform, controlled by the options initialized in [`initialize_options()`](#distutils.cmd.Command.initialize_options "distutils.cmd.Command.initialize_options"), customized by other commands, the setup script, the command-line, and config files, and finalized in [`finalize_options()`](#distutils.cmd.Command.finalize_options "distutils.cmd.Command.finalize_options"). All terminal output and filesystem interaction should be done by [`run()`](#distutils.cmd.Command.run "distutils.cmd.Command.run"). `Command.sub_commands` *sub\_commands* formalizes the notion of a “family” of commands, e.g. `install` as the parent with sub-commands `install_lib`, `install_headers`, etc. The parent of a family of commands defines *sub\_commands* as a class attribute; it’s a list of 2-tuples `(command_name, predicate)`, with *command\_name* a string and *predicate* a function, a string or `None`. *predicate* is a method of the parent command that determines whether the corresponding command is applicable in the current situation. (E.g. `install_headers` is only applicable if we have any C header files to install.) If *predicate* is `None`, that command is always applicable. *sub\_commands* is usually defined at the *end* of a class, because predicates can be methods of the class, so they must already have been defined. The canonical example is the **install** command. 9.25. distutils.command — Individual Distutils commands -------------------------------------------------------- 9.26. distutils.command.bdist — Build a binary installer --------------------------------------------------------- 9.27. distutils.command.bdist\_packager — Abstract base class for packagers ---------------------------------------------------------------------------- 9.28. distutils.command.bdist\_dumb — Build a “dumb” installer --------------------------------------------------------------- 9.29. distutils.command.bdist\_msi — Build a Microsoft Installer binary package -------------------------------------------------------------------------------- `class distutils.command.bdist_msi.bdist_msi` Deprecated since version 3.9: Use bdist\_wheel (wheel packages) instead. Builds a [Windows Installer](https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx) (.msi) binary package. In most cases, the `bdist_msi` installer is a better choice than the `bdist_wininst` installer, because it provides better support for Win64 platforms, allows administrators to perform non-interactive installations, and allows installation through group policies. 9.30. distutils.command.bdist\_rpm — Build a binary distribution as a Redhat RPM and SRPM ------------------------------------------------------------------------------------------ 9.31. distutils.command.bdist\_wininst — Build a Windows installer ------------------------------------------------------------------- Deprecated since version 3.8: Use bdist\_wheel (wheel packages) instead. 9.32. distutils.command.sdist — Build a source distribution ------------------------------------------------------------ 9.33. distutils.command.build — Build all files of a package ------------------------------------------------------------- 9.34. distutils.command.build\_clib — Build any C libraries in a package ------------------------------------------------------------------------- 9.35. distutils.command.build\_ext — Build any extensions in a package ----------------------------------------------------------------------- 9.36. distutils.command.build\_py — Build the .py/.pyc files of a package -------------------------------------------------------------------------- `class distutils.command.build_py.build_py` `class distutils.command.build_py.build_py_2to3` Alternative implementation of build\_py which also runs the 2to3 conversion library on each .py file that is going to be installed. To use this in a setup.py file for a distribution that is designed to run with both Python 2.x and 3.x, add: ``` try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: from distutils.command.build_py import build_py ``` to your setup.py, and later: ``` cmdclass = {'build_py': build_py} ``` to the invocation of setup(). 9.37. distutils.command.build\_scripts — Build the scripts of a package ------------------------------------------------------------------------ 9.38. distutils.command.clean — Clean a package build area ----------------------------------------------------------- This command removes the temporary files created by **build** and its subcommands, like intermediary compiled object files. With the `--all` option, the complete build directory will be removed. Extension modules built [in place](configfile#distutils-build-ext-inplace) will not be cleaned, as they are not in the build directory. 9.39. distutils.command.config — Perform package configuration --------------------------------------------------------------- 9.40. distutils.command.install — Install a package ---------------------------------------------------- 9.41. distutils.command.install\_data — Install data files from a package -------------------------------------------------------------------------- 9.42. distutils.command.install\_headers — Install C/C++ header files from a package ------------------------------------------------------------------------------------- 9.43. distutils.command.install\_lib — Install library files from a package ---------------------------------------------------------------------------- 9.44. distutils.command.install\_scripts — Install script files from a package ------------------------------------------------------------------------------- 9.45. distutils.command.register — Register a module with the Python Package Index ----------------------------------------------------------------------------------- The `register` command registers the package with the Python Package Index. This is described in more detail in [**PEP 301**](https://www.python.org/dev/peps/pep-0301). 9.46. distutils.command.check — Check the meta-data of a package ----------------------------------------------------------------- The `check` command performs some tests on the meta-data of a package. For example, it verifies that all required meta-data are provided as the arguments passed to the `setup()` function.
programming_docs
python Extending Distutils Extending Distutils ==================== Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. Distutils can be extended in various ways. Most extensions take the form of new commands or replacements for existing commands. New commands may be written to support new types of platform-specific packaging, for example, while replacements for existing commands may be made to modify details of how the command operates on a package. Most extensions of the distutils are made within `setup.py` scripts that want to modify existing commands; many simply add a few file extensions that should be copied into packages in addition to `.py` files as a convenience. Most distutils command implementations are subclasses of the [`distutils.cmd.Command`](apiref#distutils.cmd.Command "distutils.cmd.Command") class. New commands may directly inherit from `Command`, while replacements often derive from `Command` indirectly, directly subclassing the command they are replacing. Commands are required to derive from `Command`. 7.1. Integrating new commands ------------------------------ There are different ways to integrate new command implementations into distutils. The most difficult is to lobby for the inclusion of the new features in distutils itself, and wait for (and require) a version of Python that provides that support. This is really hard for many reasons. The most common, and possibly the most reasonable for most needs, is to include the new implementations with your `setup.py` script, and cause the [`distutils.core.setup()`](apiref#distutils.core.setup "distutils.core.setup") function use them: ``` from distutils.command.build_py import build_py as _build_py from distutils.core import setup class build_py(_build_py): """Specialized Python source builder.""" # implement whatever needs to be different... setup(cmdclass={'build_py': build_py}, ...) ``` This approach is most valuable if the new implementations must be used to use a particular package, as everyone interested in the package will need to have the new command implementation. Beginning with Python 2.4, a third option is available, intended to allow new commands to be added which can support existing `setup.py` scripts without requiring modifications to the Python installation. This is expected to allow third-party extensions to provide support for additional packaging systems, but the commands can be used for anything distutils commands can be used for. A new configuration option, `command_packages` (command-line option `--command-packages`), can be used to specify additional packages to be searched for modules implementing commands. Like all distutils options, this can be specified on the command line or in a configuration file. This option can only be set in the `[global]` section of a configuration file, or before any commands on the command line. If set in a configuration file, it can be overridden from the command line; setting it to an empty string on the command line causes the default to be used. This should never be set in a configuration file provided with a package. This new option can be used to add any number of packages to the list of packages searched for command implementations; multiple package names should be separated by commas. When not specified, the search is only performed in the [`distutils.command`](apiref#module-distutils.command "distutils.command: Contains one module for each standard Distutils command.") package. When `setup.py` is run with the option `--command-packages distcmds,buildcmds`, however, the packages [`distutils.command`](apiref#module-distutils.command "distutils.command: Contains one module for each standard Distutils command."), `distcmds`, and `buildcmds` will be searched in that order. New commands are expected to be implemented in modules of the same name as the command by classes sharing the same name. Given the example command line option above, the command **bdist\_openpkg** could be implemented by the class `distcmds.bdist_openpkg.bdist_openpkg` or `buildcmds.bdist_openpkg.bdist_openpkg`. 7.2. Adding new distribution types ----------------------------------- Commands that create distributions (files in the `dist/` directory) need to add `(command, filename)` pairs to `self.distribution.dist_files` so that **upload** can upload it to PyPI. The *filename* in the pair contains no path information, only the name of the file itself. In dry-run mode, pairs should still be added to represent what would have been created. python Creating a Source Distribution Creating a Source Distribution =============================== Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. As shown in section [A Simple Example](introduction#distutils-simple-example), you use the **sdist** command to create a source distribution. In the simplest case, ``` python setup.py sdist ``` (assuming you haven’t specified any **sdist** options in the setup script or config file), **sdist** creates the archive of the default format for the current platform. The default format is a gzip’ed tar file (`.tar.gz`) on Unix, and ZIP file on Windows. You can specify as many formats as you like using the `--formats` option, for example: ``` python setup.py sdist --formats=gztar,zip ``` to create a gzipped tarball and a zip file. The available formats are: | Format | Description | Notes | | --- | --- | --- | | `zip` | zip file (`.zip`) | (1),(3) | | `gztar` | gzip’ed tar file (`.tar.gz`) | (2) | | `bztar` | bzip2’ed tar file (`.tar.bz2`) | (5) | | `xztar` | xz’ed tar file (`.tar.xz`) | (5) | | `ztar` | compressed tar file (`.tar.Z`) | (4),(5) | | `tar` | tar file (`.tar`) | (5) | Changed in version 3.5: Added support for the `xztar` format. Notes: 1. default on Windows 2. default on Unix 3. requires either external **zip** utility or [`zipfile`](../library/zipfile#module-zipfile "zipfile: Read and write ZIP-format archive files.") module (part of the standard Python library since Python 1.6) 4. requires the **compress** program. Notice that this format is now pending for deprecation and will be removed in the future versions of Python. 5. deprecated by [PEP 527](https://www.python.org/dev/peps/pep-0527/); [PyPI](https://pypi.org) only accepts `.zip` and `.tar.gz` files. When using any `tar` format (`gztar`, `bztar`, `xztar`, `ztar` or `tar`), under Unix you can specify the `owner` and `group` names that will be set for each member of the archive. For example, if you want all files of the archive to be owned by root: ``` python setup.py sdist --owner=root --group=root ``` 4.1. Specifying the files to distribute ---------------------------------------- If you don’t supply an explicit list of files (or instructions on how to generate one), the **sdist** command puts a minimal default set into the source distribution: * all Python source files implied by the `py_modules` and `packages` options * all C source files mentioned in the `ext_modules` or `libraries` options * scripts identified by the `scripts` option See [Installing Scripts](setupscript#distutils-installing-scripts). * anything that looks like a test script: `test/test*.py` (currently, the Distutils don’t do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions) * Any of the standard README files (`README`, `README.txt`, or `README.rst`), `setup.py` (or whatever you called your setup script), and `setup.cfg`. * all files that matches the `package_data` metadata. See [Installing Package Data](setupscript#distutils-installing-package-data). * all files that matches the `data_files` metadata. See [Installing Additional Files](setupscript#distutils-additional-files). Sometimes this is enough, but usually you will want to specify additional files to distribute. The typical way to do this is to write a *manifest template*, called `MANIFEST.in` by default. The manifest template is just a list of instructions for how to generate your manifest file, `MANIFEST`, which is the exact list of files to include in your source distribution. The **sdist** command processes this template and generates a manifest based on its instructions and what it finds in the filesystem. If you prefer to roll your own manifest file, the format is simple: one filename per line, regular files (or symlinks to them) only. If you do supply your own `MANIFEST`, you must specify everything: the default set of files described above does not apply in this case. Changed in version 3.1: An existing generated `MANIFEST` will be regenerated without **sdist** comparing its modification time to the one of `MANIFEST.in` or `setup.py`. Changed in version 3.1.3: `MANIFEST` files start with a comment indicating they are generated. Files without this comment are not overwritten or removed. Changed in version 3.2.2: **sdist** will read a `MANIFEST` file if no `MANIFEST.in` exists, like it used to do. Changed in version 3.7: `README.rst` is now included in the list of distutils standard READMEs. The manifest template has one command per line, where each command specifies a set of files to include or exclude from the source distribution. For an example, again we turn to the Distutils’ own manifest template: ``` include *.txt recursive-include examples *.txt *.py prune examples/sample?/build ``` The meanings should be fairly clear: include all files in the distribution root matching `*.txt`, all files anywhere under the `examples` directory matching `*.txt` or `*.py`, and exclude all directories matching `examples/sample?/build`. All of this is done *after* the standard include set, so you can exclude files from the standard set with explicit instructions in the manifest template. (Or, you can use the `--no-defaults` option to disable the standard set entirely.) There are several other commands available in the manifest template mini-language; see section [Creating a source distribution: the sdist command](commandref#sdist-cmd). The order of commands in the manifest template matters: initially, we have the list of default files as described above, and each command in the template adds to or removes from that list of files. Once we have fully processed the manifest template, we remove files that should not be included in the source distribution: * all files in the Distutils “build” tree (default `build/`) * all files in directories named `RCS`, `CVS`, `.svn`, `.hg`, `.git`, `.bzr` or `_darcs` Now we have our complete list of files, which is written to the manifest for future reference, and then used to build the source distribution archive(s). You can disable the default set of included files with the `--no-defaults` option, and you can disable the standard exclude set with `--no-prune`. Following the Distutils’ own manifest template, let’s trace how the **sdist** command builds the list of files to include in the Distutils source distribution: 1. include all Python source files in the `distutils` and `distutils/command` subdirectories (because packages corresponding to those two directories were mentioned in the `packages` option in the setup script—see section [Writing the Setup Script](setupscript#setup-script)) 2. include `README.txt`, `setup.py`, and `setup.cfg` (standard files) 3. include `test/test*.py` (standard files) 4. include `*.txt` in the distribution root (this will find `README.txt` a second time, but such redundancies are weeded out later) 5. include anything matching `*.txt` or `*.py` in the sub-tree under `examples`, 6. exclude all files in the sub-trees starting at directories matching `examples/sample?/build`—this may exclude files included by the previous two steps, so it’s important that the `prune` command in the manifest template comes after the `recursive-include` command 7. exclude the entire `build` tree, and any `RCS`, `CVS`, `.svn`, `.hg`, `.git`, `.bzr` and `_darcs` directories Just like in the setup script, file and directory names in the manifest template should always be slash-separated; the Distutils will take care of converting them to the standard representation on your platform. That way, the manifest template is portable across operating systems. 4.2. Manifest-related options ------------------------------ The normal course of operations for the **sdist** command is as follows: * if the manifest file (`MANIFEST` by default) exists and the first line does not have a comment indicating it is generated from `MANIFEST.in`, then it is used as is, unaltered * if the manifest file doesn’t exist or has been previously automatically generated, read `MANIFEST.in` and create the manifest * if neither `MANIFEST` nor `MANIFEST.in` exist, create a manifest with just the default file set * use the list of files now in `MANIFEST` (either just generated or read in) to create the source distribution archive(s) There are a couple of options that modify this behaviour. First, use the `--no-defaults` and `--no-prune` to disable the standard “include” and “exclude” sets. Second, you might just want to (re)generate the manifest, but not create a source distribution: ``` python setup.py sdist --manifest-only ``` `-o` is a shortcut for `--manifest-only`. python Writing the Setup Configuration File Writing the Setup Configuration File ===================================== Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. Often, it’s not possible to write down everything needed to build a distribution *a priori*: you may need to get some information from the user, or from the user’s system, in order to proceed. As long as that information is fairly simple—a list of directories to search for C header files or libraries, for example—then providing a configuration file, `setup.cfg`, for users to edit is a cheap and easy way to solicit it. Configuration files also let you provide default values for any command option, which the installer can then override either on the command-line or by editing the config file. The setup configuration file is a useful middle-ground between the setup script—which, ideally, would be opaque to installers [1](#id2)—and the command-line to the setup script, which is outside of your control and entirely up to the installer. In fact, `setup.cfg` (and any other Distutils configuration files present on the target system) are processed after the contents of the setup script, but before the command-line. This has several useful consequences: * installers can override some of what you put in `setup.py` by editing `setup.cfg` * you can provide non-standard defaults for options that are not easily set in `setup.py` * installers can override anything in `setup.cfg` using the command-line options to `setup.py` The basic syntax of the configuration file is simple: ``` [command] option=value ... ``` where *command* is one of the Distutils commands (e.g. **build\_py**, **install**), and *option* is one of the options that command supports. Any number of options can be supplied for each command, and any number of command sections can be included in the file. Blank lines are ignored, as are comments, which run from a `'#'` character until the end of the line. Long option values can be split across multiple lines simply by indenting the continuation lines. You can find out the list of options supported by a particular command with the universal `--help` option, e.g. ``` $ python setup.py --help build_ext [...] Options for 'build_ext' command: --build-lib (-b) directory for compiled extension modules --build-temp (-t) directory for temporary files (build by-products) --inplace (-i) ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine --swig-opts list of SWIG command line options [...] ``` Note that an option spelled `--foo-bar` on the command-line is spelled `foo_bar` in configuration files. For example, say you want your extensions to be built “in-place”—that is, you have an extension `pkg.ext`, and you want the compiled extension file (`ext.so` on Unix, say) to be put in the same source directory as your pure Python modules `pkg.mod1` and `pkg.mod2`. You can always use the `--inplace` option on the command-line to ensure this: ``` python setup.py build_ext --inplace ``` But this requires that you always specify the **build\_ext** command explicitly, and remember to provide `--inplace`. An easier way is to “set and forget” this option, by encoding it in `setup.cfg`, the configuration file for this distribution: ``` [build_ext] inplace=1 ``` This will affect all builds of this module distribution, whether or not you explicitly specify **build\_ext**. If you include `setup.cfg` in your source distribution, it will also affect end-user builds—which is probably a bad idea for this option, since always building extensions in-place would break installation of the module distribution. In certain peculiar cases, though, modules are built right in their installation directory, so this is conceivably a useful ability. (Distributing extensions that expect to be built in their installation directory is almost always a bad idea, though.) Another example: certain commands take a lot of options that don’t change from run to run; for example, **bdist\_rpm** needs to know everything required to generate a “spec” file for creating an RPM distribution. Some of this information comes from the setup script, and some is automatically generated by the Distutils (such as the list of files installed). But some of it has to be supplied as options to **bdist\_rpm**, which would be very tedious to do on the command-line for every run. Hence, here is a snippet from the Distutils’ own `setup.cfg`: ``` [bdist_rpm] release = 1 packager = Greg Ward <[email protected]> doc_files = CHANGES.txt README.txt USAGE.txt doc/ examples/ ``` Note that the `doc_files` option is simply a whitespace-separated string split across multiple lines for readability. See also [Syntax of config files](../install/index#inst-config-syntax) in “Installing Python Modules” More information on the configuration files is available in the manual for system administrators. #### Footnotes `1` This ideal probably won’t be achieved until auto-configuration is fully supported by the Distutils. python Distutils Examples Distutils Examples =================== Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. This chapter provides a number of basic examples to help get started with distutils. Additional information about using distutils can be found in the Distutils Cookbook. See also [Distutils Cookbook](https://wiki.python.org/moin/Distutils/Cookbook) Collection of recipes showing how to achieve more control over distutils. 6.1. Pure Python distribution (by module) ------------------------------------------ If you’re just distributing a couple of modules, especially if they don’t live in a particular package, you can specify them individually using the `py_modules` option in the setup script. In the simplest case, you’ll have two files to worry about: a setup script and the single module you’re distributing, `foo.py` in this example: ``` <root>/ setup.py foo.py ``` (In all diagrams in this section, *<root>* will refer to the distribution root directory.) A minimal setup script to describe this situation would be: ``` from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` Note that the name of the distribution is specified independently with the `name` option, and there’s no rule that says it has to be the same as the name of the sole module in the distribution (although that’s probably a good convention to follow). However, the distribution name is used to generate filenames, so you should stick to letters, digits, underscores, and hyphens. Since `py_modules` is a list, you can of course specify multiple modules, eg. if you’re distributing modules `foo` and `bar`, your setup might look like this: ``` <root>/ setup.py foo.py bar.py ``` and the setup script might be ``` from distutils.core import setup setup(name='foobar', version='1.0', py_modules=['foo', 'bar'], ) ``` You can put module source files into another directory, but if you have enough modules to do that, it’s probably easier to specify modules by package rather than listing them individually. 6.2. Pure Python distribution (by package) ------------------------------------------- If you have more than a couple of modules to distribute, especially if they are in multiple packages, it’s probably easier to specify whole packages rather than individual modules. This works even if your modules are not in a package; you can just tell the Distutils to process modules from the root package, and that works the same as any other package (except that you don’t have to have an `__init__.py` file). The setup script from the last example could also be written as ``` from distutils.core import setup setup(name='foobar', version='1.0', packages=[''], ) ``` (The empty string stands for the root package.) If those two files are moved into a subdirectory, but remain in the root package, e.g.: ``` <root>/ setup.py src/ foo.py bar.py ``` then you would still specify the root package, but you have to tell the Distutils where source files in the root package live: ``` from distutils.core import setup setup(name='foobar', version='1.0', package_dir={'': 'src'}, packages=[''], ) ``` More typically, though, you will want to distribute multiple modules in the same package (or in sub-packages). For example, if the `foo` and `bar` modules belong in package `foobar`, one way to layout your source tree is ``` <root>/ setup.py foobar/ __init__.py foo.py bar.py ``` This is in fact the default layout expected by the Distutils, and the one that requires the least work to describe in your setup script: ``` from distutils.core import setup setup(name='foobar', version='1.0', packages=['foobar'], ) ``` If you want to put modules in directories not named for their package, then you need to use the `package_dir` option again. For example, if the `src` directory holds modules in the `foobar` package: ``` <root>/ setup.py src/ __init__.py foo.py bar.py ``` an appropriate setup script would be ``` from distutils.core import setup setup(name='foobar', version='1.0', package_dir={'foobar': 'src'}, packages=['foobar'], ) ``` Or, you might put modules from your main package right in the distribution root: ``` <root>/ setup.py __init__.py foo.py bar.py ``` in which case your setup script would be ``` from distutils.core import setup setup(name='foobar', version='1.0', package_dir={'foobar': ''}, packages=['foobar'], ) ``` (The empty string also stands for the current directory.) If you have sub-packages, they must be explicitly listed in `packages`, but any entries in `package_dir` automatically extend to sub-packages. (In other words, the Distutils does *not* scan your source tree, trying to figure out which directories correspond to Python packages by looking for `__init__.py` files.) Thus, if the default layout grows a sub-package: ``` <root>/ setup.py foobar/ __init__.py foo.py bar.py subfoo/ __init__.py blah.py ``` then the corresponding setup script would be ``` from distutils.core import setup setup(name='foobar', version='1.0', packages=['foobar', 'foobar.subfoo'], ) ``` 6.3. Single extension module ----------------------------- Extension modules are specified using the `ext_modules` option. `package_dir` has no effect on where extension source files are found; it only affects the source for pure Python modules. The simplest case, a single extension module in a single C source file, is: ``` <root>/ setup.py foo.c ``` If the `foo` extension belongs in the root package, the setup script for this could be ``` from distutils.core import setup from distutils.extension import Extension setup(name='foobar', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` If the extension actually belongs in a package, say `foopkg`, then With exactly the same source tree layout, this extension can be put in the `foopkg` package simply by changing the name of the extension: ``` from distutils.core import setup from distutils.extension import Extension setup(name='foobar', version='1.0', ext_modules=[Extension('foopkg.foo', ['foo.c'])], ) ``` 6.4. Checking a package ------------------------ The `check` command allows you to verify if your package meta-data meet the minimum requirements to build a distribution. To run it, just call it using your `setup.py` script. If something is missing, `check` will display a warning. Let’s take an example with a simple script: ``` from distutils.core import setup setup(name='foobar') ``` Running the `check` command will display some warnings: ``` $ python setup.py check running check warning: check: missing required meta-data: version, url warning: check: missing meta-data: either (author and author_email) or (maintainer and maintainer_email) should be supplied ``` If you use the reStructuredText syntax in the `long_description` field and [docutils](http://docutils.sourceforge.net) is installed you can check if the syntax is fine with the `check` command, using the `restructuredtext` option. For example, if the `setup.py` script is changed like this: ``` from distutils.core import setup desc = """\ My description ============== This is the description of the ``foobar`` package. """ setup(name='foobar', version='1', author='tarek', author_email='[email protected]', url='http://example.com', long_description=desc) ``` Where the long description is broken, `check` will be able to detect it by using the `docutils` parser: ``` $ python setup.py check --restructuredtext running check warning: check: Title underline too short. (line 2) warning: check: Could not finish the parsing. ``` 6.5. Reading the metadata -------------------------- The [`distutils.core.setup()`](apiref#distutils.core.setup "distutils.core.setup") function provides a command-line interface that allows you to query the metadata fields of a project through the `setup.py` script of a given project: ``` $ python setup.py --name distribute ``` This call reads the `name` metadata by running the [`distutils.core.setup()`](apiref#distutils.core.setup "distutils.core.setup") function. Although, when a source or binary distribution is created with Distutils, the metadata fields are written in a static file called `PKG-INFO`. When a Distutils-based project is installed in Python, the `PKG-INFO` file is copied alongside the modules and packages of the distribution under `NAME-VERSION-pyX.X.egg-info`, where `NAME` is the name of the project, `VERSION` its version as defined in the Metadata, and `pyX.X` the major and minor version of Python like `2.7` or `3.2`. You can read back this static file, by using the `distutils.dist.DistributionMetadata` class and its `read_pkg_file()` method: ``` >>> from distutils.dist import DistributionMetadata >>> metadata = DistributionMetadata() >>> metadata.read_pkg_file(open('distribute-0.6.8-py2.7.egg-info')) >>> metadata.name 'distribute' >>> metadata.version '0.6.8' >>> metadata.description 'Easily download, build, install, upgrade, and uninstall Python packages' ``` Notice that the class can also be instantiated with a metadata file path to loads its values: ``` >>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info' >>> DistributionMetadata(pkg_info_path).name 'distribute' ```
programming_docs
python Creating Built Distributions Creating Built Distributions ============================= Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. A “built distribution” is what you’re probably used to thinking of either as a “binary package” or an “installer” (depending on your background). It’s not necessarily binary, though, because it might contain only Python source code and/or byte-code; and we don’t call it a package, because that word is already spoken for in Python. (And “installer” is a term specific to the world of mainstream desktop systems.) A built distribution is how you make life as easy as possible for installers of your module distribution: for users of RPM-based Linux systems, it’s a binary RPM; for Windows users, it’s an executable installer; for Debian-based Linux users, it’s a Debian package; and so forth. Obviously, no one person will be able to create built distributions for every platform under the sun, so the Distutils are designed to enable module developers to concentrate on their specialty—writing code and creating source distributions—while an intermediary species called *packagers* springs up to turn source distributions into built distributions for as many platforms as there are packagers. Of course, the module developer could be their own packager; or the packager could be a volunteer “out there” somewhere who has access to a platform which the original developer does not; or it could be software periodically grabbing new source distributions and turning them into built distributions for as many platforms as the software has access to. Regardless of who they are, a packager uses the setup script and the **bdist** command family to generate built distributions. As a simple example, if I run the following command in the Distutils source tree: ``` python setup.py bdist ``` then the Distutils builds my module distribution (the Distutils itself in this case), does a “fake” installation (also in the `build` directory), and creates the default type of built distribution for my platform. The default format for built distributions is a “dumb” tar file on Unix, and a simple executable installer on Windows. (That tar file is considered “dumb” because it has to be unpacked in a specific location to work.) Thus, the above command on a Unix system creates `Distutils-1.0.*plat*.tar.gz`; unpacking this tarball from the right place installs the Distutils just as though you had downloaded the source distribution and run `python setup.py install`. (The “right place” is either the root of the filesystem or Python’s `*prefix*` directory, depending on the options given to the **bdist\_dumb** command; the default is to make dumb distributions relative to `*prefix*`.) Obviously, for pure Python distributions, this isn’t any simpler than just running `python setup.py install`—but for non-pure distributions, which include extensions that would need to be compiled, it can mean the difference between someone being able to use your extensions or not. And creating “smart” built distributions, such as an RPM package or an executable installer for Windows, is far more convenient for users even if your distribution doesn’t include any extensions. The **bdist** command has a `--formats` option, similar to the **sdist** command, which you can use to select the types of built distribution to generate: for example, ``` python setup.py bdist --format=zip ``` would, when run on a Unix system, create `Distutils-1.0.*plat*.zip`—again, this archive would be unpacked from the root directory to install the Distutils. The available formats for built distributions are: | Format | Description | Notes | | --- | --- | --- | | `gztar` | gzipped tar file (`.tar.gz`) | (1) | | `bztar` | bzipped tar file (`.tar.bz2`) | | | `xztar` | xzipped tar file (`.tar.xz`) | | | `ztar` | compressed tar file (`.tar.Z`) | (3) | | `tar` | tar file (`.tar`) | | | `zip` | zip file (`.zip`) | (2),(4) | | `rpm` | RPM | (5) | | `pkgtool` | Solaris **pkgtool** | | | `sdux` | HP-UX **swinstall** | | | `wininst` | self-extracting ZIP file for Windows | (4) | | `msi` | Microsoft Installer. | | Changed in version 3.5: Added support for the `xztar` format. Notes: 1. default on Unix 2. default on Windows 3. requires external **compress** utility. 4. requires either external **zip** utility or [`zipfile`](../library/zipfile#module-zipfile "zipfile: Read and write ZIP-format archive files.") module (part of the standard Python library since Python 1.6) 5. requires external **rpm** utility, version 3.0.4 or better (use `rpm --version` to find out which version you have) You don’t have to use the **bdist** command with the `--formats` option; you can also use the command that directly implements the format you’re interested in. Some of these **bdist** “sub-commands” actually generate several similar formats; for instance, the **bdist\_dumb** command generates all the “dumb” archive formats (`tar`, `gztar`, `bztar`, `xztar`, `ztar`, and `zip`), and **bdist\_rpm** generates both binary and source RPMs. The **bdist** sub-commands, and the formats generated by each, are: | Command | Formats | | --- | --- | | **bdist\_dumb** | tar, gztar, bztar, xztar, ztar, zip | | **bdist\_rpm** | rpm, srpm | | **bdist\_wininst** | wininst | | **bdist\_msi** | msi | Note bdist\_wininst is deprecated since Python 3.8. Note bdist\_msi is deprecated since Python 3.9. The following sections give details on the individual **bdist\_\*** commands. 5.1. Creating RPM packages --------------------------- The RPM format is used by many popular Linux distributions, including Red Hat, SuSE, and Mandrake. If one of these (or any of the other RPM-based Linux distributions) is your usual environment, creating RPM packages for other users of that same distribution is trivial. Depending on the complexity of your module distribution and differences between Linux distributions, you may also be able to create RPMs that work on different RPM-based distributions. The usual way to create an RPM of your module distribution is to run the **bdist\_rpm** command: ``` python setup.py bdist_rpm ``` or the **bdist** command with the `--format` option: ``` python setup.py bdist --formats=rpm ``` The former allows you to specify RPM-specific options; the latter allows you to easily specify multiple formats in one run. If you need to do both, you can explicitly specify multiple **bdist\_\*** commands and their options: ``` python setup.py bdist_rpm --packager="John Doe <[email protected]>" \ bdist_wininst --target-version="2.0" ``` Creating RPM packages is driven by a `.spec` file, much as using the Distutils is driven by the setup script. To make your life easier, the **bdist\_rpm** command normally creates a `.spec` file based on the information you supply in the setup script, on the command line, and in any Distutils configuration files. Various options and sections in the `.spec` file are derived from options in the setup script as follows: | RPM `.spec` file option or section | Distutils setup script option | | --- | --- | | Name | `name` | | Summary (in preamble) | `description` | | Version | `version` | | Vendor | `author` and `author_email`, or — & `maintainer` and `maintainer_email` | | Copyright | `license` | | Url | `url` | | %description (section) | `long_description` | Additionally, there are many options in `.spec` files that don’t have corresponding options in the setup script. Most of these are handled through options to the **bdist\_rpm** command as follows: | RPM `.spec` file option or section | **bdist\_rpm** option | default value | | --- | --- | --- | | Release | `release` | “1” | | Group | `group` | “Development/Libraries” | | Vendor | `vendor` | (see above) | | Packager | `packager` | (none) | | Provides | `provides` | (none) | | Requires | `requires` | (none) | | Conflicts | `conflicts` | (none) | | Obsoletes | `obsoletes` | (none) | | Distribution | `distribution_name` | (none) | | BuildRequires | `build_requires` | (none) | | Icon | `icon` | (none) | Obviously, supplying even a few of these options on the command-line would be tedious and error-prone, so it’s usually best to put them in the setup configuration file, `setup.cfg`—see section [Writing the Setup Configuration File](configfile#setup-config). If you distribute or package many Python module distributions, you might want to put options that apply to all of them in your personal Distutils configuration file (`~/.pydistutils.cfg`). If you want to temporarily disable this file, you can pass the `--no-user-cfg` option to `setup.py`. There are three steps to building a binary RPM package, all of which are handled automatically by the Distutils: 1. create a `.spec` file, which describes the package (analogous to the Distutils setup script; in fact, much of the information in the setup script winds up in the `.spec` file) 2. create the source RPM 3. create the “binary” RPM (which may or may not contain binary code, depending on whether your module distribution contains Python extensions) Normally, RPM bundles the last two steps together; when you use the Distutils, all three steps are typically bundled together. If you wish, you can separate these three steps. You can use the `--spec-only` option to make **bdist\_rpm** just create the `.spec` file and exit; in this case, the `.spec` file will be written to the “distribution directory”—normally `dist/`, but customizable with the `--dist-dir` option. (Normally, the `.spec` file winds up deep in the “build tree,” in a temporary directory created by **bdist\_rpm**.) 5.2. Creating Windows Installers --------------------------------- Warning bdist\_wininst is deprecated since Python 3.8. Warning bdist\_msi is deprecated since Python 3.9. Executable installers are the natural format for binary distributions on Windows. They display a nice graphical user interface, display some information about the module distribution to be installed taken from the metadata in the setup script, let the user select a few options, and start or cancel the installation. Since the metadata is taken from the setup script, creating Windows installers is usually as easy as running: ``` python setup.py bdist_wininst ``` or the **bdist** command with the `--formats` option: ``` python setup.py bdist --formats=wininst ``` If you have a pure module distribution (only containing pure Python modules and packages), the resulting installer will be version independent and have a name like `foo-1.0.win32.exe`. Note that creating `wininst` binary distributions in only supported on Windows systems. If you have a non-pure distribution, the extensions can only be created on a Windows platform, and will be Python version dependent. The installer filename will reflect this and now has the form `foo-1.0.win32-py2.0.exe`. You have to create a separate installer for every Python version you want to support. The installer will try to compile pure modules into [bytecode](../glossary#term-bytecode) after installation on the target system in normal and optimizing mode. If you don’t want this to happen for some reason, you can run the **bdist\_wininst** command with the `--no-target-compile` and/or the `--no-target-optimize` option. By default the installer will display the cool “Python Powered” logo when it is run, but you can also supply your own 152x261 bitmap which must be a Windows `.bmp` file with the `--bitmap` option. The installer will also display a large title on the desktop background window when it is run, which is constructed from the name of your distribution and the version number. This can be changed to another text by using the `--title` option. The installer file will be written to the “distribution directory” — normally `dist/`, but customizable with the `--dist-dir` option. 5.3. Cross-compiling on Windows -------------------------------- Starting with Python 2.6, distutils is capable of cross-compiling between Windows platforms. In practice, this means that with the correct tools installed, you can use a 32bit version of Windows to create 64bit extensions and vice-versa. To build for an alternate platform, specify the `--plat-name` option to the build command. Valid values are currently ‘win32’, and ‘win-amd64’. For example, on a 32bit version of Windows, you could execute: ``` python setup.py build --plat-name=win-amd64 ``` to build a 64bit version of your extension. The Windows Installers also support this option, so the command: ``` python setup.py build --plat-name=win-amd64 bdist_wininst ``` would create a 64bit installation executable on your 32bit version of Windows. To cross-compile, you must download the Python source code and cross-compile Python itself for the platform you are targeting - it is not possible from a binary installation of Python (as the .lib etc file for other platforms are not included.) In practice, this means the user of a 32 bit operating system will need to use Visual Studio 2008 to open the `PCbuild/PCbuild.sln` solution in the Python source tree and build the “x64” configuration of the ‘pythoncore’ project before cross-compiling extensions is possible. Note that by default, Visual Studio 2008 does not install 64bit compilers or tools. You may need to reexecute the Visual Studio setup process and select these tools (using Control Panel->[Add/Remove] Programs is a convenient way to check or modify your existing install.) ### 5.3.1. The Postinstallation script Starting with Python 2.3, a postinstallation script can be specified with the `--install-script` option. The basename of the script must be specified, and the script filename must also be listed in the scripts argument to the setup function. This script will be run at installation time on the target system after all the files have been copied, with `argv[1]` set to `-install`, and again at uninstallation time before the files are removed with `argv[1]` set to `-remove`. The installation script runs embedded in the windows installer, every output (`sys.stdout`, `sys.stderr`) is redirected into a buffer and will be displayed in the GUI after the script has finished. Some functions especially useful in this context are available as additional built-in functions in the installation script. `directory_created(path)` `file_created(path)` These functions should be called when a directory or file is created by the postinstall script at installation time. It will register *path* with the uninstaller, so that it will be removed when the distribution is uninstalled. To be safe, directories are only removed if they are empty. `get_special_folder_path(csidl_string)` This function can be used to retrieve special folder locations on Windows like the Start Menu or the Desktop. It returns the full path to the folder. *csidl\_string* must be one of the following strings: ``` "CSIDL_APPDATA" "CSIDL_COMMON_STARTMENU" "CSIDL_STARTMENU" "CSIDL_COMMON_DESKTOPDIRECTORY" "CSIDL_DESKTOPDIRECTORY" "CSIDL_COMMON_STARTUP" "CSIDL_STARTUP" "CSIDL_COMMON_PROGRAMS" "CSIDL_PROGRAMS" "CSIDL_FONTS" ``` If the folder cannot be retrieved, [`OSError`](../library/exceptions#OSError "OSError") is raised. Which folders are available depends on the exact Windows version, and probably also the configuration. For details refer to Microsoft’s documentation of the `SHGetSpecialFolderPath()` function. `create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])` This function creates a shortcut. *target* is the path to the program to be started by the shortcut. *description* is the description of the shortcut. *filename* is the title of the shortcut that the user will see. *arguments* specifies the command line arguments, if any. *workdir* is the working directory for the program. *iconpath* is the file containing the icon for the shortcut, and *iconindex* is the index of the icon in the file *iconpath*. Again, for details consult the Microsoft documentation for the `IShellLink` interface. 5.4. Vista User Access Control (UAC) ------------------------------------- Starting with Python 2.6, bdist\_wininst supports a `--user-access-control` option. The default is ‘none’ (meaning no UAC handling is done), and other valid values are ‘auto’ (meaning prompt for UAC elevation if Python was installed for all users) and ‘force’ (meaning always prompt for elevation). Note bdist\_wininst is deprecated since Python 3.8. Note bdist\_msi is deprecated since Python 3.9. python An Introduction to Distutils An Introduction to Distutils ============================= Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. This document covers using the Distutils to distribute your Python modules, concentrating on the role of developer/distributor: if you’re looking for information on installing Python modules, you should refer to the [Installing Python Modules (Legacy version)](../install/index#install-index) chapter. 1.1. Concepts & Terminology ---------------------------- Using the Distutils is quite simple, both for module developers and for users/administrators installing third-party modules. As a developer, your responsibilities (apart from writing solid, well-documented and well-tested code, of course!) are: * write a setup script (`setup.py` by convention) * (optional) write a setup configuration file * create a source distribution * (optional) create one or more built (binary) distributions Each of these tasks is covered in this document. Not all module developers have access to a multitude of platforms, so it’s not always feasible to expect them to create a multitude of built distributions. It is hoped that a class of intermediaries, called *packagers*, will arise to address this need. Packagers will take source distributions released by module developers, build them on one or more platforms, and release the resulting built distributions. Thus, users on the most popular platforms will be able to install most popular Python module distributions in the most natural way for their platform, without having to run a single setup script or compile a line of code. 1.2. A Simple Example ---------------------- The setup script is usually quite simple, although since it’s written in Python, there are no arbitrary limits to what you can do with it, though you should be careful about putting arbitrarily expensive operations in your setup script. Unlike, say, Autoconf-style configure scripts, the setup script may be run multiple times in the course of building and installing your module distribution. If all you want to do is distribute a module called `foo`, contained in a file `foo.py`, then your setup script can be as simple as this: ``` from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` Some observations: * most information that you supply to the Distutils is supplied as keyword arguments to the `setup()` function * those keyword arguments fall into two categories: package metadata (name, version number) and information about what’s in the package (a list of pure Python modules, in this case) * modules are specified by module name, not filename (the same will hold true for packages and extensions) * it’s recommended that you supply a little more metadata, in particular your name, email address and a URL for the project (see section [Writing the Setup Script](setupscript#setup-script) for an example) To create a source distribution for this module, you would create a setup script, `setup.py`, containing the above code, and run this command from a terminal: ``` python setup.py sdist ``` For Windows, open a command prompt window (Start ‣ Accessories) and change the command to: ``` setup.py sdist ``` **sdist** will create an archive file (e.g., tarball on Unix, ZIP file on Windows) containing your setup script `setup.py`, and your module `foo.py`. The archive file will be named `foo-1.0.tar.gz` (or `.zip`), and will unpack into a directory `foo-1.0`. If an end-user wishes to install your `foo` module, all they have to do is download `foo-1.0.tar.gz` (or `.zip`), unpack it, and—from the `foo-1.0` directory—run ``` python setup.py install ``` which will ultimately copy `foo.py` to the appropriate directory for third-party modules in their Python installation. This simple example demonstrates some fundamental concepts of the Distutils. First, both developers and installers have the same basic user interface, i.e. the setup script. The difference is which Distutils *commands* they use: the **sdist** command is almost exclusively for module developers, while **install** is more often for installers (although most developers will want to install their own code occasionally). If you want to make things really easy for your users, you can create one or more built distributions for them. For instance, if you are running on a Windows machine, and want to make things easy for other Windows users, you can create an executable installer (the most appropriate type of built distribution for this platform) with the **bdist\_wininst** command. For example: ``` python setup.py bdist_wininst ``` will create an executable installer, `foo-1.0.win32.exe`, in the current directory. Other useful built distribution formats are RPM, implemented by the **bdist\_rpm** command, Solaris **pkgtool** (**bdist\_pkgtool**), and HP-UX **swinstall** (**bdist\_sdux**). For example, the following command will create an RPM file called `foo-1.0.noarch.rpm`: ``` python setup.py bdist_rpm ``` (The **bdist\_rpm** command uses the **rpm** executable, therefore this has to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or Mandrake Linux.) You can find out what distribution formats are available at any time by running ``` python setup.py bdist --help-formats ``` 1.3. General Python terminology -------------------------------- If you’re reading this document, you probably have a good idea of what modules, extensions, and so forth are. Nevertheless, just to be sure that everyone is operating from a common starting point, we offer the following glossary of common Python terms: module the basic unit of code reusability in Python: a block of code imported by some other code. Three types of modules concern us here: pure Python modules, extension modules, and packages. pure Python module a module written in Python and contained in a single `.py` file (and possibly associated `.pyc` files). Sometimes referred to as a “pure module.” extension module a module written in the low-level language of the Python implementation: C/C++ for Python, Java for Jython. Typically contained in a single dynamically loadable pre-compiled file, e.g. a shared object (`.so`) file for Python extensions on Unix, a DLL (given the `.pyd` extension) for Python extensions on Windows, or a Java class file for Jython extensions. (Note that currently, the Distutils only handles C/C++ extensions for Python.) package a module that contains other modules; typically contained in a directory in the filesystem and distinguished from other directories by the presence of a file `__init__.py`. root package the root of the hierarchy of packages. (This isn’t really a package, since it doesn’t have an `__init__.py` file. But we have to call it something.) The vast majority of the standard library is in the root package, as are many small, standalone third-party modules that don’t belong to a larger module collection. Unlike regular packages, modules in the root package can be found in many directories: in fact, every directory listed in `sys.path` contributes modules to the root package. 1.4. Distutils-specific terminology ------------------------------------ The following terms apply more specifically to the domain of distributing Python modules using the Distutils: module distribution a collection of Python modules distributed together as a single downloadable resource and meant to be installed *en masse*. Examples of some well-known module distributions are NumPy, SciPy, Pillow, or mxBase. (This would be called a *package*, except that term is already taken in the Python context: a single module distribution may contain zero, one, or many Python packages.) pure module distribution a module distribution that contains only pure Python modules and packages. Sometimes referred to as a “pure distribution.” non-pure module distribution a module distribution that contains at least one extension module. Sometimes referred to as a “non-pure distribution.” distribution root the top-level directory of your source tree (or source distribution); the directory where `setup.py` exists. Generally `setup.py` will be run from this directory.
programming_docs
python Command Reference Command Reference ================== Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. 8.1. Installing modules: the **install** command family -------------------------------------------------------- The install command ensures that the build commands have been run and then runs the subcommands **install\_lib**, **install\_data** and **install\_scripts**. ### 8.1.1. **install\_data** This command installs all data files provided with the distribution. ### 8.1.2. **install\_scripts** This command installs all (Python) scripts in the distribution. 8.2. Creating a source distribution: the **sdist** command ----------------------------------------------------------- The manifest template commands are: | Command | Description | | --- | --- | | **include pat1 pat2 ...** | include all files matching any of the listed patterns | | **exclude pat1 pat2 ...** | exclude all files matching any of the listed patterns | | **recursive-include dir pat1 pat2 ...** | include all files under *dir* matching any of the listed patterns | | **recursive-exclude dir pat1 pat2 ...** | exclude all files under *dir* matching any of the listed patterns | | **global-include pat1 pat2 ...** | include all files anywhere in the source tree matching — & any of the listed patterns | | **global-exclude pat1 pat2 ...** | exclude all files anywhere in the source tree matching — & any of the listed patterns | | **prune dir** | exclude all files under *dir* | | **graft dir** | include all files under *dir* | The patterns here are Unix-style “glob” patterns: `*` matches any sequence of regular filename characters, `?` matches any single regular filename character, and `[range]` matches any of the characters in *range* (e.g., `a-z`, `a-zA-Z`, `a-f0-9_.`). The definition of “regular filename character” is platform-specific: on Unix it is anything except slash; on Windows anything except backslash or colon. python Whetting Your Appetite Whetting Your Appetite ======================= If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or rename and rearrange a bunch of photo files in a complicated way. Perhaps you’d like to write a small custom database, or a specialized GUI application, or a simple game. If you’re a professional software developer, you may have to work with several C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re writing a test suite for such a library and find writing the testing code a tedious task. Or maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application. Python is just the language for you. You could write a Unix shell script or Windows batch files for some of these tasks, but shell scripts are best at moving around files and changing text data, not well-suited for GUI applications or games. You could write a C/C++/Java program, but it can take a lot of development time to get even a first-draft program. Python is simpler to use, available on Windows, macOS, and Unix operating systems, and will help you get the job done more quickly. Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than shell scripts or batch files can offer. On the other hand, Python also offers much more error checking than C, and, being a *very-high-level language*, it has high-level data types built in, such as flexible arrays and dictionaries. Because of its more general data types Python is applicable to a much larger problem domain than Awk or even Perl, yet many things are at least as easy in Python as in those languages. Python allows you to split your program into modules that can be reused in other Python programs. It comes with a large collection of standard modules that you can use as the basis of your programs — or as examples to start learning to program in Python. Some of these modules provide things like file I/O, system calls, sockets, and even interfaces to graphical user interface toolkits like Tk. Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary. The interpreter can be used interactively, which makes it easy to experiment with features of the language, to write throw-away programs, or to test functions during bottom-up program development. It is also a handy desk calculator. Python enables programs to be written compactly and readably. Programs written in Python are typically much shorter than equivalent C, C++, or Java programs, for several reasons: * the high-level data types allow you to express complex operations in a single statement; * statement grouping is done by indentation instead of beginning and ending brackets; * no variable or argument declarations are necessary. Python is *extensible*: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application. By the way, the language is named after the BBC show “Monty Python’s Flying Circus” and has nothing to do with reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged! Now that you are all excited about Python, you’ll want to examine it in some more detail. Since the best way to learn a language is to use it, the tutorial invites you to play with the Python interpreter as you read. In the next chapter, the mechanics of using the interpreter are explained. This is rather mundane information, but essential for trying out the examples shown later. The rest of the tutorial introduces various features of the Python language and system through examples, beginning with simple expressions, statements and data types, through functions and modules, and finally touching upon advanced concepts like exceptions and user-defined classes. python Brief Tour of the Standard Library Brief Tour of the Standard Library =================================== 10.1. Operating System Interface --------------------------------- The [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces.") module provides dozens of functions for interacting with the operating system: ``` >>> import os >>> os.getcwd() # Return the current working directory 'C:\\Python39' >>> os.chdir('/server/accesslogs') # Change current working directory >>> os.system('mkdir today') # Run the command mkdir in the system shell 0 ``` Be sure to use the `import os` style instead of `from os import *`. This will keep [`os.open()`](../library/os#os.open "os.open") from shadowing the built-in [`open()`](../library/functions#open "open") function which operates much differently. The built-in [`dir()`](../library/functions#dir "dir") and [`help()`](../library/functions#help "help") functions are useful as interactive aids for working with large modules like [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces."): ``` >>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings> ``` For daily file and directory management tasks, the [`shutil`](../library/shutil#module-shutil "shutil: High-level file operations, including copying.") module provides a higher level interface that is easier to use: ``` >>> import shutil >>> shutil.copyfile('data.db', 'archive.db') 'archive.db' >>> shutil.move('/build/executables', 'installdir') 'installdir' ``` 10.2. File Wildcards --------------------- The [`glob`](../library/glob#module-glob "glob: Unix shell style pathname pattern expansion.") module provides a function for making file lists from directory wildcard searches: ``` >>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py'] ``` 10.3. Command Line Arguments ----------------------------- Common utility scripts often need to process command line arguments. These arguments are stored in the [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module’s *argv* attribute as a list. For instance the following output results from running `python demo.py one two three` at the command line: ``` >>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three'] ``` The [`argparse`](../library/argparse#module-argparse "argparse: Command-line option and argument parsing library.") module provides a more sophisticated mechanism to process command line arguments. The following script extracts one or more filenames and an optional number of lines to be displayed: ``` import argparse parser = argparse.ArgumentParser( prog='top', description='Show top lines from each file') parser.add_argument('filenames', nargs='+') parser.add_argument('-l', '--lines', type=int, default=10) args = parser.parse_args() print(args) ``` When run at the command line with `python top.py --lines=5 alpha.txt beta.txt`, the script sets `args.lines` to `5` and `args.filenames` to `['alpha.txt', 'beta.txt']`. 10.4. Error Output Redirection and Program Termination ------------------------------------------------------- The [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module also has attributes for *stdin*, *stdout*, and *stderr*. The latter is useful for emitting warnings and error messages to make them visible even when *stdout* has been redirected: ``` >>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one ``` The most direct way to terminate a script is to use `sys.exit()`. 10.5. String Pattern Matching ------------------------------ The [`re`](../library/re#module-re "re: Regular expression operations.") module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions: ``` >>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' ``` When only simple capabilities are needed, string methods are preferred because they are easier to read and debug: ``` >>> 'tea for too'.replace('too', 'two') 'tea for two' ``` 10.6. Mathematics ------------------ The [`math`](../library/math#module-math "math: Mathematical functions (sin() etc.).") module gives access to the underlying C library functions for floating point math: ``` >>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0 ``` The [`random`](../library/random#module-random "random: Generate pseudo-random numbers with various common distributions.") module provides tools for making random selections: ``` >>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4 ``` The [`statistics`](../library/statistics#module-statistics "statistics: Mathematical statistics functions") module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data: ``` >>> import statistics >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> statistics.mean(data) 1.6071428571428572 >>> statistics.median(data) 1.25 >>> statistics.variance(data) 1.3720238095238095 ``` The SciPy project <<https://scipy.org>> has many other modules for numerical computations. 10.7. Internet Access ---------------------- There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are [`urllib.request`](../library/urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs.") for retrieving data from URLs and [`smtplib`](../library/smtplib#module-smtplib "smtplib: SMTP protocol client (requires sockets).") for sending mail: ``` >>> from urllib.request import urlopen >>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response: ... for line in response: ... line = line.decode() # Convert bytes to a str ... if line.startswith('datetime'): ... print(line.rstrip()) # Remove trailing newline ... datetime: 2022-01-01T01:36:47.689215+00:00 >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit() ``` (Note that the second example needs a mailserver running on localhost.) 10.8. Dates and Times ---------------------- The [`datetime`](../library/datetime#module-datetime "datetime: Basic date and time types.") module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation. The module also supports objects that are timezone aware. ``` >>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368 ``` 10.9. Data Compression ----------------------- Common data archiving and compression formats are directly supported by modules including: [`zlib`](../library/zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip."), [`gzip`](../library/gzip#module-gzip "gzip: Interfaces for gzip compression and decompression using file objects."), [`bz2`](../library/bz2#module-bz2 "bz2: Interfaces for bzip2 compression and decompression."), [`lzma`](../library/lzma#module-lzma "lzma: A Python wrapper for the liblzma compression library."), [`zipfile`](../library/zipfile#module-zipfile "zipfile: Read and write ZIP-format archive files.") and [`tarfile`](../library/tarfile#module-tarfile "tarfile: Read and write tar-format archive files."). ``` >>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979 ``` 10.10. Performance Measurement ------------------------------- Some Python users develop a deep interest in knowing the relative performance of different approaches to the same problem. Python provides a measurement tool that answers those questions immediately. For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The [`timeit`](../library/timeit#module-timeit "timeit: Measure the execution time of small code snippets.") module quickly demonstrates a modest performance advantage: ``` >>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791 ``` In contrast to [`timeit`](../library/timeit#module-timeit "timeit: Measure the execution time of small code snippets.")’s fine level of granularity, the [`profile`](../library/profile#module-profile "profile: Python source profiler.") and [`pstats`](../library/profile#module-pstats "pstats: Statistics object for use with the profiler.") modules provide tools for identifying time critical sections in larger blocks of code. 10.11. Quality Control ----------------------- One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process. The [`doctest`](../library/doctest#module-doctest "doctest: Test pieces of code within docstrings.") module provides a tool for scanning a module and validating tests embedded in a program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring. This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation: ``` def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests ``` The [`unittest`](../library/unittest#module-unittest "unittest: Unit testing framework for Python.") module is not as effortless as the [`doctest`](../library/doctest#module-doctest "doctest: Test pieces of code within docstrings.") module, but it allows a more comprehensive set of tests to be maintained in a separate file: ``` import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests ``` 10.12. Batteries Included -------------------------- Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example: * The [`xmlrpc.client`](../library/xmlrpc.client#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") and [`xmlrpc.server`](../library/xmlrpc.server#module-xmlrpc.server "xmlrpc.server: Basic XML-RPC server implementations.") modules make implementing remote procedure calls into an almost trivial task. Despite the modules’ names, no direct knowledge or handling of XML is needed. * The [`email`](../library/email#module-email "email: Package supporting the parsing, manipulating, and generating email messages.") package is a library for managing email messages, including MIME and other [**RFC 2822**](https://tools.ietf.org/html/rfc2822.html)-based message documents. Unlike [`smtplib`](../library/smtplib#module-smtplib "smtplib: SMTP protocol client (requires sockets).") and [`poplib`](../library/poplib#module-poplib "poplib: POP3 protocol client (requires sockets).") which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols. * The [`json`](../library/json#module-json "json: Encode and decode the JSON format.") package provides robust support for parsing this popular data interchange format. The [`csv`](../library/csv#module-csv "csv: Write and read tabular data to and from delimited files.") module supports direct reading and writing of files in Comma-Separated Value format, commonly supported by databases and spreadsheets. XML processing is supported by the [`xml.etree.ElementTree`](../library/xml.etree.elementtree#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API."), [`xml.dom`](../library/xml.dom#module-xml.dom "xml.dom: Document Object Model API for Python.") and [`xml.sax`](../library/xml.sax#module-xml.sax "xml.sax: Package containing SAX2 base classes and convenience functions.") packages. Together, these modules and packages greatly simplify data interchange between Python applications and other tools. * The [`sqlite3`](../library/sqlite3#module-sqlite3 "sqlite3: A DB-API 2.0 implementation using SQLite 3.x.") module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax. * Internationalization is supported by a number of modules including [`gettext`](../library/gettext#module-gettext "gettext: Multilingual internationalization services."), [`locale`](../library/locale#module-locale "locale: Internationalization services."), and the [`codecs`](../library/codecs#module-codecs "codecs: Encode and decode data and streams.") package.
programming_docs
python Interactive Input Editing and History Substitution Interactive Input Editing and History Substitution =================================================== Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the [GNU Readline](https://tiswww.case.edu/php/chet/readline/rltop.html) library, which supports various styles of editing. This library has its own documentation which we won’t duplicate here. 14.1. Tab Completion and History Editing ----------------------------------------- Completion of variable and module names is [automatically enabled](../library/site#rlcompleter-config) at interpreter startup so that the `Tab` key invokes the completion function; it looks at Python statement names, the current local variables, and the available module names. For dotted expressions such as `string.a`, it will evaluate the expression up to the final `'.'` and then suggest completions from the attributes of the resulting object. Note that this may execute application-defined code if an object with a [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") method is part of the expression. The default configuration also saves your history into a file named `.python_history` in your user directory. The history will be available again during the next interactive interpreter session. 14.2. Alternatives to the Interactive Interpreter -------------------------------------------------- This facility is an enormous step forward compared to earlier versions of the interpreter; however, some wishes are left: It would be nice if the proper indentation were suggested on continuation lines (the parser knows if an indent token is required next). The completion mechanism might use the interpreter’s symbol table. A command to check (or even suggest) matching parentheses, quotes, etc., would also be useful. One alternative enhanced interactive interpreter that has been around for quite some time is [IPython](https://ipython.org/), which features tab completion, object exploration and advanced history management. It can also be thoroughly customized and embedded into other applications. Another similar enhanced interactive environment is [bpython](https://www.bpython-interpreter.org/). python Virtual Environments and Packages Virtual Environments and Packages ================================== 12.1. Introduction ------------------- Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because the application may require that a particular bug has been fixed or the application may be written using an obsolete version of the library’s interface. This means it may not be possible for one Python installation to meet the requirements of every application. If application A needs version 1.0 of a particular module but application B needs version 2.0, then the requirements are in conflict and installing either version 1.0 or 2.0 will leave one application unable to run. The solution for this problem is to create a [virtual environment](../glossary#term-virtual-environment), a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. Different applications can then use different virtual environments. To resolve the earlier example of conflicting requirements, application A can have its own virtual environment with version 1.0 installed while application B has another virtual environment with version 2.0. If application B requires a library be upgraded to version 3.0, this will not affect application A’s environment. 12.2. Creating Virtual Environments ------------------------------------ The module used to create and manage virtual environments is called [`venv`](../library/venv#module-venv "venv: Creation of virtual environments."). [`venv`](../library/venv#module-venv "venv: Creation of virtual environments.") will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running `python3` or whichever version you want. To create a virtual environment, decide upon a directory where you want to place it, and run the [`venv`](../library/venv#module-venv "venv: Creation of virtual environments.") module as a script with the directory path: ``` python3 -m venv tutorial-env ``` This will create the `tutorial-env` directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. A common directory location for a virtual environment is `.venv`. This name keeps the directory typically hidden in your shell and thus out of the way while giving it a name that explains why the directory exists. It also prevents clashing with `.env` environment variable definition files that some tooling supports. Once you’ve created a virtual environment, you may activate it. On Windows, run: ``` tutorial-env\Scripts\activate.bat ``` On Unix or MacOS, run: ``` source tutorial-env/bin/activate ``` (This script is written for the bash shell. If you use the **csh** or **fish** shells, there are alternate `activate.csh` and `activate.fish` scripts you should use instead.) Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using, and modify the environment so that running `python` will get you that particular version and installation of Python. For example: ``` $ source ~/envs/tutorial-env/bin/activate (tutorial-env) $ python Python 3.5.1 (default, May 6 2016, 10:59:36) ... >>> import sys >>> sys.path ['', '/usr/local/lib/python35.zip', ..., '~/envs/tutorial-env/lib/python3.5/site-packages'] >>> ``` 12.3. Managing Packages with pip --------------------------------- You can install, upgrade, and remove packages using a program called **pip**. By default `pip` will install packages from the Python Package Index, <<https://pypi.org>>. You can browse the Python Package Index by going to it in your web browser. `pip` has a number of subcommands: “install”, “uninstall”, “freeze”, etc. (Consult the [Installing Python Modules](../installing/index#installing-index) guide for complete documentation for `pip`.) You can install the latest version of a package by specifying a package’s name: ``` (tutorial-env) $ python -m pip install novas Collecting novas Downloading novas-3.1.1.3.tar.gz (136kB) Installing collected packages: novas Running setup.py install for novas Successfully installed novas-3.1.1.3 ``` You can also install a specific version of a package by giving the package name followed by `==` and the version number: ``` (tutorial-env) $ python -m pip install requests==2.6.0 Collecting requests==2.6.0 Using cached requests-2.6.0-py2.py3-none-any.whl Installing collected packages: requests Successfully installed requests-2.6.0 ``` If you re-run this command, `pip` will notice that the requested version is already installed and do nothing. You can supply a different version number to get that version, or you can run `pip install --upgrade` to upgrade the package to the latest version: ``` (tutorial-env) $ python -m pip install --upgrade requests Collecting requests Installing collected packages: requests Found existing installation: requests 2.6.0 Uninstalling requests-2.6.0: Successfully uninstalled requests-2.6.0 Successfully installed requests-2.7.0 ``` `pip uninstall` followed by one or more package names will remove the packages from the virtual environment. `pip show` will display information about a particular package: ``` (tutorial-env) $ pip show requests --- Metadata-Version: 2.0 Name: requests Version: 2.7.0 Summary: Python HTTP for Humans. Home-page: http://python-requests.org Author: Kenneth Reitz Author-email: [email protected] License: Apache 2.0 Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages Requires: ``` `pip list` will display all of the packages installed in the virtual environment: ``` (tutorial-env) $ pip list novas (3.1.1.3) numpy (1.9.2) pip (7.0.3) requests (2.7.0) setuptools (16.0) ``` `pip freeze` will produce a similar list of the installed packages, but the output uses the format that `pip install` expects. A common convention is to put this list in a `requirements.txt` file: ``` (tutorial-env) $ pip freeze > requirements.txt (tutorial-env) $ cat requirements.txt novas==3.1.1.3 numpy==1.9.2 requests==2.7.0 ``` The `requirements.txt` can then be committed to version control and shipped as part of an application. Users can then install all the necessary packages with `install -r`: ``` (tutorial-env) $ python -m pip install -r requirements.txt Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) ... Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) ... Collecting requests==2.7.0 (from -r requirements.txt (line 3)) ... Installing collected packages: novas, numpy, requests Running setup.py install for novas Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0 ``` `pip` has many more options. Consult the [Installing Python Modules](../installing/index#installing-index) guide for complete documentation for `pip`. When you’ve written a package and want to make it available on the Python Package Index, consult the [Distributing Python Modules](../distributing/index#distributing-index) guide. python The Python Tutorial The Python Tutorial =================== Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, <https://www.python.org/>, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation. The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications. This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see [The Python Standard Library](../library/index#library-index). [The Python Language Reference](../reference/index#reference-index) gives a more formal definition of the language. To write extensions in C or C++, read [Extending and Embedding the Python Interpreter](../extending/index#extending-index) and [Python/C API Reference Manual](../c-api/index#c-api-index). There are also several books covering Python in depth. This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. Instead, it introduces many of Python’s most noteworthy features, and will give you a good idea of the language’s flavor and style. After reading it, you will be able to read and write Python modules and programs, and you will be ready to learn more about the various Python library modules described in [The Python Standard Library](../library/index#library-index). The [Glossary](../glossary#glossary) is also worth going through. * [1. Whetting Your Appetite](appetite) * [2. Using the Python Interpreter](interpreter) + [2.1. Invoking the Interpreter](interpreter#invoking-the-interpreter) - [2.1.1. Argument Passing](interpreter#argument-passing) - [2.1.2. Interactive Mode](interpreter#interactive-mode) + [2.2. The Interpreter and Its Environment](interpreter#the-interpreter-and-its-environment) - [2.2.1. Source Code Encoding](interpreter#source-code-encoding) * [3. An Informal Introduction to Python](introduction) + [3.1. Using Python as a Calculator](introduction#using-python-as-a-calculator) - [3.1.1. Numbers](introduction#numbers) - [3.1.2. Strings](introduction#strings) - [3.1.3. Lists](introduction#lists) + [3.2. First Steps Towards Programming](introduction#first-steps-towards-programming) * [4. More Control Flow Tools](controlflow) + [4.1. `if` Statements](controlflow#if-statements) + [4.2. `for` Statements](controlflow#for-statements) + [4.3. The `range()` Function](controlflow#the-range-function) + [4.4. `break` and `continue` Statements, and `else` Clauses on Loops](controlflow#break-and-continue-statements-and-else-clauses-on-loops) + [4.5. `pass` Statements](controlflow#pass-statements) + [4.6. Defining Functions](controlflow#defining-functions) + [4.7. More on Defining Functions](controlflow#more-on-defining-functions) - [4.7.1. Default Argument Values](controlflow#default-argument-values) - [4.7.2. Keyword Arguments](controlflow#keyword-arguments) - [4.7.3. Special parameters](controlflow#special-parameters) * [4.7.3.1. Positional-or-Keyword Arguments](controlflow#positional-or-keyword-arguments) * [4.7.3.2. Positional-Only Parameters](controlflow#positional-only-parameters) * [4.7.3.3. Keyword-Only Arguments](controlflow#keyword-only-arguments) * [4.7.3.4. Function Examples](controlflow#function-examples) * [4.7.3.5. Recap](controlflow#recap) - [4.7.4. Arbitrary Argument Lists](controlflow#arbitrary-argument-lists) - [4.7.5. Unpacking Argument Lists](controlflow#unpacking-argument-lists) - [4.7.6. Lambda Expressions](controlflow#lambda-expressions) - [4.7.7. Documentation Strings](controlflow#documentation-strings) - [4.7.8. Function Annotations](controlflow#function-annotations) + [4.8. Intermezzo: Coding Style](controlflow#intermezzo-coding-style) * [5. Data Structures](datastructures) + [5.1. More on Lists](datastructures#more-on-lists) - [5.1.1. Using Lists as Stacks](datastructures#using-lists-as-stacks) - [5.1.2. Using Lists as Queues](datastructures#using-lists-as-queues) - [5.1.3. List Comprehensions](datastructures#list-comprehensions) - [5.1.4. Nested List Comprehensions](datastructures#nested-list-comprehensions) + [5.2. The `del` statement](datastructures#the-del-statement) + [5.3. Tuples and Sequences](datastructures#tuples-and-sequences) + [5.4. Sets](datastructures#sets) + [5.5. Dictionaries](datastructures#dictionaries) + [5.6. Looping Techniques](datastructures#looping-techniques) + [5.7. More on Conditions](datastructures#more-on-conditions) + [5.8. Comparing Sequences and Other Types](datastructures#comparing-sequences-and-other-types) * [6. Modules](modules) + [6.1. More on Modules](modules#more-on-modules) - [6.1.1. Executing modules as scripts](modules#executing-modules-as-scripts) - [6.1.2. The Module Search Path](modules#the-module-search-path) - [6.1.3. “Compiled” Python files](modules#compiled-python-files) + [6.2. Standard Modules](modules#standard-modules) + [6.3. The `dir()` Function](modules#the-dir-function) + [6.4. Packages](modules#packages) - [6.4.1. Importing \* From a Package](modules#importing-from-a-package) - [6.4.2. Intra-package References](modules#intra-package-references) - [6.4.3. Packages in Multiple Directories](modules#packages-in-multiple-directories) * [7. Input and Output](inputoutput) + [7.1. Fancier Output Formatting](inputoutput#fancier-output-formatting) - [7.1.1. Formatted String Literals](inputoutput#formatted-string-literals) - [7.1.2. The String format() Method](inputoutput#the-string-format-method) - [7.1.3. Manual String Formatting](inputoutput#manual-string-formatting) - [7.1.4. Old string formatting](inputoutput#old-string-formatting) + [7.2. Reading and Writing Files](inputoutput#reading-and-writing-files) - [7.2.1. Methods of File Objects](inputoutput#methods-of-file-objects) - [7.2.2. Saving structured data with `json`](inputoutput#saving-structured-data-with-json) * [8. Errors and Exceptions](errors) + [8.1. Syntax Errors](errors#syntax-errors) + [8.2. Exceptions](errors#exceptions) + [8.3. Handling Exceptions](errors#handling-exceptions) + [8.4. Raising Exceptions](errors#raising-exceptions) + [8.5. Exception Chaining](errors#exception-chaining) + [8.6. User-defined Exceptions](errors#user-defined-exceptions) + [8.7. Defining Clean-up Actions](errors#defining-clean-up-actions) + [8.8. Predefined Clean-up Actions](errors#predefined-clean-up-actions) * [9. Classes](classes) + [9.1. A Word About Names and Objects](classes#a-word-about-names-and-objects) + [9.2. Python Scopes and Namespaces](classes#python-scopes-and-namespaces) - [9.2.1. Scopes and Namespaces Example](classes#scopes-and-namespaces-example) + [9.3. A First Look at Classes](classes#a-first-look-at-classes) - [9.3.1. Class Definition Syntax](classes#class-definition-syntax) - [9.3.2. Class Objects](classes#class-objects) - [9.3.3. Instance Objects](classes#instance-objects) - [9.3.4. Method Objects](classes#method-objects) - [9.3.5. Class and Instance Variables](classes#class-and-instance-variables) + [9.4. Random Remarks](classes#random-remarks) + [9.5. Inheritance](classes#inheritance) - [9.5.1. Multiple Inheritance](classes#multiple-inheritance) + [9.6. Private Variables](classes#private-variables) + [9.7. Odds and Ends](classes#odds-and-ends) + [9.8. Iterators](classes#iterators) + [9.9. Generators](classes#generators) + [9.10. Generator Expressions](classes#generator-expressions) * [10. Brief Tour of the Standard Library](stdlib) + [10.1. Operating System Interface](stdlib#operating-system-interface) + [10.2. File Wildcards](stdlib#file-wildcards) + [10.3. Command Line Arguments](stdlib#command-line-arguments) + [10.4. Error Output Redirection and Program Termination](stdlib#error-output-redirection-and-program-termination) + [10.5. String Pattern Matching](stdlib#string-pattern-matching) + [10.6. Mathematics](stdlib#mathematics) + [10.7. Internet Access](stdlib#internet-access) + [10.8. Dates and Times](stdlib#dates-and-times) + [10.9. Data Compression](stdlib#data-compression) + [10.10. Performance Measurement](stdlib#performance-measurement) + [10.11. Quality Control](stdlib#quality-control) + [10.12. Batteries Included](stdlib#batteries-included) * [11. Brief Tour of the Standard Library — Part II](stdlib2) + [11.1. Output Formatting](stdlib2#output-formatting) + [11.2. Templating](stdlib2#templating) + [11.3. Working with Binary Data Record Layouts](stdlib2#working-with-binary-data-record-layouts) + [11.4. Multi-threading](stdlib2#multi-threading) + [11.5. Logging](stdlib2#logging) + [11.6. Weak References](stdlib2#weak-references) + [11.7. Tools for Working with Lists](stdlib2#tools-for-working-with-lists) + [11.8. Decimal Floating Point Arithmetic](stdlib2#decimal-floating-point-arithmetic) * [12. Virtual Environments and Packages](venv) + [12.1. Introduction](venv#introduction) + [12.2. Creating Virtual Environments](venv#creating-virtual-environments) + [12.3. Managing Packages with pip](venv#managing-packages-with-pip) * [13. What Now?](whatnow) * [14. Interactive Input Editing and History Substitution](interactive) + [14.1. Tab Completion and History Editing](interactive#tab-completion-and-history-editing) + [14.2. Alternatives to the Interactive Interpreter](interactive#alternatives-to-the-interactive-interpreter) * [15. Floating Point Arithmetic: Issues and Limitations](floatingpoint) + [15.1. Representation Error](floatingpoint#representation-error) * [16. Appendix](appendix) + [16.1. Interactive Mode](appendix#interactive-mode) - [16.1.1. Error Handling](appendix#error-handling) - [16.1.2. Executable Python Scripts](appendix#executable-python-scripts) - [16.1.3. The Interactive Startup File](appendix#the-interactive-startup-file) - [16.1.4. The Customization Modules](appendix#the-customization-modules)
programming_docs
python Modules Modules ======== If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a *script*. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program. To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a *module*; definitions from a module can be *imported* into other modules or into the *main* module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). A module is a file containing Python definitions and statements. The file name is the module name with the suffix `.py` appended. Within a module, the module’s name (as a string) is available as the value of the global variable `__name__`. For instance, use your favorite text editor to create a file called `fibo.py` in the current directory with the following contents: ``` # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result ``` Now enter the Python interpreter and import this module with the following command: ``` >>> import fibo ``` This does not enter the names of the functions defined in `fibo` directly in the current symbol table; it only enters the module name `fibo` there. Using the module name you can access the functions: ``` >>> fibo.fib(1000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo' ``` If you intend to use a function often you can assign it to a local name: ``` >>> fib = fibo.fib >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ``` 6.1. More on Modules --------------------- A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the *first* time the module name is encountered in an import statement. [1](#id2) (They are also run if the file is executed as a script.) Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, `modname.itemname`. Modules can import other modules. It is customary but not required to place all [`import`](../reference/simple_stmts#import) statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table. There is a variant of the [`import`](../reference/simple_stmts#import) statement that imports names from a module directly into the importing module’s symbol table. For example: ``` >>> from fibo import fib, fib2 >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ``` This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, `fibo` is not defined). There is even a variant to import all names that a module defines: ``` >>> from fibo import * >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ``` This imports all names except those beginning with an underscore (`_`). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined. Note that in general the practice of importing `*` from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions. If the module name is followed by `as`, then the name following `as` is bound directly to the imported module. ``` >>> import fibo as fib >>> fib.fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ``` This is effectively importing the module in the same way that `import fibo` will do, with the only difference of it being available as `fib`. It can also be used when utilising [`from`](../reference/simple_stmts#from) with similar effects: ``` >>> from fibo import fib as fibonacci >>> fibonacci(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ``` Note For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use [`importlib.reload()`](../library/importlib#importlib.reload "importlib.reload"), e.g. `import importlib; importlib.reload(modulename)`. ### 6.1.1. Executing modules as scripts When you run a Python module with ``` python fibo.py <arguments> ``` the code in the module will be executed, just as if you imported it, but with the `__name__` set to `"__main__"`. That means that by adding this code at the end of your module: ``` if __name__ == "__main__": import sys fib(int(sys.argv[1])) ``` you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file: ``` $ python fibo.py 50 0 1 1 2 3 5 8 13 21 34 ``` If the module is imported, the code is not run: ``` >>> import fibo >>> ``` This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite). ### 6.1.2. The Module Search Path When a module named `spam` is imported, the interpreter first searches for a built-in module with that name. These module names are listed in [`sys.builtin_module_names`](../library/sys#sys.builtin_module_names "sys.builtin_module_names"). If not found, it then searches for a file named `spam.py` in a list of directories given by the variable [`sys.path`](../library/sys#sys.path "sys.path"). [`sys.path`](../library/sys#sys.path "sys.path") is initialized from these locations: * The directory containing the input script (or the current directory when no file is specified). * [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) (a list of directory names, with the same syntax as the shell variable `PATH`). * The installation-dependent default (by convention including a `site-packages` directory, handled by the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module). Note On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is **not** added to the module search path. After initialization, Python programs can modify [`sys.path`](../library/sys#sys.path "sys.path"). The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section [Standard Modules](#tut-standardmodules) for more information. ### 6.1.3. “Compiled” Python files To speed up loading modules, Python caches the compiled version of each module in the `__pycache__` directory under the name `module.*version*.pyc`, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as `__pycache__/spam.cpython-33.pyc`. This naming convention allows compiled modules from different releases and different versions of Python to coexist. Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures. Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module. Some tips for experts: * You can use the [`-O`](../using/cmdline#cmdoption-o) or [`-OO`](../using/cmdline#cmdoption-oo) switches on the Python command to reduce the size of a compiled module. The `-O` switch removes assert statements, the `-OO` switch removes both assert statements and \_\_doc\_\_ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an `opt-` tag and are usually smaller. Future releases may change the effects of optimization. * A program doesn’t run any faster when it is read from a `.pyc` file than when it is read from a `.py` file; the only thing that’s faster about `.pyc` files is the speed with which they are loaded. * The module [`compileall`](../library/compileall#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") can create .pyc files for all modules in a directory. * There is more detail on this process, including a flow chart of the decisions, in [**PEP 3147**](https://www.python.org/dev/peps/pep-3147). 6.2. Standard Modules ---------------------- Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the [`winreg`](../library/winreg#module-winreg "winreg: Routines and objects for manipulating the Windows registry. (Windows)") module is only provided on Windows systems. One particular module deserves some attention: [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions."), which is built into every Python interpreter. The variables `sys.ps1` and `sys.ps2` define the strings used as primary and secondary prompts: ``` >>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = 'C> ' C> print('Yuck!') Yuck! C> ``` These two variables are only defined if the interpreter is in interactive mode. The variable `sys.path` is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH), or from a built-in default if [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) is not set. You can modify it using standard list operations: ``` >>> import sys >>> sys.path.append('/ufs/guido/lib/python') ``` 6.3. The dir() Function ------------------------ The built-in function [`dir()`](../library/functions#dir "dir") is used to find out which names a module defines. It returns a sorted list of strings: ``` >>> import fibo, sys >>> dir(fibo) ['__name__', 'fib', 'fib2'] >>> dir(sys) ['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework', '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', 'warnoptions'] ``` Without arguments, [`dir()`](../library/functions#dir "dir") lists the names you have defined currently: ``` >>> a = [1, 2, 3, 4, 5] >>> import fibo >>> fib = fibo.fib >>> dir() ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] ``` Note that it lists all types of names: variables, modules, functions, etc. [`dir()`](../library/functions#dir "dir") does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace."): ``` >>> import builtins >>> dir(builtins) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] ``` 6.4. Packages -------------- Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name `A.B` designates a submodule named `B` in a package named `A`. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names. Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: `.wav`, `.aiff`, `.au`), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem): ``` sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ... ``` When importing the package, Python searches through the directories on `sys.path` looking for the package subdirectory. The `__init__.py` files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as `string`, unintentionally hiding valid modules that occur later on the module search path. In the simplest case, `__init__.py` can just be an empty file, but it can also execute initialization code for the package or set the `__all__` variable, described later. Users of the package can import individual modules from the package, for example: ``` import sound.effects.echo ``` This loads the submodule `sound.effects.echo`. It must be referenced with its full name. ``` sound.effects.echo.echofilter(input, output, delay=0.7, atten=4) ``` An alternative way of importing the submodule is: ``` from sound.effects import echo ``` This also loads the submodule `echo`, and makes it available without its package prefix, so it can be used as follows: ``` echo.echofilter(input, output, delay=0.7, atten=4) ``` Yet another variation is to import the desired function or variable directly: ``` from sound.effects.echo import echofilter ``` Again, this loads the submodule `echo`, but this makes its function `echofilter()` directly available: ``` echofilter(input, output, delay=0.7, atten=4) ``` Note that when using `from package import item`, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The `import` statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an [`ImportError`](../library/exceptions#ImportError "ImportError") exception is raised. Contrarily, when using syntax like `import item.subitem.subsubitem`, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item. ### 6.4.1. Importing \* From a Package Now what happens when the user writes `from sound.effects import *`? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported. The only solution is for the package author to provide an explicit index of the package. The [`import`](../reference/simple_stmts#import) statement uses the following convention: if a package’s `__init__.py` code defines a list named `__all__`, it is taken to be the list of module names that should be imported when `from package import *` is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing \* from their package. For example, the file `sound/effects/__init__.py` could contain the following code: ``` __all__ = ["echo", "surround", "reverse"] ``` This would mean that `from sound.effects import *` would import the three named submodules of the `sound.effects` package. If `__all__` is not defined, the statement `from sound.effects import *` does *not* import all submodules from the package `sound.effects` into the current namespace; it only ensures that the package `sound.effects` has been imported (possibly running any initialization code in `__init__.py`) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by `__init__.py`. It also includes any submodules of the package that were explicitly loaded by previous [`import`](../reference/simple_stmts#import) statements. Consider this code: ``` import sound.effects.echo import sound.effects.surround from sound.effects import * ``` In this example, the `echo` and `surround` modules are imported in the current namespace because they are defined in the `sound.effects` package when the `from...import` statement is executed. (This also works when `__all__` is defined.) Although certain modules are designed to export only names that follow certain patterns when you use `import *`, it is still considered bad practice in production code. Remember, there is nothing wrong with using `from package import specific_submodule`! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages. ### 6.4.2. Intra-package References When packages are structured into subpackages (as with the `sound` package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module `sound.filters.vocoder` needs to use the `echo` module in the `sound.effects` package, it can use `from sound.effects import echo`. You can also write relative imports, with the `from module import name` form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the `surround` module for example, you might use: ``` from . import echo from .. import formats from ..filters import equalizer ``` Note that relative imports are based on the name of the current module. Since the name of the main module is always `"__main__"`, modules intended for use as the main module of a Python application must always use absolute imports. ### 6.4.3. Packages in Multiple Directories Packages support one more special attribute, [`__path__`](../reference/import#__path__ "__path__"). This is initialized to be a list containing the name of the directory holding the package’s `__init__.py` before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package. While this feature is not often needed, it can be used to extend the set of modules found in a package. #### Footnotes `1` In fact function definitions are also ‘statements’ that are ‘executed’; the execution of a module-level function definition enters the function name in the module’s global symbol table.
programming_docs
python What Now? What Now? ========== Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world problems. Where should you go to learn more? This tutorial is part of Python’s documentation set. Some other documents in the set are: * [The Python Standard Library](../library/index#library-index): You should browse through this manual, which gives complete (though terse) reference material about types, functions, and the modules in the standard library. The standard Python distribution includes a *lot* of additional code. There are modules to read Unix mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, write CGI programs, compress data, and many other tasks. Skimming through the Library Reference will give you an idea of what’s available. * [Installing Python Modules](../installing/index#installing-index) explains how to install additional modules written by other Python users. * [The Python Language Reference](../reference/index#reference-index): A detailed explanation of Python’s syntax and semantics. It’s heavy reading, but is useful as a complete guide to the language itself. More Python resources: * <https://www.python.org>: The major Python Web site. It contains code, documentation, and pointers to Python-related pages around the Web. This Web site is mirrored in various places around the world, such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your geographical location. * <https://docs.python.org>: Fast access to Python’s documentation. * <https://pypi.org>: The Python Package Index, previously also nicknamed the Cheese Shop [1](#id2), is an index of user-created Python modules that are available for download. Once you begin releasing code, you can register it here so that others can find it. * <https://code.activestate.com/recipes/langs/python/>: The Python Cookbook is a sizable collection of code examples, larger modules, and useful scripts. Particularly notable contributions are collected in a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.) * <http://www.pyvideo.org> collects links to Python-related videos from conferences and user-group meetings. * <https://scipy.org>: The Scientific Python project includes modules for fast array computations and manipulations plus a host of packages for such things as linear algebra, Fourier transforms, non-linear solvers, random number distributions, statistical analysis and the like. For Python-related questions and problem reports, you can post to the newsgroup *comp.lang.python*, or send them to the mailing list at [[email protected]](mailto:python-list%40python.org). The newsgroup and mailing list are gatewayed, so messages posted to one will automatically be forwarded to the other. There are hundreds of postings a day, asking (and answering) questions, suggesting new features, and announcing new modules. Mailing list archives are available at <https://mail.python.org/pipermail/>. Before posting, be sure to check the list of [Frequently Asked Questions](../faq/index#faq-index) (also called the FAQ). The FAQ answers many of the questions that come up again and again, and may already contain the solution for your problem. #### Footnotes `1` “Cheese Shop” is a Monty Python’s sketch: a customer enters a cheese shop, but whatever cheese he asks for, the clerk says it’s missing. python Input and Output Input and Output ================= There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. 7.1. Fancier Output Formatting ------------------------------- So far we’ve encountered two ways of writing values: *expression statements* and the [`print()`](../library/functions#print "print") function. (A third way is using the `write()` method of file objects; the standard output file can be referenced as `sys.stdout`. See the Library Reference for more information on this.) Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output. * To use [formatted string literals](#tut-f-strings), begin a string with `f` or `F` before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between `{` and `}` characters that can refer to variables or literal values. ``` >>> year = 2016 >>> event = 'Referendum' >>> f'Results of the {year} {event}' 'Results of the 2016 Referendum' ``` * The [`str.format()`](../library/stdtypes#str.format "str.format") method of strings requires more manual effort. You’ll still use `{` and `}` to mark where a variable will be substituted and can provide detailed formatting directives, but you’ll also need to provide the information to be formatted. ``` >>> yes_votes = 42_572_654 >>> no_votes = 43_132_495 >>> percentage = yes_votes / (yes_votes + no_votes) >>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) ' 42572654 YES votes 49.67%' ``` * Finally, you can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine. The string type has some methods that perform useful operations for padding strings to a given column width. When you don’t need fancy output but just want a quick display of some variables for debugging purposes, you can convert any value to a string with the [`repr()`](../library/functions#repr "repr") or [`str()`](../library/stdtypes#str "str") functions. The [`str()`](../library/stdtypes#str "str") function is meant to return representations of values which are fairly human-readable, while [`repr()`](../library/functions#repr "repr") is meant to generate representations which can be read by the interpreter (or will force a [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError") if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, [`str()`](../library/stdtypes#str "str") will return the same value as [`repr()`](../library/functions#repr "repr"). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings, in particular, have two distinct representations. Some examples: ``` >>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" >>> str(1/7) '0.14285714285714285' >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>> print(s) The value of x is 32.5, and y is 40000... >>> # The repr() of a string adds string quotes and backslashes: ... hello = 'hello, world\n' >>> hellos = repr(hello) >>> print(hellos) 'hello, world\n' >>> # The argument to repr() may be any Python object: ... repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))" ``` The [`string`](../library/string#module-string "string: Common string operations.") module contains a [`Template`](../library/string#string.Template "string.Template") class that offers yet another way to substitute values into strings, using placeholders like `$x` and replacing them with values from a dictionary, but offers much less control of the formatting. ### 7.1.1. Formatted String Literals [Formatted string literals](../reference/lexical_analysis#f-strings) (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with `f` or `F` and writing expressions as `{expression}`. An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal: ``` >>> import math >>> print(f'The value of pi is approximately {math.pi:.3f}.') The value of pi is approximately 3.142. ``` Passing an integer after the `':'` will cause that field to be a minimum number of characters wide. This is useful for making columns line up. ``` >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print(f'{name:10} ==> {phone:10d}') ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678 ``` Other modifiers can be used to convert the value before it is formatted. `'!a'` applies [`ascii()`](../library/functions#ascii "ascii"), `'!s'` applies [`str()`](../library/stdtypes#str "str"), and `'!r'` applies [`repr()`](../library/functions#repr "repr"): ``` >>> animals = 'eels' >>> print(f'My hovercraft is full of {animals}.') My hovercraft is full of eels. >>> print(f'My hovercraft is full of {animals!r}.') My hovercraft is full of 'eels'. ``` For a reference on these format specifications, see the reference guide for the [Format Specification Mini-Language](../library/string#formatspec). ### 7.1.2. The String format() Method Basic usage of the [`str.format()`](../library/stdtypes#str.format "str.format") method looks like this: ``` >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!" ``` The brackets and characters within them (called format fields) are replaced with the objects passed into the [`str.format()`](../library/stdtypes#str.format "str.format") method. A number in the brackets can be used to refer to the position of the object passed into the [`str.format()`](../library/stdtypes#str.format "str.format") method. ``` >>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs >>> print('{1} and {0}'.format('spam', 'eggs')) eggs and spam ``` If keyword arguments are used in the [`str.format()`](../library/stdtypes#str.format "str.format") method, their values are referred to by using the name of the argument. ``` >>> print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) This spam is absolutely horrible. ``` Positional and keyword arguments can be arbitrarily combined: ``` >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')) The story of Bill, Manfred, and Georg. ``` If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets `'[]'` to access the keys. ``` >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' ... 'Dcab: {0[Dcab]:d}'.format(table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 ``` This could also be done by passing the table as keyword arguments with the ‘\*\*’ notation. ``` >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 ``` This is particularly useful in combination with the built-in function [`vars()`](../library/functions#vars "vars"), which returns a dictionary containing all local variables. As an example, the following lines produce a tidily-aligned set of columns giving integers and their squares and cubes: ``` >>> for x in range(1, 11): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 ``` For a complete overview of string formatting with [`str.format()`](../library/stdtypes#str.format "str.format"), see [Format String Syntax](../library/string#formatstrings). ### 7.1.3. Manual String Formatting Here’s the same table of squares and cubes, formatted manually: ``` >>> for x in range(1, 11): ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') ... # Note use of 'end' on previous line ... print(repr(x*x*x).rjust(4)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 ``` (Note that the one space between each column was added by the way [`print()`](../library/functions#print "print") works: it always adds spaces between its arguments.) The [`str.rjust()`](../library/stdtypes#str.rjust "str.rjust") method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods [`str.ljust()`](../library/stdtypes#str.ljust "str.ljust") and [`str.center()`](../library/stdtypes#str.center "str.center"). These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in `x.ljust(n)[:n]`.) There is another method, [`str.zfill()`](../library/stdtypes#str.zfill "str.zfill"), which pads a numeric string on the left with zeros. It understands about plus and minus signs: ``` >>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> '3.14159265359'.zfill(5) '3.14159265359' ``` ### 7.1.4. Old string formatting The % operator (modulo) can also be used for string formatting. Given `'string' % values`, instances of `%` in `string` are replaced with zero or more elements of `values`. This operation is commonly known as string interpolation. For example: ``` >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. ``` More information can be found in the [printf-style String Formatting](../library/stdtypes#old-string-formatting) section. 7.2. Reading and Writing Files ------------------------------- [`open()`](../library/functions#open "open") returns a [file object](../glossary#term-file-object), and is most commonly used with two positional arguments and one keyword argument: `open(filename, mode, encoding=None)` ``` >>> f = open('workfile', 'w', encoding="utf-8") ``` The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. *mode* can be `'r'` when the file will only be read, `'w'` for only writing (an existing file with the same name will be erased), and `'a'` opens the file for appending; any data written to the file is automatically added to the end. `'r+'` opens the file for both reading and writing. The *mode* argument is optional; `'r'` will be assumed if it’s omitted. Normally, files are opened in *text mode*, that means, you read and write strings from and to the file, which are encoded in a specific *encoding*. If *encoding* is not specified, the default is platform dependent (see [`open()`](../library/functions#open "open")). Because UTF-8 is the modern de-facto standard, `encoding="utf-8"` is recommended unless you know that you need to use a different encoding. Appending a `'b'` to the mode opens the file in *binary mode*. Binary mode data is read and written as [`bytes`](../library/stdtypes#bytes "bytes") objects. You can not specify *encoding* when opening file in binary mode. In text mode, the default when reading is to convert platform-specific line endings (`\n` on Unix, `\r\n` on Windows) to just `\n`. When writing in text mode, the default is to convert occurrences of `\n` back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in `JPEG` or `EXE` files. Be very careful to use binary mode when reading and writing such files. It is good practice to use the [`with`](../reference/compound_stmts#with) keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using `with` is also much shorter than writing equivalent [`try`](../reference/compound_stmts#try)-[`finally`](../reference/compound_stmts#finally) blocks: ``` >>> with open('workfile', encoding="utf-8") as f: ... read_data = f.read() >>> # We can check that the file has been automatically closed. >>> f.closed True ``` If you’re not using the [`with`](../reference/compound_stmts#with) keyword, then you should call `f.close()` to close the file and immediately free up any system resources used by it. Warning Calling `f.write()` without using the `with` keyword or calling `f.close()` **might** result in the arguments of `f.write()` not being completely written to the disk, even if the program exits successfully. After a file object is closed, either by a [`with`](../reference/compound_stmts#with) statement or by calling `f.close()`, attempts to use the file object will automatically fail. ``` >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file. ``` ### 7.2.1. Methods of File Objects The rest of the examples in this section will assume that a file object called `f` has already been created. To read a file’s contents, call `f.read(size)`, which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). *size* is an optional numeric argument. When *size* is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most *size* characters (in text mode) or *size* bytes (in binary mode) are read and returned. If the end of the file has been reached, `f.read()` will return an empty string (`''`). ``` >>> f.read() 'This is the entire file.\n' >>> f.read() '' ``` `f.readline()` reads a single line from the file; a newline character (`\n`) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if `f.readline()` returns an empty string, the end of the file has been reached, while a blank line is represented by `'\n'`, a string containing only a single newline. ``` >>> f.readline() 'This is the first line of the file.\n' >>> f.readline() 'Second line of the file\n' >>> f.readline() '' ``` For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: ``` >>> for line in f: ... print(line, end='') ... This is the first line of the file. Second line of the file ``` If you want to read all the lines of a file in a list you can also use `list(f)` or `f.readlines()`. `f.write(string)` writes the contents of *string* to the file, returning the number of characters written. ``` >>> f.write('This is a test\n') 15 ``` Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them: ``` >>> value = ('the answer', 42) >>> s = str(value) # convert the tuple to string >>> f.write(s) 18 ``` `f.tell()` returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode. To change the file object’s position, use `f.seek(offset, whence)`. The position is computed from adding *offset* to a reference point; the reference point is selected by the *whence* argument. A *whence* value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. *whence* can be omitted and defaults to 0, using the beginning of the file as the reference point. ``` >>> f = open('workfile', 'rb+') >>> f.write(b'0123456789abcdef') 16 >>> f.seek(5) # Go to the 6th byte in the file 5 >>> f.read(1) b'5' >>> f.seek(-3, 2) # Go to the 3rd byte before the end 13 >>> f.read(1) b'd' ``` In text files (those opened without a `b` in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with `seek(0, 2)`) and the only valid *offset* values are those returned from the `f.tell()`, or zero. Any other *offset* value produces undefined behaviour. File objects have some additional methods, such as `isatty()` and `truncate()` which are less frequently used; consult the Library Reference for a complete guide to file objects. ### 7.2.2. Saving structured data with [`json`](../library/json#module-json "json: Encode and decode the JSON format.") Strings can easily be written to and read from a file. Numbers take a bit more effort, since the `read()` method only returns strings, which will have to be passed to a function like [`int()`](../library/functions#int "int"), which takes a string like `'123'` and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated. Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called [JSON (JavaScript Object Notation)](http://json.org). The standard module called [`json`](../library/json#module-json "json: Encode and decode the JSON format.") can take Python data hierarchies, and convert them to string representations; this process is called *serializing*. Reconstructing the data from the string representation is called *deserializing*. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine. Note The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability. If you have an object `x`, you can view its JSON string representation with a simple line of code: ``` >>> import json >>> x = [1, 'simple', 'list'] >>> json.dumps(x) '[1, "simple", "list"]' ``` Another variant of the [`dumps()`](../library/json#json.dumps "json.dumps") function, called [`dump()`](../library/json#json.dump "json.dump"), simply serializes the object to a [text file](../glossary#term-text-file). So if `f` is a [text file](../glossary#term-text-file) object opened for writing, we can do this: ``` json.dump(x, f) ``` To decode the object again, if `f` is a [binary file](../glossary#term-binary-file) or [text file](../glossary#term-text-file) object which has been opened for reading: ``` x = json.load(f) ``` Note JSON files must be encoded in UTF-8. Use `encoding="utf-8"` when opening JSON file as a [text file](../glossary#term-text-file) for both of reading and writing. This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the [`json`](../library/json#module-json "json: Encode and decode the JSON format.") module contains an explanation of this. See also [`pickle`](../library/pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") - the pickle module Contrary to [JSON](#tut-json), *pickle* is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.
programming_docs
python Brief Tour of the Standard Library — Part II Brief Tour of the Standard Library — Part II ============================================= This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. 11.1. Output Formatting ------------------------ The [`reprlib`](../library/reprlib#module-reprlib "reprlib: Alternate repr() implementation with size limits.") module provides a version of [`repr()`](../library/functions#repr "repr") customized for abbreviated displays of large or deeply nested containers: ``` >>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "{'a', 'c', 'd', 'e', 'f', 'g', ...}" ``` The [`pprint`](../library/pprint#module-pprint "pprint: Data pretty printer.") module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. When the result is longer than one line, the “pretty printer” adds line breaks and indentation to more clearly reveal data structure: ``` >>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ... 'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]] ``` The [`textwrap`](../library/textwrap#module-textwrap "textwrap: Text wrapping and filling") module formats paragraphs of text to fit a given screen width: ``` >>> import textwrap >>> doc = """The wrap() method is just like fill() except that it returns ... a list of strings instead of one big string with newlines to separate ... the wrapped lines.""" ... >>> print(textwrap.fill(doc, width=40)) The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines. ``` The [`locale`](../library/locale#module-locale "locale: Internationalization services.") module accesses a database of culture specific data formats. The grouping attribute of locale’s format function provides a direct way of formatting numbers with group separators: ``` >>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> conv = locale.localeconv() # get a mapping of conventions >>> x = 1234567.8 >>> locale.format("%d", x, grouping=True) '1,234,567' >>> locale.format_string("%s%.*f", (conv['currency_symbol'], ... conv['frac_digits'], x), grouping=True) '$1,234,567.80' ``` 11.2. Templating ----------------- The [`string`](../library/string#module-string "string: Common string operations.") module includes a versatile [`Template`](../library/string#string.Template "string.Template") class with a simplified syntax suitable for editing by end-users. This allows users to customize their applications without having to alter the application. The format uses placeholder names formed by `$` with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing `$$` creates a single escaped `$`: ``` >>> from string import Template >>> t = Template('${village}folk send $$10 to $cause.') >>> t.substitute(village='Nottingham', cause='the ditch fund') 'Nottinghamfolk send $10 to the ditch fund.' ``` The [`substitute()`](../library/string#string.Template.substitute "string.Template.substitute") method raises a [`KeyError`](../library/exceptions#KeyError "KeyError") when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user supplied data may be incomplete and the [`safe_substitute()`](../library/string#string.Template.safe_substitute "string.Template.safe_substitute") method may be more appropriate — it will leave placeholders unchanged if data is missing: ``` >>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') >>> t.substitute(d) Traceback (most recent call last): ... KeyError: 'owner' >>> t.safe_substitute(d) 'Return the unladen swallow to $owner.' ``` Template subclasses can specify a custom delimiter. For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format: ``` >>> import time, os.path >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] >>> class BatchRename(Template): ... delimiter = '%' >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt) >>> date = time.strftime('%d%b%y') >>> for i, filename in enumerate(photofiles): ... base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) ... print('{0} --> {1}'.format(filename, newname)) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg img_1077.jpg --> Ashley_2.jpg ``` Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports. 11.3. Working with Binary Data Record Layouts ---------------------------------------------- The [`struct`](../library/struct#module-struct "struct: Interpret bytes as packed binary data.") module provides [`pack()`](../library/struct#struct.pack "struct.pack") and [`unpack()`](../library/struct#struct.unpack "struct.unpack") functions for working with variable length binary record formats. The following example shows how to loop through header information in a ZIP file without using the [`zipfile`](../library/zipfile#module-zipfile "zipfile: Read and write ZIP-format archive files.") module. Pack codes `"H"` and `"I"` represent two and four byte unsigned numbers respectively. The `"<"` indicates that they are standard size and in little-endian byte order: ``` import struct with open('myfile.zip', 'rb') as f: data = f.read() start = 0 for i in range(3): # show the first 3 file headers start += 14 fields = struct.unpack('<IIIHH', data[start:start+16]) crc32, comp_size, uncomp_size, filenamesize, extra_size = fields start += 16 filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] print(filename, hex(crc32), comp_size, uncomp_size) start += extra_size + comp_size # skip to the next header ``` 11.4. Multi-threading ---------------------- Threading is a technique for decoupling tasks which are not sequentially dependent. Threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background. A related use case is running I/O in parallel with computations in another thread. The following code shows how the high level [`threading`](../library/threading#module-threading "threading: Thread-based parallelism.") module can run tasks in background while the main program continues to run: ``` import threading, zipfile class AsyncZip(threading.Thread): def __init__(self, infile, outfile): threading.Thread.__init__(self) self.infile = infile self.outfile = outfile def run(self): f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() print('Finished background zip of:', self.infile) background = AsyncZip('mydata.txt', 'myarchive.zip') background.start() print('The main program continues to run in foreground.') background.join() # Wait for the background task to finish print('Main program waited until background was done.') ``` The principal challenge of multi-threaded applications is coordinating threads that share data or other resources. To that end, the threading module provides a number of synchronization primitives including locks, events, condition variables, and semaphores. While those tools are powerful, minor design errors can result in problems that are difficult to reproduce. So, the preferred approach to task coordination is to concentrate all access to a resource in a single thread and then use the [`queue`](../library/queue#module-queue "queue: A synchronized queue class.") module to feed that thread with requests from other threads. Applications using [`Queue`](../library/queue#queue.Queue "queue.Queue") objects for inter-thread communication and coordination are easier to design, more readable, and more reliable. 11.5. Logging -------------- The [`logging`](../library/logging#module-logging "logging: Flexible event logging system for applications.") module offers a full featured and flexible logging system. At its simplest, log messages are sent to a file or to `sys.stderr`: ``` import logging logging.debug('Debugging information') logging.info('Informational message') logging.warning('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') ``` This produces the following output: ``` WARNING:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down ``` By default, informational and debugging messages are suppressed and the output is sent to standard error. Other output options include routing messages through email, datagrams, sockets, or to an HTTP Server. New filters can select different routing based on message priority: `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`. The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the application. 11.6. Weak References ---------------------- Python does automatic memory management (reference counting for most objects and [garbage collection](../glossary#term-garbage-collection) to eliminate cycles). The memory is freed shortly after the last reference to it has been eliminated. This approach works fine for most applications but occasionally there is a need to track objects only as long as they are being used by something else. Unfortunately, just tracking them creates a reference that makes them permanent. The [`weakref`](../library/weakref#module-weakref "weakref: Support for weak references and weak dictionaries.") module provides tools for tracking objects without creating a reference. When the object is no longer needed, it is automatically removed from a weakref table and a callback is triggered for weakref objects. Typical applications include caching objects that are expensive to create: ``` >>> import weakref, gc >>> class A: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ... return str(self.value) ... >>> a = A(10) # create a reference >>> d = weakref.WeakValueDictionary() >>> d['primary'] = a # does not create a reference >>> d['primary'] # fetch the object if it is still alive 10 >>> del a # remove the one reference >>> gc.collect() # run garbage collection right away 0 >>> d['primary'] # entry was automatically removed Traceback (most recent call last): File "<stdin>", line 1, in <module> d['primary'] # entry was automatically removed File "C:/python39/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' ``` 11.7. Tools for Working with Lists ----------------------------------- Many data structure needs can be met with the built-in list type. However, sometimes there is a need for alternative implementations with different performance trade-offs. The [`array`](../library/array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module provides an [`array()`](../library/array#array.array "array.array") object that is like a list that stores only homogeneous data and stores it more compactly. The following example shows an array of numbers stored as two byte unsigned binary numbers (typecode `"H"`) rather than the usual 16 bytes per entry for regular lists of Python int objects: ``` >>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700]) ``` The [`collections`](../library/collections#module-collections "collections: Container datatypes") module provides a [`deque()`](../library/collections#collections.deque "collections.deque") object that is like a list with faster appends and pops from the left side but slower lookups in the middle. These objects are well suited for implementing queues and breadth first tree searches: ``` >>> from collections import deque >>> d = deque(["task1", "task2", "task3"]) >>> d.append("task4") >>> print("Handling", d.popleft()) Handling task1 ``` ``` unsearched = deque([starting_node]) def breadth_first_search(unsearched): node = unsearched.popleft() for m in gen_moves(node): if is_goal(m): return m unsearched.append(m) ``` In addition to alternative list implementations, the library also offers other tools such as the [`bisect`](../library/bisect#module-bisect "bisect: Array bisection algorithms for binary searching.") module with functions for manipulating sorted lists: ``` >>> import bisect >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] >>> bisect.insort(scores, (300, 'ruby')) >>> scores [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')] ``` The [`heapq`](../library/heapq#module-heapq "heapq: Heap queue algorithm (a.k.a. priority queue).") module provides functions for implementing heaps based on regular lists. The lowest valued entry is always kept at position zero. This is useful for applications which repeatedly access the smallest element but do not want to run a full list sort: ``` >>> from heapq import heapify, heappop, heappush >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> heapify(data) # rearrange the list into heap order >>> heappush(data, -5) # add a new entry >>> [heappop(data) for i in range(3)] # fetch the three smallest entries [-5, 0, 1] ``` 11.8. Decimal Floating Point Arithmetic ---------------------------------------- The [`decimal`](../library/decimal#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") module offers a [`Decimal`](../library/decimal#decimal.Decimal "decimal.Decimal") datatype for decimal floating point arithmetic. Compared to the built-in [`float`](../library/functions#float "float") implementation of binary floating point, the class is especially helpful for * financial applications and other uses which require exact decimal representation, * control over precision, * control over rounding to meet legal or regulatory requirements, * tracking of significant decimal places, or * applications where the user expects the results to match calculations done by hand. For example, calculating a 5% tax on a 70 cent phone charge gives different results in decimal floating point and binary floating point. The difference becomes significant if the results are rounded to the nearest cent: ``` >>> from decimal import * >>> round(Decimal('0.70') * Decimal('1.05'), 2) Decimal('0.74') >>> round(.70 * 1.05, 2) 0.73 ``` The [`Decimal`](../library/decimal#decimal.Decimal "decimal.Decimal") result keeps a trailing zero, automatically inferring four place significance from multiplicands with two place significance. Decimal reproduces mathematics as done by hand and avoids issues that can arise when binary floating point cannot exactly represent decimal quantities. Exact representation enables the [`Decimal`](../library/decimal#decimal.Decimal "decimal.Decimal") class to perform modulo calculations and equality tests that are unsuitable for binary floating point: ``` >>> Decimal('1.00') % Decimal('.10') Decimal('0.00') >>> 1.00 % 0.10 0.09999999999999995 >>> sum([Decimal('0.1')]*10) == Decimal('1.0') True >>> sum([0.1]*10) == 1.0 False ``` The [`decimal`](../library/decimal#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") module provides arithmetic with as much precision as needed: ``` >>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal('0.142857142857142857142857142857142857') ``` python Floating Point Arithmetic: Issues and Limitations Floating Point Arithmetic: Issues and Limitations ================================================== Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction ``` 0.125 ``` has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction ``` 0.001 ``` has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2. Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine. The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction: ``` 0.3 ``` or, better, ``` 0.33 ``` or, better, ``` 0.333 ``` and so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3. In the same way, no matter how many base 2 digits you’re willing to use, the decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base 2, 1/10 is the infinitely repeating fraction ``` 0.0001100110011001100110011001100110011001100110011... ``` Stop at any finite number of bits, and you get an approximation. On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two. In the case of 1/10, the binary fraction is `3602879701896397 / 2 ** 55` which is close to but not exactly equal to the true value of 1/10. Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display ``` >>> 0.1 0.1000000000000000055511151231257827021181583404541015625 ``` That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead ``` >>> 1 / 10 0.1 ``` Just remember, even though the printed result looks like the exact value of 1/10, the actual stored value is the nearest representable binary fraction. Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers `0.1` and `0.10000000000000001` and `0.1000000000000000055511151231257827021181583404541015625` are all approximated by `3602879701896397 / 2 ** 55`. Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant `eval(repr(x)) == x`. Historically, the Python prompt and built-in [`repr()`](../library/functions#repr "repr") function would choose the one with 17 significant digits, `0.10000000000000001`. Starting with Python 3.1, Python (on most systems) is now able to choose the shortest of these and simply display `0.1`. Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not *display* the difference by default, or in all output modes). For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits: ``` >>> format(math.pi, '.12g') # give 12 significant digits '3.14159265359' >>> format(math.pi, '.2f') # give 2 digits after the point '3.14' >>> repr(math.pi) '3.141592653589793' ``` It’s important to realize that this is, in a real sense, an illusion: you’re simply rounding the *display* of the true machine value. One illusion may beget another. For example, since 0.1 is not exactly 1/10, summing three values of 0.1 may not yield exactly 0.3, either: ``` >>> .1 + .1 + .1 == .3 False ``` Also, since the 0.1 cannot get any closer to the exact value of 1/10 and 0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with [`round()`](../library/functions#round "round") function cannot help: ``` >>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1) False ``` Though the numbers cannot be made closer to their intended exact values, the [`round()`](../library/functions#round "round") function can be useful for post-rounding so that results with inexact values become comparable to one another: ``` >>> round(.1 + .1 + .1, 10) == round(.3, 10) True ``` Binary floating-point arithmetic holds many surprises like this. The problem with “0.1” is explained in precise detail below, in the “Representation Error” section. See [The Perils of Floating Point](https://www.lahey.com/float.htm) for a more complete account of other common surprises. As that says near the end, “there are no easy answers.” Still, don’t be unduly wary of floating-point! The errors in Python float operations are inherited from the floating-point hardware, and on most machines are on the order of no more than 1 part in 2\*\*53 per operation. That’s more than adequate for most tasks, but you do need to keep in mind that it’s not decimal arithmetic and that every float operation can suffer a new rounding error. While pathological cases do exist, for most casual use of floating-point arithmetic you’ll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. [`str()`](../library/stdtypes#str "str") usually suffices, and for finer control see the [`str.format()`](../library/stdtypes#str.format "str.format") method’s format specifiers in [Format String Syntax](../library/string#formatstrings). For use cases which require exact decimal representation, try using the [`decimal`](../library/decimal#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") module which implements decimal arithmetic suitable for accounting applications and high-precision applications. Another form of exact arithmetic is supported by the [`fractions`](../library/fractions#module-fractions "fractions: Rational numbers.") module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly). If you are a heavy user of floating point operations you should take a look at the NumPy package and many other packages for mathematical and statistical operations supplied by the SciPy project. See <<https://scipy.org>>. Python provides tools that may help on those rare occasions when you really *do* want to know the exact value of a float. The [`float.as_integer_ratio()`](../library/stdtypes#float.as_integer_ratio "float.as_integer_ratio") method expresses the value of a float as a fraction: ``` >>> x = 3.14159 >>> x.as_integer_ratio() (3537115888337719, 1125899906842624) ``` Since the ratio is exact, it can be used to losslessly recreate the original value: ``` >>> x == 3537115888337719 / 1125899906842624 True ``` The [`float.hex()`](../library/stdtypes#float.hex "float.hex") method expresses a float in hexadecimal (base 16), again giving the exact value stored by your computer: ``` >>> x.hex() '0x1.921f9f01b866ep+1' ``` This precise hexadecimal representation can be used to reconstruct the float value exactly: ``` >>> x == float.fromhex('0x1.921f9f01b866ep+1') True ``` Since the representation is exact, it is useful for reliably porting values across different versions of Python (platform independence) and exchanging data with other languages that support the same format (such as Java and C99). Another helpful tool is the [`math.fsum()`](../library/math#math.fsum "math.fsum") function which helps mitigate loss-of-precision during summation. It tracks “lost digits” as values are added onto a running total. That can make a difference in overall accuracy so that the errors do not accumulate to the point where they affect the final total: ``` >>> sum([0.1] * 10) == 1.0 False >>> math.fsum([0.1] * 10) == 1.0 True ``` 15.1. Representation Error --------------------------- This section explains the “0.1” example in detail, and shows how you can perform an exact analysis of cases like this yourself. Basic familiarity with binary floating-point representation is assumed. *Representation error* refers to the fact that some (most, actually) decimal fractions cannot be represented exactly as binary (base 2) fractions. This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many others) often won’t display the exact decimal number you expect. Why is that? 1/10 is not exactly representable as a binary fraction. Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”. 754 doubles contain 53 bits of precision, so on input the computer strives to convert 0.1 to the closest fraction it can of the form *J*/2\*\**N* where *J* is an integer containing exactly 53 bits. Rewriting ``` 1 / 10 ~= J / (2**N) ``` as ``` J ~= 2**N / 10 ``` and recalling that *J* has exactly 53 bits (is `>= 2**52` but `< 2**53`), the best value for *N* is 56: ``` >>> 2**52 <= 2**56 // 10 < 2**53 True ``` That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits. The best possible value for *J* is then that quotient rounded: ``` >>> q, r = divmod(2**56, 10) >>> r 6 ``` Since the remainder is more than half of 10, the best approximation is obtained by rounding up: ``` >>> q+1 7205759403792794 ``` Therefore the best possible approximation to 1/10 in 754 double precision is: ``` 7205759403792794 / 2 ** 56 ``` Dividing both the numerator and denominator by two reduces the fraction to: ``` 3602879701896397 / 2 ** 55 ``` Note that since we rounded up, this is actually a little bit larger than 1/10; if we had not rounded up, the quotient would have been a little bit smaller than 1/10. But in no case can it be *exactly* 1/10! So the computer never “sees” 1/10: what it sees is the exact fraction given above, the best 754 double approximation it can get: ``` >>> 0.1 * 2 ** 55 3602879701896397.0 ``` If we multiply that fraction by 10\*\*55, we can see the value out to 55 decimal digits: ``` >>> 3602879701896397 * 10 ** 55 // 2 ** 55 1000000000000000055511151231257827021181583404541015625 ``` meaning that the exact number stored in the computer is equal to the decimal value 0.1000000000000000055511151231257827021181583404541015625. Instead of displaying the full decimal value, many languages (including older versions of Python), round the result to 17 significant digits: ``` >>> format(0.1, '.17f') '0.10000000000000001' ``` The [`fractions`](../library/fractions#module-fractions "fractions: Rational numbers.") and [`decimal`](../library/decimal#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") modules make these calculations easy: ``` >>> from decimal import Decimal >>> from fractions import Fraction >>> Fraction.from_float(0.1) Fraction(3602879701896397, 36028797018963968) >>> (0.1).as_integer_ratio() (3602879701896397, 36028797018963968) >>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> format(Decimal.from_float(0.1), '.17') '0.10000000000000001' ```
programming_docs
python Using the Python Interpreter Using the Python Interpreter ============================= 2.1. Invoking the Interpreter ------------------------------ The Python interpreter is usually installed as `/usr/local/bin/python3.9` on those machines where it is available; putting `/usr/local/bin` in your Unix shell’s search path makes it possible to start it by typing the command: ``` python3.9 ``` to the shell. [1](#id2) Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., `/usr/local/python` is a popular alternative location.) On Windows machines where you have installed Python from the [Microsoft Store](../using/windows#windows-store), the `python3.9` command will be available. If you have the [py.exe launcher](../using/windows#launcher) installed, you can use the `py` command. See [Excursus: Setting environment variables](../using/windows#setting-envvars) for other ways to launch Python. Typing an end-of-file character (`Control-D` on Unix, `Control-Z` on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command: `quit()`. The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support the [GNU Readline](https://tiswww.case.edu/php/chet/readline/rltop.html) library. Perhaps the quickest check to see whether command line editing is supported is typing `Control-P` to the first Python prompt you get. If it beeps, you have command line editing; see Appendix [Interactive Input Editing and History Substitution](interactive#tut-interacting) for an introduction to the keys. If nothing appears to happen, or if `^P` is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line. The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a *script* from that file. A second way of starting the interpreter is `python -c command [arg] ...`, which executes the statement(s) in *command*, analogous to the shell’s [`-c`](../using/cmdline#cmdoption-c) option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote *command* in its entirety with single quotes. Some Python modules are also useful as scripts. These can be invoked using `python -m module [arg] ...`, which executes the source file for *module* as if you had spelled out its full name on the command line. When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing [`-i`](../using/cmdline#cmdoption-i) before the script. All command line options are described in [Command line and environment](../using/cmdline#using-on-general). ### 2.1.1. Argument Passing When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the `argv` variable in the `sys` module. You can access this list by executing `import sys`. The length of the list is at least one; when no script and no arguments are given, `sys.argv[0]` is an empty string. When the script name is given as `'-'` (meaning standard input), `sys.argv[0]` is set to `'-'`. When [`-c`](../using/cmdline#cmdoption-c) *command* is used, `sys.argv[0]` is set to `'-c'`. When [`-m`](../using/cmdline#cmdoption-m) *module* is used, `sys.argv[0]` is set to the full name of the located module. Options found after [`-c`](../using/cmdline#cmdoption-c) *command* or [`-m`](../using/cmdline#cmdoption-m) *module* are not consumed by the Python interpreter’s option processing but left in `sys.argv` for the command or module to handle. ### 2.1.2. Interactive Mode When commands are read from a tty, the interpreter is said to be in *interactive mode*. In this mode it prompts for the next command with the *primary prompt*, usually three greater-than signs (`>>>`); for continuation lines it prompts with the *secondary prompt*, by default three dots (`...`). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt: ``` $ python3.9 Python 3.9 (default, June 4 2019, 09:25:04) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` Continuation lines are needed when entering a multi-line construct. As an example, take a look at this [`if`](../reference/compound_stmts#if) statement: ``` >>> the_world_is_flat = True >>> if the_world_is_flat: ... print("Be careful not to fall off!") ... Be careful not to fall off! ``` For more on interactive mode, see [Interactive Mode](appendix#tut-interac). 2.2. The Interpreter and Its Environment ----------------------------------------- ### 2.2.1. Source Code Encoding By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file. To declare an encoding other than the default one, a special comment line should be added as the *first* line of the file. The syntax is as follows: ``` # -*- coding: encoding -*- ``` where *encoding* is one of the valid [`codecs`](../library/codecs#module-codecs "codecs: Encode and decode data and streams.") supported by Python. For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be: ``` # -*- coding: cp1252 -*- ``` One exception to the *first line* rule is when the source code starts with a [UNIX “shebang” line](appendix#tut-scripts). In this case, the encoding declaration should be added as the second line of the file. For example: ``` #!/usr/bin/env python3 # -*- coding: cp1252 -*- ``` #### Footnotes `1` On Unix, the Python 3.x interpreter is by default not installed with the executable named `python`, so that it does not conflict with a simultaneously installed Python 2.x executable. python Appendix Appendix ========= 16.1. Interactive Mode ----------------------- ### 16.1.1. Error Handling When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an [`except`](../reference/compound_stmts#except) clause in a [`try`](../reference/compound_stmts#try) statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output. Typing the interrupt character (usually `Control-C` or `Delete`) to the primary or secondary prompt cancels the input and returns to the primary prompt. [1](#id2) Typing an interrupt while a command is executing raises the [`KeyboardInterrupt`](../library/exceptions#KeyboardInterrupt "KeyboardInterrupt") exception, which may be handled by a [`try`](../reference/compound_stmts#try) statement. ### 16.1.2. Executable Python Scripts On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line ``` #!/usr/bin/env python3.5 ``` (assuming that the interpreter is on the user’s `PATH`) at the beginning of the script and giving the file an executable mode. The `#!` must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending (`'\n'`), not a Windows (`'\r\n'`) line ending. Note that the hash, or pound, character, `'#'`, is used to start a comment in Python. The script can be given an executable mode, or permission, using the **chmod** command. ``` $ chmod +x myscript.py ``` On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates `.py` files with `python.exe` so that a double-click on a Python file will run it as a script. The extension can also be `.pyw`, in that case, the console window that normally appears is suppressed. ### 16.1.3. The Interactive Startup File When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named [`PYTHONSTARTUP`](../using/cmdline#envvar-PYTHONSTARTUP) to the name of a file containing your start-up commands. This is similar to the `.profile` feature of the Unix shells. This file is only read in interactive sessions, not when Python reads commands from a script, and not when `/dev/tty` is given as the explicit source of commands (which otherwise behaves like an interactive session). It is executed in the same namespace where interactive commands are executed, so that objects that it defines or imports can be used without qualification in the interactive session. You can also change the prompts `sys.ps1` and `sys.ps2` in this file. If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like `if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())`. If you want to use the startup file in a script, you must do this explicitly in the script: ``` import os filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): with open(filename) as fobj: startup_file = fobj.read() exec(startup_file) ``` ### 16.1.4. The Customization Modules Python provides two hooks to let you customize it: `sitecustomize` and `usercustomize`. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code: ``` >>> import site >>> site.getusersitepackages() '/home/user/.local/lib/python3.5/site-packages' ``` Now you can create a file named `usercustomize.py` in that directory and put anything you want in it. It will affect every invocation of Python, unless it is started with the [`-s`](../using/cmdline#cmdoption-s) option to disable the automatic import. `sitecustomize` works in the same way, but is typically created by an administrator of the computer in the global site-packages directory, and is imported before `usercustomize`. See the documentation of the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module for more details. #### Footnotes `1` A problem with the GNU Readline package may prevent this. python Data Structures Data Structures ================ This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. 5.1. More on Lists ------------------- The list data type has some more methods. Here are all of the methods of list objects: `list.append(x)` Add an item to the end of the list. Equivalent to `a[len(a):] = [x]`. `list.extend(iterable)` Extend the list by appending all the items from the iterable. Equivalent to `a[len(a):] = iterable`. `list.insert(i, x)` Insert an item at a given position. The first argument is the index of the element before which to insert, so `a.insert(0, x)` inserts at the front of the list, and `a.insert(len(a), x)` is equivalent to `a.append(x)`. `list.remove(x)` Remove the first item from the list whose value is equal to *x*. It raises a [`ValueError`](../library/exceptions#ValueError "ValueError") if there is no such item. `list.pop([i])` Remove the item at the given position in the list, and return it. If no index is specified, `a.pop()` removes and returns the last item in the list. (The square brackets around the *i* in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.) `list.clear()` Remove all items from the list. Equivalent to `del a[:]`. `list.index(x[, start[, end]])` Return zero-based index in the list of the first item whose value is equal to *x*. Raises a [`ValueError`](../library/exceptions#ValueError "ValueError") if there is no such item. The optional arguments *start* and *end* are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the *start* argument. `list.count(x)` Return the number of times *x* appears in the list. `list.sort(*, key=None, reverse=False)` Sort the items of the list in place (the arguments can be used for sort customization, see [`sorted()`](../library/functions#sorted "sorted") for their explanation). `list.reverse()` Reverse the elements of the list in place. `list.copy()` Return a shallow copy of the list. Equivalent to `a[:]`. An example that uses most of the list methods: ``` >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> fruits.reverse() >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>> fruits.append('grape') >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>> fruits.sort() >>> fruits ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>> fruits.pop() 'pear' ``` You might have noticed that methods like `insert`, `remove` or `sort` that only modify the list have no return value printed – they return the default `None`. [1](#id2) This is a design principle for all mutable data structures in Python. Another thing you might notice is that not all data can be sorted or compared. For instance, `[None, 'hello', 10]` doesn’t sort because integers can’t be compared to strings and *None* can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, `3+4j < 5+7j` isn’t a valid comparison. ### 5.1.1. Using Lists as Stacks The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use `append()`. To retrieve an item from the top of the stack, use `pop()` without an explicit index. For example: ``` >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] ``` ### 5.1.2. Using Lists as Queues It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one). To implement a queue, use [`collections.deque`](../library/collections#collections.deque "collections.deque") which was designed to have fast appends and pops from both ends. For example: ``` >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham']) ``` ### 5.1.3. List Comprehensions List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. For example, assume we want to create a list of squares, like: ``` >>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ``` Note that this creates (or overwrites) a variable named `x` that still exists after the loop completes. We can calculate the list of squares without any side effects using: ``` squares = list(map(lambda x: x**2, range(10))) ``` or, equivalently: ``` squares = [x**2 for x in range(10)] ``` which is more concise and readable. A list comprehension consists of brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. The result will be a new list resulting from evaluating the expression in the context of the `for` and `if` clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal: ``` >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ``` and it’s equivalent to: ``` >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ``` Note how the order of the [`for`](../reference/compound_stmts#for) and [`if`](../reference/compound_stmts#if) statements is the same in both these snippets. If the expression is a tuple (e.g. the `(x, y)` in the previous example), it must be parenthesized. ``` >>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in <module> [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` List comprehensions can contain complex expressions and nested functions: ``` >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] ``` ### 5.1.4. Nested List Comprehensions The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension. Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4: ``` >>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] ``` The following list comprehension will transpose rows and columns: ``` >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` As we saw in the previous section, the nested listcomp is evaluated in the context of the [`for`](../reference/compound_stmts#for) that follows it, so this example is equivalent to: ``` >>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` which, in turn, is the same as: ``` >>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] ``` In the real world, you should prefer built-in functions to complex flow statements. The [`zip()`](../library/functions#zip "zip") function would do a great job for this use case: ``` >>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] ``` See [Unpacking Argument Lists](controlflow#tut-unpacking-arguments) for details on the asterisk in this line. 5.2. The `del` statement ------------------------- There is a way to remove an item from a list given its index instead of its value: the [`del`](../reference/simple_stmts#del) statement. This differs from the `pop()` method which returns a value. The `del` statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example: ``` >>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a [] ``` [`del`](../reference/simple_stmts#del) can also be used to delete entire variables: ``` >>> del a ``` Referencing the name `a` hereafter is an error (at least until another value is assigned to it). We’ll find other uses for [`del`](../reference/simple_stmts#del) later. 5.3. Tuples and Sequences -------------------------- We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of *sequence* data types (see [Sequence Types — list, tuple, range](../library/stdtypes#typesseq)). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the *tuple*. A tuple consists of a number of values separated by commas, for instance: ``` >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: ... t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: ... v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1]) ``` As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists. Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are [immutable](../glossary#term-immutable), and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of [`namedtuples`](../library/collections#collections.namedtuple "collections.namedtuple")). Lists are [mutable](../glossary#term-mutable), and their elements are usually homogeneous and are accessed by iterating over the list. A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example: ``` >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) ``` The statement `t = 12345, 54321, 'hello!'` is an example of *tuple packing*: the values `12345`, `54321` and `'hello!'` are packed together in a tuple. The reverse operation is also possible: ``` >>> x, y, z = t ``` This is called, appropriately enough, *sequence unpacking* and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking. 5.4. Sets ---------- Python also includes a data type for *sets*. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. Curly braces or the [`set()`](../library/stdtypes#set "set") function can be used to create sets. Note: to create an empty set you have to use `set()`, not `{}`; the latter creates an empty dictionary, a data structure that we discuss in the next section. Here is a brief demonstration: ``` >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} ``` Similarly to [list comprehensions](#tut-listcomps), set comprehensions are also supported: ``` >>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'} ``` 5.5. Dictionaries ------------------ Another useful data type built into Python is the *dictionary* (see [Mapping Types — dict](../library/stdtypes#typesmapping)). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by *keys*, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like `append()` and `extend()`. It is best to think of a dictionary as a set of *key: value* pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: `{}`. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output. The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with `del`. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key. Performing `list(d)` on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use `sorted(d)` instead). To check whether a single key is in the dictionary, use the [`in`](../reference/expressions#in) keyword. Here is a small example using a dictionary: ``` >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'jack': 4098, 'sape': 4139, 'guido': 4127} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'jack': 4098, 'guido': 4127, 'irv': 4127} >>> list(tel) ['jack', 'guido', 'irv'] >>> sorted(tel) ['guido', 'irv', 'jack'] >>> 'guido' in tel True >>> 'jack' not in tel False ``` The [`dict()`](../library/stdtypes#dict "dict") constructor builds dictionaries directly from sequences of key-value pairs: ``` >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'guido': 4127, 'jack': 4098} ``` In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions: ``` >>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} ``` When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments: ``` >>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'guido': 4127, 'jack': 4098} ``` 5.6. Looping Techniques ------------------------ When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the `items()` method. ``` >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave ``` When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the [`enumerate()`](../library/functions#enumerate "enumerate") function. ``` >>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe ``` To loop over two or more sequences at the same time, the entries can be paired with the [`zip()`](../library/functions#zip "zip") function. ``` >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. ``` To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the [`reversed()`](../library/functions#reversed "reversed") function. ``` >>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1 ``` To loop over a sequence in sorted order, use the [`sorted()`](../library/functions#sorted "sorted") function which returns a new sorted list while leaving the source unaltered. ``` >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for i in sorted(basket): ... print(i) ... apple apple banana orange orange pear ``` Using [`set()`](../library/stdtypes#set "set") on a sequence eliminates duplicate elements. The use of [`sorted()`](../library/functions#sorted "sorted") in combination with [`set()`](../library/stdtypes#set "set") over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order. ``` >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear ``` It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead. ``` >>> import math >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] >>> filtered_data = [] >>> for value in raw_data: ... if not math.isnan(value): ... filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8] ``` 5.7. More on Conditions ------------------------ The conditions used in `while` and `if` statements can contain any operators, not just comparisons. The comparison operators `in` and `not in` check whether a value occurs (does not occur) in a sequence. The operators `is` and `is not` compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators. Comparisons can be chained. For example, `a < b == c` tests whether `a` is less than `b` and moreover `b` equals `c`. Comparisons may be combined using the Boolean operators `and` and `or`, and the outcome of a comparison (or of any other Boolean expression) may be negated with `not`. These have lower priorities than comparison operators; between them, `not` has the highest priority and `or` the lowest, so that `A and not B or C` is equivalent to `(A and (not B)) or C`. As always, parentheses can be used to express the desired composition. The Boolean operators `and` and `or` are so-called *short-circuit* operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if `A` and `C` are true but `B` is false, `A and B and C` does not evaluate the expression `C`. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument. It is possible to assign the result of a comparison or other Boolean expression to a variable. For example, ``` >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' ``` Note that in Python, unlike C, assignment inside expressions must be done explicitly with the [walrus operator](../faq/design#why-can-t-i-use-an-assignment-in-an-expression) `:=`. This avoids a common class of problems encountered in C programs: typing `=` in an expression when `==` was intended. 5.8. Comparing Sequences and Other Types ----------------------------------------- Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses *lexicographical* ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type: ``` (1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) ``` Note that comparing objects of different types with `<` or `>` is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a [`TypeError`](../library/exceptions#TypeError "TypeError") exception. #### Footnotes `1` Other languages may return the mutated object, which allows method chaining, such as `d->insert("a")->remove("b")->sort();`.
programming_docs
python More Control Flow Tools More Control Flow Tools ======================== Besides the [`while`](../reference/compound_stmts#while) statement just introduced, Python uses the usual flow control statements known from other languages, with some twists. 4.1. `if` Statements --------------------- Perhaps the most well-known statement type is the [`if`](../reference/compound_stmts#if) statement. For example: ``` >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') ... More ``` There can be zero or more [`elif`](../reference/compound_stmts#elif) parts, and the [`else`](../reference/compound_stmts#else) part is optional. The keyword ‘`elif`’ is short for ‘else if’, and is useful to avoid excessive indentation. An `if` … `elif` … `elif` … sequence is a substitute for the `switch` or `case` statements found in other languages. 4.2. `for` Statements ---------------------- The [`for`](../reference/compound_stmts#for) statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s `for` statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended): ``` >>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12 ``` Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection: ``` # Strategy: Iterate over a copy for user, status in users.copy().items(): if status == 'inactive': del users[user] # Strategy: Create a new collection active_users = {} for user, status in users.items(): if status == 'active': active_users[user] = status ``` 4.3. The range() Function -------------------------- If you do need to iterate over a sequence of numbers, the built-in function [`range()`](../library/stdtypes#range "range") comes in handy. It generates arithmetic progressions: ``` >>> for i in range(5): ... print(i) ... 0 1 2 3 4 ``` The given end point is never part of the generated sequence; `range(10)` generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’): ``` >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] ``` To iterate over the indices of a sequence, you can combine [`range()`](../library/stdtypes#range "range") and [`len()`](../library/functions#len "len") as follows: ``` >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb ``` In most such cases, however, it is convenient to use the [`enumerate()`](../library/functions#enumerate "enumerate") function, see [Looping Techniques](datastructures#tut-loopidioms). A strange thing happens if you just print a range: ``` >>> range(10) range(0, 10) ``` In many ways the object returned by [`range()`](../library/stdtypes#range "range") behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space. We say such an object is [iterable](../glossary#term-iterable), that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the [`for`](../reference/compound_stmts#for) statement is such a construct, while an example of a function that takes an iterable is [`sum()`](../library/functions#sum "sum"): ``` >>> sum(range(4)) # 0 + 1 + 2 + 3 6 ``` Later we will see more functions that return iterables and take iterables as arguments. In chapter [Data Structures](datastructures#tut-structures), we will discuss in more detail about [`list()`](../library/stdtypes#list "list"). 4.4. `break` and `continue` Statements, and `else` Clauses on Loops -------------------------------------------------------------------- The [`break`](../reference/simple_stmts#break) statement, like in C, breaks out of the innermost enclosing [`for`](../reference/compound_stmts#for) or [`while`](../reference/compound_stmts#while) loop. Loop statements may have an `else` clause; it is executed when the loop terminates through exhaustion of the iterable (with [`for`](../reference/compound_stmts#for)) or when the condition becomes false (with [`while`](../reference/compound_stmts#while)), but not when the loop is terminated by a [`break`](../reference/simple_stmts#break) statement. This is exemplified by the following loop, which searches for prime numbers: ``` >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 ``` (Yes, this is the correct code. Look closely: the `else` clause belongs to the [`for`](../reference/compound_stmts#for) loop, **not** the [`if`](../reference/compound_stmts#if) statement.) When used with a loop, the `else` clause has more in common with the `else` clause of a [`try`](../reference/compound_stmts#try) statement than it does with that of [`if`](../reference/compound_stmts#if) statements: a [`try`](../reference/compound_stmts#try) statement’s `else` clause runs when no exception occurs, and a loop’s `else` clause runs when no `break` occurs. For more on the `try` statement and exceptions, see [Handling Exceptions](errors#tut-handling). The [`continue`](../reference/simple_stmts#continue) statement, also borrowed from C, continues with the next iteration of the loop: ``` >>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found an odd number", num) ... Found an even number 2 Found an odd number 3 Found an even number 4 Found an odd number 5 Found an even number 6 Found an odd number 7 Found an even number 8 Found an odd number 9 ``` 4.5. `pass` Statements ----------------------- The [`pass`](../reference/simple_stmts#pass) statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: ``` >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... ``` This is commonly used for creating minimal classes: ``` >>> class MyEmptyClass: ... pass ... ``` Another place [`pass`](../reference/simple_stmts#pass) can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The `pass` is silently ignored: ``` >>> def initlog(*args): ... pass # Remember to implement this! ... ``` 4.6. Defining Functions ------------------------ We can create a function that writes the Fibonacci series to an arbitrary boundary: ``` >>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while a < n: ... print(a, end=' ') ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ``` The keyword [`def`](../reference/compound_stmts#def) introduces a function *definition*. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented. The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or *docstring*. (More about docstrings can be found in the section [Documentation Strings](#tut-docstrings).) There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it’s good practice to include docstrings in code that you write, so make a habit of it. The *execution* of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a [`global`](../reference/simple_stmts#global) statement, or, for variables of enclosing functions, named in a [`nonlocal`](../reference/simple_stmts#nonlocal) statement), although they may be referenced. The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using *call by value* (where the *value* is always an object *reference*, not the value of the object). [1](#id2) When a function calls another function, or calls itself recursively, a new local symbol table is created for that call. A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function: ``` >>> fib <function fib at 10042ed0> >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89 ``` Coming from other languages, you might object that `fib` is not a function but a procedure since it doesn’t return a value. In fact, even functions without a [`return`](../reference/simple_stmts#return) statement do return a value, albeit a rather boring one. This value is called `None` (it’s a built-in name). Writing the value `None` is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to using [`print()`](../library/functions#print "print"): ``` >>> fib(0) >>> print(fib(0)) None ``` It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it: ``` >>> def fib2(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" ... result = [] ... a, b = 0, 1 ... while a < n: ... result.append(a) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ``` This example, as usual, demonstrates some new Python features: * The [`return`](../reference/simple_stmts#return) statement returns with a value from a function. `return` without an expression argument returns `None`. Falling off the end of a function also returns `None`. * The statement `result.append(a)` calls a *method* of the list object `result`. A method is a function that ‘belongs’ to an object and is named `obj.methodname`, where `obj` is some object (this may be an expression), and `methodname` is the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using *classes*, see [Classes](classes#tut-classes)) The method `append()` shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to `result = result + [a]`, but more efficient. 4.7. More on Defining Functions -------------------------------- It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined. ### 4.7.1. Default Argument Values The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example: ``` def ask_ok(prompt, retries=4, reminder='Please try again!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise ValueError('invalid user response') print(reminder) ``` This function can be called in several ways: * giving only the mandatory argument: `ask_ok('Do you really want to quit?')` * giving one of the optional arguments: `ask_ok('OK to overwrite the file?', 2)` * or even giving all arguments: `ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')` This example also introduces the [`in`](../reference/expressions#in) keyword. This tests whether or not a sequence contains a certain value. The default values are evaluated at the point of function definition in the *defining* scope, so that ``` i = 5 def f(arg=i): print(arg) i = 6 f() ``` will print `5`. **Important warning:** The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: ``` def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) ``` This will print ``` [1] [1, 2] [1, 2, 3] ``` If you don’t want the default to be shared between subsequent calls, you can write the function like this instead: ``` def f(a, L=None): if L is None: L = [] L.append(a) return L ``` ### 4.7.2. Keyword Arguments Functions can also be called using [keyword arguments](../glossary#term-keyword-argument) of the form `kwarg=value`. For instance, the following function: ``` def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.") print("-- Lovely plumage, the", type) print("-- It's", state, "!") ``` accepts one required argument (`voltage`) and three optional arguments (`state`, `action`, and `type`). This function can be called in any of the following ways: ``` parrot(1000) # 1 positional argument parrot(voltage=1000) # 1 keyword argument parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword ``` but all the following calls would be invalid: ``` parrot() # required argument missing parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument parrot(110, voltage=220) # duplicate value for the same argument parrot(actor='John Cleese') # unknown keyword argument ``` In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. `actor` is not a valid argument for the `parrot` function), and their order is not important. This also includes non-optional arguments (e.g. `parrot(voltage=1000)` is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction: ``` >>> def function(a): ... pass ... >>> function(0, a=0) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function() got multiple values for argument 'a' ``` When a final formal parameter of the form `**name` is present, it receives a dictionary (see [Mapping Types — dict](../library/stdtypes#typesmapping)) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form `*name` (described in the next subsection) which receives a [tuple](datastructures#tut-tuples) containing the positional arguments beyond the formal parameter list. (`*name` must occur before `**name`.) For example, if we define a function like this: ``` def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw]) ``` It could be called like this: ``` cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch") ``` and of course it would print: ``` -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch ``` Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call. ### 4.7.3. Special parameters By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability and performance, it makes sense to restrict the way arguments can be passed so that a developer need only look at the function definition to determine if items are passed by position, by position or keyword, or by keyword. A function definition may look like: ``` def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): ----------- ---------- ---------- | | | | Positional or keyword | | - Keyword only -- Positional only ``` where `/` and `*` are optional. If used, these symbols indicate the kind of parameter by how the arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-only. Keyword parameters are also referred to as named parameters. #### 4.7.3.1. Positional-or-Keyword Arguments If `/` and `*` are not present in the function definition, arguments may be passed to a function by position or by keyword. #### 4.7.3.2. Positional-Only Parameters Looking at this in a bit more detail, it is possible to mark certain parameters as *positional-only*. If *positional-only*, the parameters’ order matters, and the parameters cannot be passed by keyword. Positional-only parameters are placed before a `/` (forward-slash). The `/` is used to logically separate the positional-only parameters from the rest of the parameters. If there is no `/` in the function definition, there are no positional-only parameters. Parameters following the `/` may be *positional-or-keyword* or *keyword-only*. #### 4.7.3.3. Keyword-Only Arguments To mark parameters as *keyword-only*, indicating the parameters must be passed by keyword argument, place an `*` in the arguments list just before the first *keyword-only* parameter. #### 4.7.3.4. Function Examples Consider the following example function definitions paying close attention to the markers `/` and `*`: ``` >>> def standard_arg(arg): ... print(arg) ... >>> def pos_only_arg(arg, /): ... print(arg) ... >>> def kwd_only_arg(*, arg): ... print(arg) ... >>> def combined_example(pos_only, /, standard, *, kwd_only): ... print(pos_only, standard, kwd_only) ``` The first function definition, `standard_arg`, the most familiar form, places no restrictions on the calling convention and arguments may be passed by position or keyword: ``` >>> standard_arg(2) 2 >>> standard_arg(arg=2) 2 ``` The second function `pos_only_arg` is restricted to only use positional parameters as there is a `/` in the function definition: ``` >>> pos_only_arg(1) 1 >>> pos_only_arg(arg=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg' ``` The third function `kwd_only_args` only allows keyword arguments as indicated by a `*` in the function definition: ``` >>> kwd_only_arg(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given >>> kwd_only_arg(arg=3) 3 ``` And the last uses all three calling conventions in the same function definition: ``` >>> combined_example(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: combined_example() takes 2 positional arguments but 3 were given >>> combined_example(1, 2, kwd_only=3) 1 2 3 >>> combined_example(1, standard=2, kwd_only=3) 1 2 3 >>> combined_example(pos_only=1, standard=2, kwd_only=3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only' ``` Finally, consider this function definition which has a potential collision between the positional argument `name` and `**kwds` which has `name` as a key: ``` def foo(name, **kwds): return 'name' in kwds ``` There is no possible call that will make it return `True` as the keyword `'name'` will always bind to the first parameter. For example: ``` >>> foo(1, **{'name': 2}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() got multiple values for argument 'name' >>> ``` But using `/` (positional only arguments), it is possible since it allows `name` as a positional argument and `'name'` as a key in the keyword arguments: ``` def foo(name, /, **kwds): return 'name' in kwds >>> foo(1, **{'name': 2}) True ``` In other words, the names of positional-only parameters can be used in `**kwds` without ambiguity. #### 4.7.3.5. Recap The use case will determine which parameters to use in the function definition: ``` def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): ``` As guidance: * Use positional-only if you want the name of the parameters to not be available to the user. This is useful when parameter names have no real meaning, if you want to enforce the order of the arguments when the function is called or if you need to take some positional parameters and arbitrary keywords. * Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names or you want to prevent users relying on the position of the argument being passed. * For an API, use positional-only to prevent breaking API changes if the parameter’s name is modified in the future. ### 4.7.4. Arbitrary Argument Lists Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see [Tuples and Sequences](datastructures#tut-tuples)). Before the variable number of arguments, zero or more normal arguments may occur. ``` def write_multiple_items(file, separator, *args): file.write(separator.join(args)) ``` Normally, these *variadic* arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the `*args` parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments. ``` >>> def concat(*args, sep="/"): ... return sep.join(args) ... >>> concat("earth", "mars", "venus") 'earth/mars/venus' >>> concat("earth", "mars", "venus", sep=".") 'earth.mars.venus' ``` ### 4.7.5. Unpacking Argument Lists The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in [`range()`](../library/stdtypes#range "range") function expects separate *start* and *stop* arguments. If they are not available separately, write the function call with the `*`-operator to unpack the arguments out of a list or tuple: ``` >>> list(range(3, 6)) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] ``` In the same fashion, dictionaries can deliver keyword arguments with the `**`-operator: ``` >>> def parrot(voltage, state='a stiff', action='voom'): ... print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!") ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! ``` ### 4.7.6. Lambda Expressions Small anonymous functions can be created with the [`lambda`](../reference/expressions#lambda) keyword. This function returns the sum of its two arguments: `lambda a, b: a+b`. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope: ``` >>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43 ``` The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument: ``` >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] ``` ### 4.7.7. Documentation Strings Here are some conventions about the content and formatting of documentation strings. The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc. The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line *after* the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally). Here is an example of a multi-line docstring: ``` >>> def my_function(): ... """Do nothing, but document it. ... ... No, really, it doesn't do anything. ... """ ... pass ... >>> print(my_function.__doc__) Do nothing, but document it. No, really, it doesn't do anything. ``` ### 4.7.8. Function Annotations [Function annotations](../reference/compound_stmts#function) are completely optional metadata information about the types used by user-defined functions (see [**PEP 3107**](https://www.python.org/dev/peps/pep-3107) and [**PEP 484**](https://www.python.org/dev/peps/pep-0484) for more information). [Annotations](../glossary#term-function-annotation) are stored in the `__annotations__` attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal `->`, followed by an expression, between the parameter list and the colon denoting the end of the [`def`](../reference/compound_stmts#def) statement. The following example has a required argument, an optional argument, and the return value annotated: ``` >>> def f(ham: str, eggs: str = 'eggs') -> str: ... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs) ... return ham + ' and ' + eggs ... >>> f('spam') Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} Arguments: spam eggs 'spam and eggs' ``` 4.8. Intermezzo: Coding Style ------------------------------ Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about *coding style*. Most languages can be written (or more concise, *formatted*) in different styles; some are more readable than others. Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that. For Python, [**PEP 8**](https://www.python.org/dev/peps/pep-0008) has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you: * Use 4-space indentation, and no tabs. 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out. * Wrap lines so that they don’t exceed 79 characters. This helps users with small displays and makes it possible to have several code files side-by-side on larger displays. * Use blank lines to separate functions and classes, and larger blocks of code inside functions. * When possible, put comments on a line of their own. * Use docstrings. * Use spaces around operators and after commas, but not directly inside bracketing constructs: `a = f(1, 2) + g(3, 4)`. * Name your classes and functions consistently; the convention is to use `UpperCamelCase` for classes and `lowercase_with_underscores` for functions and methods. Always use `self` as the name for the first method argument (see [A First Look at Classes](classes#tut-firstclasses) for more on classes and methods). * Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case. * Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code. #### Footnotes `1` Actually, *call by object reference* would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).
programming_docs
python Classes Classes ======== Classes provide a means of bundling data and functionality together. Creating a new class creates a new *type* of object, allowing new *instances* of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state. Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation. In C++ terminology, normally class members (including the data members) are *public* (except see below [Private Variables](#tut-private)), and all member functions are *virtual*. As in Modula-3, there are no shorthands for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call. As in Smalltalk, classes themselves are objects. This provides semantics for importing and renaming. Unlike C++ and Modula-3, built-in types can be used as base classes for extension by the user. Also, like in C++, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances. (Lacking universally accepted terminology to talk about classes, I will make occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since its object-oriented semantics are closer to those of Python than C++, but I expect that few readers have heard of it.) 9.1. A Word About Names and Objects ------------------------------------ Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has a possibly surprising effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most other types. This is usually used to the benefit of the program, since aliases behave like pointers in some respects. For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mechanisms as in Pascal. 9.2. Python Scopes and Namespaces ---------------------------------- Before introducing classes, I first have to tell you something about Python’s scope rules. Class definitions play some neat tricks with namespaces, and you need to know how scopes and namespaces work to fully understand what’s going on. Incidentally, knowledge about this subject is useful for any advanced Python programmer. Let’s begin with some definitions. A *namespace* is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (containing functions such as [`abs()`](../library/functions#abs "abs"), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function `maximize` without confusion — users of the modules must prefix it with the module name. By the way, I use the word *attribute* for any name following a dot — for example, in the expression `z.real`, `real` is an attribute of the object `z`. Strictly speaking, references to names in modules are attribute references: in the expression `modname.funcname`, `modname` is a module object and `funcname` is an attribute of it. In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace! [1](#id2) Attributes may be read-only or writable. In the latter case, assignment to attributes is possible. Module attributes are writable: you can write `modname.the_answer = 42`. Writable attributes may also be deleted with the [`del`](../reference/simple_stmts#del) statement. For example, `del modname.the_answer` will remove the attribute `the_answer` from the object named by `modname`. Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run."), so they have their own global namespace. (The built-in names actually also live in a module; this is called [`builtins`](../library/builtins#module-builtins "builtins: The module that provides the built-in namespace.").) The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace. A *scope* is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace. Although scopes are determined statically, they are used dynamically. At any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible: * the innermost scope, which is searched first, contains the local names * the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names * the next-to-last scope contains the current module’s global names * the outermost scope (searched last) is the namespace containing built-in names If a name is declared global, then all references and assignments go directly to the middle scope containing the module’s global names. To rebind variables found outside of the innermost scope, the [`nonlocal`](../reference/simple_stmts#nonlocal) statement can be used; if not declared nonlocal, those variables are read-only (an attempt to write to such a variable will simply create a *new* local variable in the innermost scope, leaving the identically named outer variable unchanged). Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. Class definitions place yet another namespace in the local scope. It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.) A special quirk of Python is that – if no [`global`](../reference/simple_stmts#global) or [`nonlocal`](../reference/simple_stmts#nonlocal) statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement `del x` removes the binding of `x` from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, [`import`](../reference/simple_stmts#import) statements and function definitions bind the module or function name in the local scope. The [`global`](../reference/simple_stmts#global) statement can be used to indicate that particular variables live in the global scope and should be rebound there; the [`nonlocal`](../reference/simple_stmts#nonlocal) statement indicates that particular variables live in an enclosing scope and should be rebound there. ### 9.2.1. Scopes and Namespaces Example This is an example demonstrating how to reference the different scopes and namespaces, and how [`global`](../reference/simple_stmts#global) and [`nonlocal`](../reference/simple_stmts#nonlocal) affect variable binding: ``` def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) ``` The output of the example code is: ``` After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam ``` Note how the *local* assignment (which is default) didn’t change *scope\_test*’s binding of *spam*. The [`nonlocal`](../reference/simple_stmts#nonlocal) assignment changed *scope\_test*’s binding of *spam*, and the [`global`](../reference/simple_stmts#global) assignment changed the module-level binding. You can also see that there was no previous binding for *spam* before the [`global`](../reference/simple_stmts#global) assignment. 9.3. A First Look at Classes ----------------------------- Classes introduce a little bit of new syntax, three new object types, and some new semantics. ### 9.3.1. Class Definition Syntax The simplest form of class definition looks like this: ``` class ClassName: <statement-1> . . . <statement-N> ``` Class definitions, like function definitions ([`def`](../reference/compound_stmts#def) statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an [`if`](../reference/compound_stmts#if) statement, or inside a function.) In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful — we’ll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods — again, this is explained later. When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. When a class definition is left normally (via the end), a *class object* is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (`ClassName` in the example). ### 9.3.2. Class Objects Class objects support two kinds of operations: attribute references and instantiation. *Attribute references* use the standard syntax used for all attribute references in Python: `obj.name`. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this: ``` class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' ``` then `MyClass.i` and `MyClass.f` are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of `MyClass.i` by assignment. `__doc__` is also a valid attribute, returning the docstring belonging to the class: `"A simple example class"`. Class *instantiation* uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class): ``` x = MyClass() ``` creates a new *instance* of the class and assigns this object to the local variable `x`. The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"), like this: ``` def __init__(self): self.data = [] ``` When a class defines an [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method, class instantiation automatically invokes [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") for the newly-created class instance. So in this example, a new, initialized instance can be obtained by: ``` x = MyClass() ``` Of course, the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"). For example, ``` >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) ``` ### 9.3.3. Instance Objects Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names: data attributes and methods. *data attributes* correspond to “instance variables” in Smalltalk, and to “data members” in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. For example, if `x` is the instance of `MyClass` created above, the following piece of code will print the value `16`, without leaving a trace: ``` x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print(x.counter) del x.counter ``` The other kind of instance attribute reference is a *method*. A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. However, in the following discussion, we’ll use the term method exclusively to mean methods of class instance objects, unless explicitly stated otherwise.) Valid method names of an instance object depend on its class. By definition, all attributes of a class that are function objects define corresponding methods of its instances. So in our example, `x.f` is a valid method reference, since `MyClass.f` is a function, but `x.i` is not, since `MyClass.i` is not. But `x.f` is not the same thing as `MyClass.f` — it is a *method object*, not a function object. ### 9.3.4. Method Objects Usually, a method is called right after it is bound: ``` x.f() ``` In the `MyClass` example, this will return the string `'hello world'`. However, it is not necessary to call a method right away: `x.f` is a method object, and can be stored away and called at a later time. For example: ``` xf = x.f while True: print(xf()) ``` will continue to print `hello world` until the end of time. What exactly happens when a method is called? You may have noticed that `x.f()` was called without an argument above, even though the function definition for `f()` specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used… Actually, you may have guessed the answer: the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call `x.f()` is exactly equivalent to `MyClass.f(x)`. In general, calling a method with a list of *n* arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument. If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list. ### 9.3.5. Class and Instance Variables Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class: ``` class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.kind # shared by all dogs 'canine' >>> e.kind # shared by all dogs 'canine' >>> d.name # unique to d 'Fido' >>> e.name # unique to e 'Buddy' ``` As discussed in [A Word About Names and Objects](#tut-object), shared data can have possibly surprising effects with involving [mutable](../glossary#term-mutable) objects such as lists and dictionaries. For example, the *tricks* list in the following code should not be used as a class variable because just a single list would be shared by all *Dog* instances: ``` class Dog: tricks = [] # mistaken use of a class variable def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.add_trick('roll over') >>> e.add_trick('play dead') >>> d.tricks # unexpectedly shared by all dogs ['roll over', 'play dead'] ``` Correct design of the class should use an instance variable instead: ``` class Dog: def __init__(self, name): self.name = name self.tricks = [] # creates a new empty list for each dog def add_trick(self, trick): self.tricks.append(trick) >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.add_trick('roll over') >>> e.add_trick('play dead') >>> d.tricks ['roll over'] >>> e.tricks ['play dead'] ``` 9.4. Random Remarks -------------------- If the same attribute name occurs in both an instance and in a class, then attribute lookup prioritizes the instance: ``` >>> class Warehouse: purpose = 'storage' region = 'west' >>> w1 = Warehouse() >>> print(w1.purpose, w1.region) storage west >>> w2 = Warehouse() >>> w2.region = 'east' >>> print(w2.purpose, w2.region) storage east ``` Data attributes may be referenced by methods as well as by ordinary users (“clients”) of an object. In other words, classes are not usable to implement pure abstract data types. In fact, nothing in Python makes it possible to enforce data hiding — it is all based upon convention. (On the other hand, the Python implementation, written in C, can completely hide implementation details and control access to an object if necessary; this can be used by extensions to Python written in C.) Clients should use data attributes with care — clients may mess up invariants maintained by the methods by stamping on their data attributes. Note that clients may add data attributes of their own to an instance object without affecting the validity of the methods, as long as name conflicts are avoided — again, a naming convention can save a lot of headaches here. There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method. Often, the first argument of a method is called `self`. This is nothing more than a convention: the name `self` has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a *class browser* program might be written that relies upon such a convention. Any function object that is a class attribute defines a method for instances of that class. It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok. For example: ``` # Function defined outside the class def f1(self, x, y): return min(x, x+y) class C: f = f1 def g(self): return 'hello world' h = g ``` Now `f`, `g` and `h` are all attributes of class `C` that refer to function objects, and consequently they are all methods of instances of `C` — `h` being exactly equivalent to `g`. Note that this practice usually only serves to confuse the reader of a program. Methods may call other methods by using method attributes of the `self` argument: ``` class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x) ``` Methods may reference global names in the same way as ordinary functions. The global scope associated with a method is the module containing its definition. (A class is never used as a global scope.) While one rarely encounters a good reason for using global data in a method, there are many legitimate uses of the global scope: for one thing, functions and modules imported into the global scope can be used by methods, as well as functions and classes defined in it. Usually, the class containing the method is itself defined in this global scope, and in the next section we’ll find some good reasons why a method would want to reference its own class. Each value is an object, and therefore has a *class* (also called its *type*). It is stored as `object.__class__`. 9.5. Inheritance ----------------- Of course, a language feature would not be worthy of the name “class” without supporting inheritance. The syntax for a derived class definition looks like this: ``` class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N> ``` The name `BaseClassName` must be defined in a scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module: ``` class DerivedClassName(modname.BaseClassName): ``` Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class. There’s nothing special about instantiation of derived classes: `DerivedClassName()` creates a new instance of the class. Method references are resolved as follows: the corresponding class attribute is searched, descending down the chain of base classes if necessary, and the method reference is valid if this yields a function object. Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively `virtual`.) An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call `BaseClassName.methodname(self, arguments)`. This is occasionally useful to clients as well. (Note that this only works if the base class is accessible as `BaseClassName` in the global scope.) Python has two built-in functions that work with inheritance: * Use [`isinstance()`](../library/functions#isinstance "isinstance") to check an instance’s type: `isinstance(obj, int)` will be `True` only if `obj.__class__` is [`int`](../library/functions#int "int") or some class derived from [`int`](../library/functions#int "int"). * Use [`issubclass()`](../library/functions#issubclass "issubclass") to check class inheritance: `issubclass(bool, int)` is `True` since [`bool`](../library/functions#bool "bool") is a subclass of [`int`](../library/functions#int "int"). However, `issubclass(float, int)` is `False` since [`float`](../library/functions#float "float") is not a subclass of [`int`](../library/functions#int "int"). ### 9.5.1. Multiple Inheritance Python supports a form of multiple inheritance as well. A class definition with multiple base classes looks like this: ``` class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N> ``` For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in `DerivedClassName`, it is searched for in `Base1`, then (recursively) in the base classes of `Base1`, and if it was not found there, it was searched for in `Base2`, and so on. In fact, it is slightly more complex than that; the method resolution order changes dynamically to support cooperative calls to [`super()`](../library/functions#super "super"). This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages. Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost class). For example, all classes inherit from [`object`](../library/functions#object "object"), so any case of multiple inheritance provides more than one path to reach [`object`](../library/functions#object "object"). To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents). Taken together, these properties make it possible to design reliable and extensible classes with multiple inheritance. For more detail, see <https://www.python.org/download/releases/2.3/mro/>. 9.6. Private Variables ----------------------- “Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. `_spam`) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice. Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called *name mangling*. Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where `classname` is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example: ``` class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) ``` The above example would work even if `MappingSubclass` were to introduce a `__update` identifier since it is replaced with `_Mapping__update` in the `Mapping` class and `_MappingSubclass__update` in the `MappingSubclass` class respectively. Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger. Notice that code passed to `exec()` or `eval()` does not consider the classname of the invoking class to be the current class; this is similar to the effect of the `global` statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to `getattr()`, `setattr()` and `delattr()`, as well as when referencing `__dict__` directly. 9.7. Odds and Ends ------------------- Sometimes it is useful to have a data type similar to the Pascal “record” or C “struct”, bundling together a few named data items. An empty class definition will do nicely: ``` class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salary = 1000 ``` A piece of Python code that expects a particular abstract data type can often be passed a class that emulates the methods of that data type instead. For instance, if you have a function that formats some data from a file object, you can define a class with methods `read()` and `readline()` that get the data from a string buffer instead, and pass it as an argument. Instance method objects have attributes, too: `m.__self__` is the instance object with the method `m()`, and `m.__func__` is the function object corresponding to the method. 9.8. Iterators --------------- By now you have probably noticed that most container objects can be looped over using a [`for`](../reference/compound_stmts#for) statement: ``` for element in [1, 2, 3]: print(element) for element in (1, 2, 3): print(element) for key in {'one':1, 'two':2}: print(key) for char in "123": print(char) for line in open("myfile.txt"): print(line, end='') ``` This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the [`for`](../reference/compound_stmts#for) statement calls [`iter()`](../library/functions#iter "iter") on the container object. The function returns an iterator object that defines the method [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") which accesses elements in the container one at a time. When there are no more elements, [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") raises a [`StopIteration`](../library/exceptions#StopIteration "StopIteration") exception which tells the `for` loop to terminate. You can call the [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method using the [`next()`](../library/functions#next "next") built-in function; this example shows how it all works: ``` >>> s = 'abc' >>> it = iter(s) >>> it <str_iterator object at 0x10c90e650> >>> next(it) 'a' >>> next(it) 'b' >>> next(it) 'c' >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> next(it) StopIteration ``` Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define an [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") method which returns an object with a [`__next__()`](../library/stdtypes#iterator.__next__ "iterator.__next__") method. If the class defines `__next__()`, then [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") can just return `self`: ``` class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] ``` ``` >>> rev = Reverse('spam') >>> iter(rev) <__main__.Reverse object at 0x00A1DB50> >>> for char in rev: ... print(char) ... m a p s ``` 9.9. Generators ---------------- [Generators](../glossary#term-generator) are a simple and powerful tool for creating iterators. They are written like regular functions but use the [`yield`](../reference/simple_stmts#yield) statement whenever they want to return data. Each time [`next()`](../library/functions#next "next") is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create: ``` def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] ``` ``` >>> for char in reverse('golf'): ... print(char) ... f l o g ``` Anything that can be done with generators can also be done with class-based iterators as described in the previous section. What makes generators so compact is that the [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") and [`__next__()`](../reference/expressions#generator.__next__ "generator.__next__") methods are created automatically. Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using instance variables like `self.index` and `self.data`. In addition to automatic method creation and saving program state, when generators terminate, they automatically raise [`StopIteration`](../library/exceptions#StopIteration "StopIteration"). In combination, these features make it easy to create iterators with no more effort than writing a regular function. 9.10. Generator Expressions ---------------------------- Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but with parentheses instead of square brackets. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions. Examples: ``` >>> sum(i*i for i in range(10)) # sum of squares 285 >>> xvec = [10, 20, 30] >>> yvec = [7, 5, 3] >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product 260 >>> unique_words = set(word for line in page for word in line.split()) >>> valedictorian = max((student.gpa, student.name) for student in graduates) >>> data = 'golf' >>> list(data[i] for i in range(len(data)-1, -1, -1)) ['f', 'l', 'o', 'g'] ``` #### Footnotes `1` Except for one thing. Module objects have a secret read-only attribute called [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") which returns the dictionary used to implement the module’s namespace; the name [`__dict__`](../library/stdtypes#object.__dict__ "object.__dict__") is an attribute but not a global name. Obviously, using this violates the abstraction of namespace implementation, and should be restricted to things like post-mortem debuggers.
programming_docs
python Errors and Exceptions Errors and Exceptions ====================== Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: *syntax errors* and *exceptions*. 8.1. Syntax Errors ------------------- Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python: ``` >>> while True print('Hello world') File "<stdin>", line 1 while True print('Hello world') ^ SyntaxError: invalid syntax ``` The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token *preceding* the arrow: in the example, the error is detected at the function [`print()`](../library/functions#print "print"), since a colon (`':'`) is missing before it. File name and line number are printed so you know where to look in case the input came from a script. 8.2. Exceptions ---------------- Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called *exceptions* and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here: ``` >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str ``` The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are [`ZeroDivisionError`](../library/exceptions#ZeroDivisionError "ZeroDivisionError"), [`NameError`](../library/exceptions#NameError "NameError") and [`TypeError`](../library/exceptions#TypeError "TypeError"). The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords). The rest of the line provides detail based on the type of exception and what caused it. The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input. [Built-in Exceptions](../library/exceptions#bltin-exceptions) lists the built-in exceptions and their meanings. 8.3. Handling Exceptions ------------------------- It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using `Control-C` or whatever the operating system supports); note that a user-generated interruption is signalled by raising the [`KeyboardInterrupt`](../library/exceptions#KeyboardInterrupt "KeyboardInterrupt") exception. ``` >>> while True: ... try: ... x = int(input("Please enter a number: ")) ... break ... except ValueError: ... print("Oops! That was no valid number. Try again...") ... ``` The [`try`](../reference/compound_stmts#try) statement works as follows. * First, the *try clause* (the statement(s) between the [`try`](../reference/compound_stmts#try) and [`except`](../reference/compound_stmts#except) keywords) is executed. * If no exception occurs, the *except clause* is skipped and execution of the [`try`](../reference/compound_stmts#try) statement is finished. * If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the [`except`](../reference/compound_stmts#except) keyword, the except clause is executed, and then execution continues after the [`try`](../reference/compound_stmts#try) statement. * If an exception occurs which does not match the exception named in the except clause, it is passed on to outer [`try`](../reference/compound_stmts#try) statements; if no handler is found, it is an *unhandled exception* and execution stops with a message as shown above. A [`try`](../reference/compound_stmts#try) statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same `try` statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: ``` ... except (RuntimeError, TypeError, NameError): ... pass ``` A class in an [`except`](../reference/compound_stmts#except) clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order: ``` class B(Exception): pass class C(B): pass class D(C): pass for cls in [B, C, D]: try: raise cls() except D: print("D") except C: print("C") except B: print("B") ``` Note that if the except clauses were reversed (with `except B` first), it would have printed B, B, B — the first matching except clause is triggered. The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well): ``` import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise ``` The [`try`](../reference/compound_stmts#try) … [`except`](../reference/compound_stmts#except) statement has an optional *else clause*, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example: ``` for arg in sys.argv[1:]: try: f = open(arg, 'r') except OSError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close() ``` The use of the `else` clause is better than adding additional code to the [`try`](../reference/compound_stmts#try) clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the `try` … `except` statement. When an exception occurs, it may have an associated value, also known as the exception’s *argument*. The presence and type of the argument depend on the exception type. The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in `instance.args`. For convenience, the exception instance defines [`__str__()`](../reference/datamodel#object.__str__ "object.__str__") so the arguments can be printed directly without having to reference `.args`. One may also instantiate an exception first before raising it and add any attributes to it as desired. ``` >>> try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print(type(inst)) # the exception instance ... print(inst.args) # arguments stored in .args ... print(inst) # __str__ allows args to be printed directly, ... # but may be overridden in exception subclasses ... x, y = inst.args # unpack args ... print('x =', x) ... print('y =', y) ... <class 'Exception'> ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs ``` If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions. Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example: ``` >>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError as err: ... print('Handling run-time error:', err) ... Handling run-time error: division by zero ``` 8.4. Raising Exceptions ------------------------ The [`raise`](../reference/simple_stmts#raise) statement allows the programmer to force a specified exception to occur. For example: ``` >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: HiThere ``` The sole argument to [`raise`](../reference/simple_stmts#raise) indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from [`Exception`](../library/exceptions#Exception "Exception")). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments: ``` raise ValueError # shorthand for 'raise ValueError()' ``` If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the [`raise`](../reference/simple_stmts#raise) statement allows you to re-raise the exception: ``` >>> try: ... raise NameError('HiThere') ... except NameError: ... print('An exception flew by!') ... raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: HiThere ``` 8.5. Exception Chaining ------------------------ The [`raise`](../reference/simple_stmts#raise) statement allows an optional [`from`](../reference/simple_stmts#raise) which enables chaining exceptions. For example: ``` # exc must be exception instance or None. raise RuntimeError from exc ``` This can be useful when you are transforming exceptions. For example: ``` >>> def func(): ... raise IOError ... >>> try: ... func() ... except IOError as exc: ... raise RuntimeError('Failed to open database') from exc ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 2, in func OSError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError: Failed to open database ``` Exception chaining happens automatically when an exception is raised inside an [`except`](../reference/compound_stmts#except) or [`finally`](../reference/compound_stmts#finally) section. Exception chaining can be disabled by using `from None` idiom: ``` >>> try: ... open('database.sqlite') ... except OSError: ... raise RuntimeError from None ... Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError ``` For more information about chaining mechanics, see [Built-in Exceptions](../library/exceptions#bltin-exceptions). 8.6. User-defined Exceptions ----------------------------- Programs may name their own exceptions by creating a new exception class (see [Classes](classes#tut-classes) for more about Python classes). Exceptions should typically be derived from the [`Exception`](../library/exceptions#Exception "Exception") class, either directly or indirectly. Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions. Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter [Classes](classes#tut-classes). 8.7. Defining Clean-up Actions ------------------------------- The [`try`](../reference/compound_stmts#try) statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: ``` >>> try: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') ... Goodbye, world! KeyboardInterrupt Traceback (most recent call last): File "<stdin>", line 2, in <module> ``` If a [`finally`](../reference/compound_stmts#finally) clause is present, the `finally` clause will execute as the last task before the [`try`](../reference/compound_stmts#try) statement completes. The `finally` clause runs whether or not the `try` statement produces an exception. The following points discuss more complex cases when an exception occurs: * If an exception occurs during execution of the `try` clause, the exception may be handled by an [`except`](../reference/compound_stmts#except) clause. If the exception is not handled by an `except` clause, the exception is re-raised after the `finally` clause has been executed. * An exception could occur during execution of an `except` or `else` clause. Again, the exception is re-raised after the `finally` clause has been executed. * If the `finally` clause executes a [`break`](../reference/simple_stmts#break), [`continue`](../reference/simple_stmts#continue) or [`return`](../reference/simple_stmts#return) statement, exceptions are not re-raised. * If the `try` statement reaches a [`break`](../reference/simple_stmts#break), [`continue`](../reference/simple_stmts#continue) or [`return`](../reference/simple_stmts#return) statement, the `finally` clause will execute just prior to the `break`, `continue` or `return` statement’s execution. * If a `finally` clause includes a `return` statement, the returned value will be the one from the `finally` clause’s `return` statement, not the value from the `try` clause’s `return` statement. For example: ``` >>> def bool_return(): ... try: ... return True ... finally: ... return False ... >>> bool_return() False ``` A more complicated example: ``` >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print("division by zero!") ... else: ... print("result is", result) ... finally: ... print("executing finally clause") ... >>> divide(2, 1) result is 2.0 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str' ``` As you can see, the [`finally`](../reference/compound_stmts#finally) clause is executed in any event. The [`TypeError`](../library/exceptions#TypeError "TypeError") raised by dividing two strings is not handled by the [`except`](../reference/compound_stmts#except) clause and therefore re-raised after the `finally` clause has been executed. In real world applications, the [`finally`](../reference/compound_stmts#finally) clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful. 8.8. Predefined Clean-up Actions --------------------------------- Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen. ``` for line in open("myfile.txt"): print(line, end="") ``` The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The [`with`](../reference/compound_stmts#with) statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. ``` with open("myfile.txt") as f: for line in f: print(line, end="") ``` After the statement is executed, the file *f* is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation. python An Informal Introduction to Python An Informal Introduction to Python =================================== In the following examples, input and output are distinguished by the presence or absence of prompts ([>>>](../glossary#term-0) and […](../glossary#term-1)): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command. You can toggle the display of prompts and output by clicking on `>>>` in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter. Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, `#`, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples. Some examples: ``` # this is the first comment spam = 1 # and this is the second comment # ... and now a third! text = "# This is not a comment because it's inside quotes." ``` 3.1. Using Python as a Calculator ---------------------------------- Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, `>>>`. (It shouldn’t take long.) ### 3.1.1. Numbers The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators `+`, `-`, `*` and `/` work just like in most other languages (for example, Pascal or C); parentheses (`()`) can be used for grouping. For example: ``` >>> 2 + 2 4 >>> 50 - 5*6 20 >>> (50 - 5*6) / 4 5.0 >>> 8 / 5 # division always returns a floating point number 1.6 ``` The integer numbers (e.g. `2`, `4`, `20`) have type [`int`](../library/functions#int "int"), the ones with a fractional part (e.g. `5.0`, `1.6`) have type [`float`](../library/functions#float "float"). We will see more about numeric types later in the tutorial. Division (`/`) always returns a float. To do [floor division](../glossary#term-floor-division) and get an integer result (discarding any fractional result) you can use the `//` operator; to calculate the remainder you can use `%`: ``` >>> 17 / 3 # classic division returns a float 5.666666666666667 >>> >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2 >>> 5 * 3 + 2 # floored quotient * divisor + remainder 17 ``` With Python, it is possible to use the `**` operator to calculate powers [1](#id3): ``` >>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128 ``` The equal sign (`=`) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt: ``` >>> width = 20 >>> height = 5 * 9 >>> width * height 900 ``` If a variable is not “defined” (assigned a value), trying to use it will give you an error: ``` >>> n # try to access an undefined variable Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'n' is not defined ``` There is full support for floating point; operators with mixed type operands convert the integer operand to floating point: ``` >>> 4 * 3.75 - 1 14.0 ``` In interactive mode, the last printed expression is assigned to the variable `_`. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example: ``` >>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06 ``` This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior. In addition to [`int`](../library/functions#int "int") and [`float`](../library/functions#float "float"), Python supports other types of numbers, such as [`Decimal`](../library/decimal#decimal.Decimal "decimal.Decimal") and [`Fraction`](../library/fractions#fractions.Fraction "fractions.Fraction"). Python also has built-in support for [complex numbers](../library/stdtypes#typesnumeric), and uses the `j` or `J` suffix to indicate the imaginary part (e.g. `3+5j`). ### 3.1.2. Strings Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes (`'...'`) or double quotes (`"..."`) with the same result [2](#id4). `\` can be used to escape quotes: ``` >>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.' ``` In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The [`print()`](../library/functions#print "print") function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters: ``` >>> '"Isn\'t," they said.' '"Isn\'t," they said.' >>> print('"Isn\'t," they said.') "Isn't," they said. >>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), \n is included in the output 'First line.\nSecond line.' >>> print(s) # with print(), \n produces a new line First line. Second line. ``` If you don’t want characters prefaced by `\` to be interpreted as special characters, you can use *raw strings* by adding an `r` before the first quote: ``` >>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name ``` String literals can span multiple lines. One way is using triple-quotes: `"""..."""` or `'''...'''`. End of lines are automatically included in the string, but it’s possible to prevent this by adding a `\` at the end of the line. The following example: ``` print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) ``` produces the following output (note that the initial newline is not included): ``` Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to ``` Strings can be concatenated (glued together) with the `+` operator, and repeated with `*`: ``` >>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium' ``` Two or more *string literals* (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. ``` >>> 'Py' 'thon' 'Python' ``` This feature is particularly useful when you want to break long strings: ``` >>> text = ('Put several strings within parentheses ' ... 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.' ``` This only works with two literals though, not with variables or expressions: ``` >>> prefix = 'Py' >>> prefix 'thon' # can't concatenate a variable and a string literal File "<stdin>", line 1 prefix 'thon' ^ SyntaxError: invalid syntax >>> ('un' * 3) 'ium' File "<stdin>", line 1 ('un' * 3) 'ium' ^ SyntaxError: invalid syntax ``` If you want to concatenate variables or a variable and a literal, use `+`: ``` >>> prefix + 'thon' 'Python' ``` Strings can be *indexed* (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one: ``` >>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n' ``` Indices may also be negative numbers, to start counting from the right: ``` >>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P' ``` Note that since -0 is the same as 0, negative indices start from -1. In addition to indexing, *slicing* is also supported. While indexing is used to obtain individual characters, *slicing* allows you to obtain substring: ``` >>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho' ``` Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced. ``` >>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on' ``` Note how the start is always included, and the end always excluded. This makes sure that `s[:i] + s[i:]` is always equal to `s`: ``` >>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python' ``` One way to remember how slices work is to think of the indices as pointing *between* characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of *n* characters has index *n*, for example: ``` +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 ``` The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from *i* to *j* consists of all characters between the edges labeled *i* and *j*, respectively. For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of `word[1:3]` is 2. Attempting to use an index that is too large will result in an error: ``` >>> word[42] # the word only has 6 characters Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range ``` However, out of range slice indexes are handled gracefully when used for slicing: ``` >>> word[4:42] 'on' >>> word[42:] '' ``` Python strings cannot be changed — they are [immutable](../glossary#term-immutable). Therefore, assigning to an indexed position in the string results in an error: ``` >>> word[0] = 'J' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment ``` If you need a different string, you should create a new one: ``` >>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy' ``` The built-in function [`len()`](../library/functions#len "len") returns the length of a string: ``` >>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34 ``` See also [Text Sequence Type — str](../library/stdtypes#textseq) Strings are examples of *sequence types*, and support the common operations supported by such types. [String Methods](../library/stdtypes#string-methods) Strings support a large number of methods for basic transformations and searching. [Formatted string literals](../reference/lexical_analysis#f-strings) String literals that have embedded expressions. [Format String Syntax](../library/string#formatstrings) Information about string formatting with [`str.format()`](../library/stdtypes#str.format "str.format"). [printf-style String Formatting](../library/stdtypes#old-string-formatting) The old formatting operations invoked when strings are the left operand of the `%` operator are described in more detail here. ### 3.1.3. Lists Python knows a number of *compound* data types, used to group together other values. The most versatile is the *list*, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. ``` >>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25] ``` Like strings (and all other built-in [sequence](../glossary#term-sequence) types), lists can be indexed and sliced: ``` >>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25] ``` All slice operations return a new list containing the requested elements. This means that the following slice returns a [shallow copy](../library/copy#shallow-vs-deep-copy) of the list: ``` >>> squares[:] [1, 4, 9, 16, 25] ``` Lists also support operations like concatenation: ``` >>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ``` Unlike strings, which are [immutable](../glossary#term-immutable), lists are a [mutable](../glossary#term-mutable) type, i.e. it is possible to change their content: ``` >>> cubes = [1, 8, 27, 65, 125] # something's wrong here >>> 4 ** 3 # the cube of 4 is 64, not 65! 64 >>> cubes[3] = 64 # replace the wrong value >>> cubes [1, 8, 27, 64, 125] ``` You can also add new items at the end of the list, by using the `append()` *method* (we will see more about methods later): ``` >>> cubes.append(216) # add the cube of 6 >>> cubes.append(7 ** 3) # and the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343] ``` Assignment to slices is also possible, and this can even change the size of the list or clear it entirely: ``` >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # replace some values >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # now remove them >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # clear the list by replacing all the elements with an empty list >>> letters[:] = [] >>> letters [] ``` The built-in function [`len()`](../library/functions#len "len") also applies to lists: ``` >>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4 ``` It is possible to nest lists (create lists containing other lists), for example: ``` >>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b' ``` 3.2. First Steps Towards Programming ------------------------------------- Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the [Fibonacci series](https://en.wikipedia.org/wiki/Fibonacci_number) as follows: ``` >>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while a < 10: ... print(a) ... a, b = b, a+b ... 0 1 1 2 3 5 8 ``` This example introduces several new features. * The first line contains a *multiple assignment*: the variables `a` and `b` simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right. * The [`while`](../reference/compound_stmts#while) loop executes as long as the condition (here: `a < 10`) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: `<` (less than), `>` (greater than), `==` (equal to), `<=` (less than or equal to), `>=` (greater than or equal to) and `!=` (not equal to). * The *body* of the loop is *indented*: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount. * The [`print()`](../library/functions#print "print") function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this: ``` >>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536 ``` The keyword argument *end* can be used to avoid the newline after the output, or end the output with a different string: ``` >>> a, b = 0, 1 >>> while a < 1000: ... print(a, end=',') ... a, b = b, a+b ... 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, ``` #### Footnotes `1` Since `**` has higher precedence than `-`, `-3**2` will be interpreted as `-(3**2)` and thus result in `-9`. To avoid this and get `9`, you can use `(-3)**2`. `2` Unlike other languages, special characters such as `\n` have the same meaning with both single (`'...'`) and double (`"..."`) quotes. The only difference between the two is that within single quotes you don’t need to escape `"` (but you have to escape `\'`) and vice versa.
programming_docs
python Installing Python Modules (Legacy version) Installing Python Modules (Legacy version) ========================================== Author Greg Ward See also [Installing Python Modules](../installing/index#installing-index) The up to date module installation documentation. For regular Python usage, you almost certainly want that document rather than this one. Note This document is being retained solely until the `setuptools` documentation at <https://setuptools.readthedocs.io/en/latest/setuptools.html> independently covers all of the relevant information currently included here. Note This guide only covers the basic tools for building and distributing extensions that are provided as part of this version of Python. Third party tools offer easier to use and more secure alternatives. Refer to the [quick recommendations section](https://packaging.python.org/guides/tool-recommendations/) in the Python Packaging User Guide for more information. Introduction ------------ In Python 2.0, the `distutils` API was first added to the standard library. This provided Linux distro maintainers with a standard way of converting Python projects into Linux distro packages, and system administrators with a standard way of installing them directly onto target systems. In the many years since Python 2.0 was released, tightly coupling the build system and package installer to the language runtime release cycle has turned out to be problematic, and it is now recommended that projects use the `pip` package installer and the `setuptools` build system, rather than using `distutils` directly. See [Installing Python Modules](../installing/index#installing-index) and [Distributing Python Modules](../distributing/index#distributing-index) for more details. This legacy documentation is being retained only until we’re confident that the `setuptools` documentation covers everything needed. ### Distutils based source distributions If you download a module source distribution, you can tell pretty quickly if it was packaged and distributed in the standard way, i.e. using the Distutils. First, the distribution’s name and version number will be featured prominently in the name of the downloaded archive, e.g. `foo-1.0.tar.gz` or `widget-0.9.7.zip`. Next, the archive will unpack into a similarly-named directory: `foo-1.0` or `widget-0.9.7`. Additionally, the distribution will contain a setup script `setup.py`, and a file named `README.txt` or possibly just `README`, which should explain that building and installing the module distribution is a simple matter of running one command from a terminal: ``` python setup.py install ``` For Windows, this command should be run from a command prompt window (Start ‣ Accessories): ``` setup.py install ``` If all these things are true, then you already know how to build and install the modules you’ve just downloaded: Run the command above. Unless you need to install things in a non-standard way or customize the build process, you don’t really need this manual. Or rather, the above command is everything you need to get out of this manual. Standard Build and Install -------------------------- As described in section [Distutils based source distributions](#inst-new-standard), building and installing a module distribution using the Distutils is usually one simple command to run from a terminal: ``` python setup.py install ``` ### Platform variations You should always run the setup command from the distribution root directory, i.e. the top-level subdirectory that the module source distribution unpacks into. For example, if you’ve just downloaded a module source distribution `foo-1.0.tar.gz` onto a Unix system, the normal thing to do is: ``` gunzip -c foo-1.0.tar.gz | tar xf - # unpacks into directory foo-1.0 cd foo-1.0 python setup.py install ``` On Windows, you’d probably download `foo-1.0.zip`. If you downloaded the archive file to `C:\Temp`, then it would unpack into `C:\Temp\foo-1.0`; you can use either an archive manipulator with a graphical user interface (such as WinZip) or a command-line tool (such as **unzip** or **pkunzip**) to unpack the archive. Then, open a command prompt window and run: ``` cd c:\Temp\foo-1.0 python setup.py install ``` ### Splitting the job up Running `setup.py install` builds and installs all modules in one run. If you prefer to work incrementally—especially useful if you want to customize the build process, or if things are going wrong—you can use the setup script to do one thing at a time. This is particularly helpful when the build and install will be done by different users—for example, you might want to build a module distribution and hand it off to a system administrator for installation (or do it yourself, with super-user privileges). For example, you can build everything in one step, and then install everything in a second step, by invoking the setup script twice: ``` python setup.py build python setup.py install ``` If you do this, you will notice that running the **install** command first runs the **build** command, which—in this case—quickly notices that it has nothing to do, since everything in the `build` directory is up-to-date. You may not need this ability to break things down often if all you do is install modules downloaded off the ‘net, but it’s very handy for more advanced tasks. If you get into distributing your own Python modules and extensions, you’ll run lots of individual Distutils commands on their own. ### How building works As implied above, the **build** command is responsible for putting the files to install into a *build directory*. By default, this is `build` under the distribution root; if you’re excessively concerned with speed, or want to keep the source tree pristine, you can change the build directory with the `--build-base` option. For example: ``` python setup.py build --build-base=/path/to/pybuild/foo-1.0 ``` (Or you could do this permanently with a directive in your system or personal Distutils configuration file; see section [Distutils Configuration Files](#inst-config-files).) Normally, this isn’t necessary. The default layout for the build tree is as follows: ``` --- build/ --- lib/ or --- build/ --- lib.<plat>/ temp.<plat>/ ``` where `<plat>` expands to a brief description of the current OS/hardware platform and Python version. The first form, with just a `lib` directory, is used for “pure module distributions”—that is, module distributions that include only pure Python modules. If a module distribution contains any extensions (modules written in C/C++), then the second form, with two `<plat>` directories, is used. In that case, the `temp.*plat*` directory holds temporary files generated by the compile/link process that don’t actually get installed. In either case, the `lib` (or `lib.*plat*`) directory contains all Python modules (pure Python and extensions) that will be installed. In the future, more directories will be added to handle Python scripts, documentation, binary executables, and whatever else is needed to handle the job of installing Python modules and applications. ### How installation works After the **build** command runs (whether you run it explicitly, or the **install** command does it for you), the work of the **install** command is relatively simple: all it has to do is copy everything under `build/lib` (or `build/lib.*plat*`) to your chosen installation directory. If you don’t choose an installation directory—i.e., if you just run `setup.py install`—then the **install** command installs to the standard location for third-party Python modules. This location varies by platform and by how you built/installed Python itself. On Unix (and macOS, which is also Unix-based), it also depends on whether the module distribution being installed is pure Python or contains extensions (“non-pure”): | Platform | Standard installation location | Default value | Notes | | --- | --- | --- | --- | | Unix (pure) | `*prefix*/lib/python*X.Y*/site-packages` | `/usr/local/lib/python*X.Y*/site-packages` | (1) | | Unix (non-pure) | `*exec-prefix*/lib/python*X.Y*/site-packages` | `/usr/local/lib/python*X.Y*/site-packages` | (1) | | Windows | `*prefix*\Lib\site-packages` | `C:\Python*XY*\Lib\site-packages` | (2) | Notes: 1. Most Linux distributions include Python as a standard part of the system, so `*prefix*` and `*exec-prefix*` are usually both `/usr` on Linux. If you build Python yourself on Linux (or any Unix-like system), the default `*prefix*` and `*exec-prefix*` are `/usr/local`. 2. The default installation directory on Windows was `C:\Program Files\Python` under Python 1.6a1, 1.5.2, and earlier. `*prefix*` and `*exec-prefix*` stand for the directories that Python is installed to, and where it finds its libraries at run-time. They are always the same under Windows, and very often the same under Unix and macOS. You can find out what your Python installation uses for `*prefix*` and `*exec-prefix*` by running Python in interactive mode and typing a few simple commands. Under Unix, just type `python` at the shell prompt. Under Windows, choose Start ‣ Programs ‣ Python X.Y ‣ Python (command line). Once the interpreter is started, you type Python code at the prompt. For example, on my Linux system, I type the three Python statements shown below, and get the output as shown, to find out my `*prefix*` and `*exec-prefix*`: ``` Python 2.4 (#26, Aug 7 2004, 17:19:02) Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.prefix '/usr' >>> sys.exec_prefix '/usr' ``` A few other placeholders are used in this document: `*X.Y*` stands for the version of Python, for example `3.2`; `*abiflags*` will be replaced by the value of [`sys.abiflags`](../library/sys#sys.abiflags "sys.abiflags") or the empty string for platforms which don’t define ABI flags; `*distname*` will be replaced by the name of the module distribution being installed. Dots and capitalization are important in the paths; for example, a value that uses `python3.2` on UNIX will typically use `Python32` on Windows. If you don’t want to install modules to the standard location, or if you don’t have permission to write there, then you need to read about alternate installations in section [Alternate Installation](#inst-alt-install). If you want to customize your installation directories more heavily, see section [Custom Installation](#inst-custom-install) on custom installations. Alternate Installation ---------------------- Often, it is necessary or desirable to install modules to a location other than the standard location for third-party Python modules. For example, on a Unix system you might not have permission to write to the standard third-party module directory. Or you might wish to try out a module before making it a standard part of your local Python installation. This is especially true when upgrading a distribution already present: you want to make sure your existing base of scripts still works with the new version before actually upgrading. The Distutils **install** command is designed to make installing module distributions to an alternate location simple and painless. The basic idea is that you supply a base directory for the installation, and the **install** command picks a set of directories (called an *installation scheme*) under this base directory in which to install files. The details differ across platforms, so read whichever of the following sections applies to you. Note that the various alternate installation schemes are mutually exclusive: you can pass `--user`, or `--home`, or `--prefix` and `--exec-prefix`, or `--install-base` and `--install-platbase`, but you can’t mix from these groups. ### Alternate installation: the user scheme This scheme is designed to be the most convenient solution for users that don’t have write permission to the global site-packages directory or don’t want to install into it. It is enabled with a simple option: ``` python setup.py install --user ``` Files will be installed into subdirectories of [`site.USER_BASE`](../library/site#site.USER_BASE "site.USER_BASE") (written as `*userbase*` hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as [`site.USER_SITE`](../library/site#site.USER_SITE "site.USER_SITE")). Here are the values for UNIX, including macOS: | Type of file | Installation directory | | --- | --- | | modules | `*userbase*/lib/python*X.Y*/site-packages` | | scripts | `*userbase*/bin` | | data | `*userbase*` | | C headers | `*userbase*/include/python*X.Y**abiflags*/*distname*` | And here are the values used on Windows: | Type of file | Installation directory | | --- | --- | | modules | `*userbase*\Python*XY*\site-packages` | | scripts | `*userbase*\Python*XY*\Scripts` | | data | `*userbase*` | | C headers | `*userbase*\Python*XY*\Include{distname}` | The advantage of using this scheme compared to the other ones described below is that the user site-packages directory is under normal conditions always included in [`sys.path`](../library/sys#sys.path "sys.path") (see [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") for more information), which means that there is no additional step to perform after running the `setup.py` script to finalize the installation. The **build\_ext** command also has a `--user` option to add `*userbase*/include` to the compiler search path for header files and `*userbase*/lib` to the compiler search path for libraries as well as to the runtime search path for shared C libraries (rpath). ### Alternate installation: the home scheme The idea behind the “home scheme” is that you build and maintain a personal stash of Python modules. This scheme’s name is derived from the idea of a “home” directory on Unix, since it’s not unusual for a Unix user to make their home directory have a layout similar to `/usr/` or `/usr/local/`. This scheme can be used by anyone, regardless of the operating system they are installing for. Installing a new module distribution is as simple as ``` python setup.py install --home=<dir> ``` where you can supply any directory you like for the `--home` option. On Unix, lazy typists can just type a tilde (`~`); the **install** command will expand this to your home directory: ``` python setup.py install --home=~ ``` To make Python find the distributions installed with this scheme, you may have to [modify Python’s search path](#inst-search-path) or edit `sitecustomize` (see [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.")) to call [`site.addsitedir()`](../library/site#site.addsitedir "site.addsitedir") or edit [`sys.path`](../library/sys#sys.path "sys.path"). The `--home` option defines the installation base directory. Files are installed to the following directories under the installation base as follows: | Type of file | Installation directory | | --- | --- | | modules | `*home*/lib/python` | | scripts | `*home*/bin` | | data | `*home*` | | C headers | `*home*/include/python/*distname*` | (Mentally replace slashes with backslashes if you’re on Windows.) ### Alternate installation: Unix (the prefix scheme) The “prefix scheme” is useful when you wish to use one Python installation to perform the build/install (i.e., to run the setup script), but install modules into the third-party module directory of a different Python installation (or something that looks like a different Python installation). If this sounds a trifle unusual, it is—that’s why the user and home schemes come before. However, there are at least two known cases where the prefix scheme will be useful. First, consider that many Linux distributions put Python in `/usr`, rather than the more traditional `/usr/local`. This is entirely appropriate, since in those cases Python is part of “the system” rather than a local add-on. However, if you are installing Python modules from source, you probably want them to go in `/usr/local/lib/python2.*X*` rather than `/usr/lib/python2.*X*`. This can be done with ``` /usr/bin/python setup.py install --prefix=/usr/local ``` Another possibility is a network filesystem where the name used to write to a remote directory is different from the name used to read it: for example, the Python interpreter accessed as `/usr/local/bin/python` might search for modules in `/usr/local/lib/python2.*X*`, but those modules would have to be installed to, say, `/mnt/*@server*/export/lib/python2.*X*`. This could be done with ``` /usr/local/bin/python setup.py install --prefix=/mnt/@server/export ``` In either case, the `--prefix` option defines the installation base, and the `--exec-prefix` option defines the platform-specific installation base, which is used for platform-specific files. (Currently, this just means non-pure module distributions, but could be expanded to C libraries, binary executables, etc.) If `--exec-prefix` is not supplied, it defaults to `--prefix`. Files are installed as follows: | Type of file | Installation directory | | --- | --- | | Python modules | `*prefix*/lib/python*X.Y*/site-packages` | | extension modules | `*exec-prefix*/lib/python*X.Y*/site-packages` | | scripts | `*prefix*/bin` | | data | `*prefix*` | | C headers | `*prefix*/include/python*X.Y**abiflags*/*distname*` | There is no requirement that `--prefix` or `--exec-prefix` actually point to an alternate Python installation; if the directories listed above do not already exist, they are created at installation time. Incidentally, the real reason the prefix scheme is important is simply that a standard Unix installation uses the prefix scheme, but with `--prefix` and `--exec-prefix` supplied by Python itself as `sys.prefix` and `sys.exec_prefix`. Thus, you might think you’ll never use the prefix scheme, but every time you run `python setup.py install` without any other options, you’re using it. Note that installing extensions to an alternate Python installation has no effect on how those extensions are built: in particular, the Python header files (`Python.h` and friends) installed with the Python interpreter used to run the setup script will be used in compiling extensions. It is your responsibility to ensure that the interpreter used to run extensions installed in this way is compatible with the interpreter used to build them. The best way to do this is to ensure that the two interpreters are the same version of Python (possibly different builds, or possibly copies of the same build). (Of course, if your `--prefix` and `--exec-prefix` don’t even point to an alternate Python installation, this is immaterial.) ### Alternate installation: Windows (the prefix scheme) Windows has no concept of a user’s home directory, and since the standard Python installation under Windows is simpler than under Unix, the `--prefix` option has traditionally been used to install additional packages in separate locations on Windows. ``` python setup.py install --prefix="\Temp\Python" ``` to install modules to the `\Temp\Python` directory on the current drive. The installation base is defined by the `--prefix` option; the `--exec-prefix` option is not supported under Windows, which means that pure Python modules and extension modules are installed into the same location. Files are installed as follows: | Type of file | Installation directory | | --- | --- | | modules | `*prefix*\Lib\site-packages` | | scripts | `*prefix*\Scripts` | | data | `*prefix*` | | C headers | `*prefix*\Include{distname}` | Custom Installation ------------------- Sometimes, the alternate installation schemes described in section [Alternate Installation](#inst-alt-install) just don’t do what you want. You might want to tweak just one or two directories while keeping everything under the same base directory, or you might want to completely redefine the installation scheme. In either case, you’re creating a *custom installation scheme*. To create a custom installation scheme, you start with one of the alternate schemes and override some of the installation directories used for the various types of files, using these options: | Type of file | Override option | | --- | --- | | Python modules | `--install-purelib` | | extension modules | `--install-platlib` | | all modules | `--install-lib` | | scripts | `--install-scripts` | | data | `--install-data` | | C headers | `--install-headers` | These override options can be relative, absolute, or explicitly defined in terms of one of the installation base directories. (There are two installation base directories, and they are normally the same—they only differ when you use the Unix “prefix scheme” and supply different `--prefix` and `--exec-prefix` options; using `--install-lib` will override values computed or given for `--install-purelib` and `--install-platlib`, and is recommended for schemes that don’t make a difference between Python and extension modules.) For example, say you’re installing a module distribution to your home directory under Unix—but you want scripts to go in `~/scripts` rather than `~/bin`. As you might expect, you can override this directory with the `--install-scripts` option; in this case, it makes most sense to supply a relative path, which will be interpreted relative to the installation base directory (your home directory, in this case): ``` python setup.py install --home=~ --install-scripts=scripts ``` Another Unix example: suppose your Python installation was built and installed with a prefix of `/usr/local/python`, so under a standard installation scripts will wind up in `/usr/local/python/bin`. If you want them in `/usr/local/bin` instead, you would supply this absolute directory for the `--install-scripts` option: ``` python setup.py install --install-scripts=/usr/local/bin ``` (This performs an installation using the “prefix scheme”, where the prefix is whatever your Python interpreter was installed with— `/usr/local/python` in this case.) If you maintain Python on Windows, you might want third-party modules to live in a subdirectory of `*prefix*`, rather than right in `*prefix*` itself. This is almost as easy as customizing the script installation directory—you just have to remember that there are two types of modules to worry about, Python and extension modules, which can conveniently be both controlled by one option: ``` python setup.py install --install-lib=Site ``` The specified installation directory is relative to `*prefix*`. Of course, you also have to ensure that this directory is in Python’s module search path, such as by putting a `.pth` file in a site directory (see [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.")). See section [Modifying Python’s Search Path](#inst-search-path) to find out how to modify Python’s search path. If you want to define an entire installation scheme, you just have to supply all of the installation directory options. The recommended way to do this is to supply relative paths; for example, if you want to maintain all Python module-related files under `python` in your home directory, and you want a separate directory for each platform that you use your home directory from, you might define the following installation scheme: ``` python setup.py install --home=~ \ --install-purelib=python/lib \ --install-platlib=python/lib.$PLAT \ --install-scripts=python/scripts --install-data=python/data ``` or, equivalently, ``` python setup.py install --home=~/python \ --install-purelib=lib \ --install-platlib='lib.$PLAT' \ --install-scripts=scripts --install-data=data ``` `$PLAT` is not (necessarily) an environment variable—it will be expanded by the Distutils as it parses your command line options, just as it does when parsing your configuration file(s). Obviously, specifying the entire installation scheme every time you install a new module distribution would be very tedious. Thus, you can put these options into your Distutils config file (see section [Distutils Configuration Files](#inst-config-files)): ``` [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data ``` or, equivalently, ``` [install] install-base=$HOME/python install-purelib=lib install-platlib=lib.$PLAT install-scripts=scripts install-data=data ``` Note that these two are *not* equivalent if you supply a different installation base directory when you run the setup script. For example, ``` python setup.py install --install-base=/tmp ``` would install pure modules to `/tmp/python/lib` in the first case, and to `/tmp/lib` in the second case. (For the second case, you probably want to supply an installation base of `/tmp/python`.) You probably noticed the use of `$HOME` and `$PLAT` in the sample configuration file input. These are Distutils configuration variables, which bear a strong resemblance to environment variables. In fact, you can use environment variables in config files on platforms that have such a notion but the Distutils additionally define a few extra variables that may not be in your environment, such as `$PLAT`. (And of course, on systems that don’t have environment variables, such as Mac OS 9, the configuration variables supplied by the Distutils are the only ones you can use.) See section [Distutils Configuration Files](#inst-config-files) for details. Note When a [virtual environment](../library/venv#venv-def) is activated, any options that change the installation path will be ignored from all distutils configuration files to prevent inadvertently installing projects outside of the virtual environment. ### Modifying Python’s Search Path When the Python interpreter executes an [`import`](../reference/simple_stmts#import) statement, it searches for both Python code and extension modules along a search path. A default value for the path is configured into the Python binary when the interpreter is built. You can determine the path by importing the [`sys`](../library/sys#module-sys "sys: Access system-specific parameters and functions.") module and printing the value of `sys.path`. ``` $ python Python 2.2 (#11, Oct 3 2002, 13:31:27) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages'] >>> ``` The null string in `sys.path` represents the current working directory. The expected convention for locally installed packages is to put them in the `*…*/site-packages/` directory, but you may want to install Python modules into some arbitrary directory. For example, your site may have a convention of keeping all software related to the web server under `/www`. Add-on Python modules might then belong in `/www/python`, and in order to import them, this directory must be added to `sys.path`. There are several different ways to add the directory. The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the `.../site-packages/` directory. Path configuration files have an extension of `.pth`, and each line must contain a single path that will be appended to `sys.path`. (Because the new paths are appended to `sys.path`, modules in the added directories will not override standard modules. This means you can’t use this mechanism for installing fixed versions of standard modules.) Paths can be absolute or relative, in which case they’re relative to the directory containing the `.pth` file. See the documentation of the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module for more information. A slightly less convenient way is to edit the `site.py` file in Python’s standard library, and modify `sys.path`. `site.py` is automatically imported when the Python interpreter is executed, unless the [`-S`](../using/cmdline#id3) switch is supplied to suppress this behaviour. So you could simply edit `site.py` and add two lines to it: ``` import sys sys.path.append('/www/python/') ``` However, if you reinstall the same major version of Python (perhaps when upgrading from 2.2 to 2.2.2, for example) `site.py` will be overwritten by the stock version. You’d have to remember that it was modified and save a copy before doing the installation. There are two environment variables that can modify `sys.path`. [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) sets an alternate value for the prefix of the Python installation. For example, if [`PYTHONHOME`](../using/cmdline#envvar-PYTHONHOME) is set to `/www/python`, the search path will be set to `['', '/www/python/lib/pythonX.Y/', '/www/python/lib/pythonX.Y/plat-linux2', ...]`. The [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) variable can be set to a list of paths that will be added to the beginning of `sys.path`. For example, if [`PYTHONPATH`](../using/cmdline#envvar-PYTHONPATH) is set to `/www/python:/opt/py`, the search path will begin with `['/www/python', '/opt/py']`. (Note that directories must exist in order to be added to `sys.path`; the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module removes paths that don’t exist.) Finally, `sys.path` is just a regular Python list, so any Python application can modify it by adding or removing entries. Distutils Configuration Files ----------------------------- As mentioned above, you can use Distutils configuration files to record personal or site preferences for any Distutils options. That is, any option to any command can be stored in one of two or three (depending on your platform) configuration files, which will be consulted before the command-line is parsed. This means that configuration files will override default values, and the command-line will in turn override configuration files. Furthermore, if multiple configuration files apply, values from “earlier” files are overridden by “later” files. ### Location and names of config files The names and locations of the configuration files vary slightly across platforms. On Unix and macOS, the three configuration files (in the order they are processed) are: | Type of file | Location and filename | Notes | | --- | --- | --- | | system | `*prefix*/lib/python*ver*/distutils/distutils.cfg` | (1) | | personal | `$HOME/.pydistutils.cfg` | (2) | | local | `setup.cfg` | (3) | And on Windows, the configuration files are: | Type of file | Location and filename | Notes | | --- | --- | --- | | system | `*prefix*\Lib\distutils\distutils.cfg` | (4) | | personal | `%HOME%\pydistutils.cfg` | (5) | | local | `setup.cfg` | (3) | On all platforms, the “personal” file can be temporarily disabled by passing the `–no-user-cfg` option. Notes: 1. Strictly speaking, the system-wide configuration file lives in the directory where the Distutils are installed; under Python 1.6 and later on Unix, this is as shown. For Python 1.5.2, the Distutils will normally be installed to `*prefix*/lib/python1.5/site-packages/distutils`, so the system configuration file should be put there under Python 1.5.2. 2. On Unix, if the `HOME` environment variable is not defined, the user’s home directory will be determined with the `getpwuid()` function from the standard [`pwd`](../library/pwd#module-pwd "pwd: The password database (getpwnam() and friends). (Unix)") module. This is done by the [`os.path.expanduser()`](../library/os.path#os.path.expanduser "os.path.expanduser") function used by Distutils. 3. I.e., in the current directory (usually the location of the setup script). 4. (See also note (1).) Under Python 1.6 and later, Python’s default “installation prefix” is `C:\Python`, so the system configuration file is normally `C:\Python\Lib\distutils\distutils.cfg`. Under Python 1.5.2, the default prefix was `C:\Program Files\Python`, and the Distutils were not part of the standard library—so the system configuration file would be `C:\Program Files\Python\distutils\distutils.cfg` in a standard Python 1.5.2 installation under Windows. 5. On Windows, if the `HOME` environment variable is not defined, `USERPROFILE` then `HOMEDRIVE` and `HOMEPATH` will be tried. This is done by the [`os.path.expanduser()`](../library/os.path#os.path.expanduser "os.path.expanduser") function used by Distutils. ### Syntax of config files The Distutils configuration files all have the same syntax. The config files are grouped into sections. There is one section for each Distutils command, plus a `global` section for global options that affect every command. Each section consists of one option per line, specified as `option=value`. For example, the following is a complete config file that just forces all commands to run quietly by default: ``` [global] verbose=0 ``` If this is installed as the system config file, it will affect all processing of any Python module distribution by any user on the current system. If it is installed as your personal config file (on systems that support them), it will affect only module distributions processed by you. And if it is used as the `setup.cfg` for a particular module distribution, it affects only that distribution. You could override the default “build base” directory and make the **build\*** commands always forcibly rebuild all files with the following: ``` [build] build-base=blib force=1 ``` which corresponds to the command-line arguments ``` python setup.py build --build-base=blib --force ``` except that including the **build** command on the command-line means that command will be run. Including a particular command in config files has no such implication; it only means that if the command is run, the options in the config file will apply. (Or if other commands that derive values from it are run, they will use the values in the config file.) You can find out the complete list of options for any command using the `--help` option, e.g.: ``` python setup.py build --help ``` and you can find out the complete list of global options by using `--help` without a command: ``` python setup.py --help ``` See also the “Reference” section of the “Distributing Python Modules” manual. Building Extensions: Tips and Tricks ------------------------------------ Whenever possible, the Distutils try to use the configuration information made available by the Python interpreter used to run the `setup.py` script. For example, the same compiler and linker flags used to compile Python will also be used for compiling extensions. Usually this will work well, but in complicated situations this might be inappropriate. This section discusses how to override the usual Distutils behaviour. ### Tweaking compiler/linker flags Compiling a Python extension written in C or C++ will sometimes require specifying custom flags for the compiler and linker in order to use a particular library or produce a special kind of object code. This is especially true if the extension hasn’t been tested on your platform, or if you’re trying to cross-compile Python. In the most general case, the extension author might have foreseen that compiling the extensions would be complicated, and provided a `Setup` file for you to edit. This will likely only be done if the module distribution contains many separate extension modules, or if they often require elaborate sets of compiler flags in order to work. A `Setup` file, if present, is parsed in order to get a list of extensions to build. Each line in a `Setup` describes a single module. Lines have the following structure: ``` module ... [sourcefile ...] [cpparg ...] [library ...] ``` Let’s examine each of the fields in turn. * *module* is the name of the extension module to be built, and should be a valid Python identifier. You can’t just change this in order to rename a module (edits to the source code would also be needed), so this should be left alone. * *sourcefile* is anything that’s likely to be a source code file, at least judging by the filename. Filenames ending in `.c` are assumed to be written in C, filenames ending in `.C`, `.cc`, and `.c++` are assumed to be C++, and filenames ending in `.m` or `.mm` are assumed to be in Objective C. * *cpparg* is an argument for the C preprocessor, and is anything starting with `-I`, `-D`, `-U` or `-C`. * *library* is anything ending in `.a` or beginning with `-l` or `-L`. If a particular platform requires a special library on your platform, you can add it by editing the `Setup` file and running `python setup.py build`. For example, if the module defined by the line ``` foo foomodule.c ``` must be linked with the math library `libm.a` on your platform, simply add `-lm` to the line: ``` foo foomodule.c -lm ``` Arbitrary switches intended for the compiler or the linker can be supplied with the `-Xcompiler` *arg* and `-Xlinker` *arg* options: ``` foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm ``` The next option after `-Xcompiler` and `-Xlinker` will be appended to the proper command line, so in the above example the compiler will be passed the `-o32` option, and the linker will be passed `-shared`. If a compiler option requires an argument, you’ll have to supply multiple `-Xcompiler` options; for example, to pass `-x c++` the `Setup` file would have to contain `-Xcompiler -x -Xcompiler c++`. Compiler flags can also be supplied through setting the `CFLAGS` environment variable. If set, the contents of `CFLAGS` will be added to the compiler flags specified in the `Setup` file. ### Using non-Microsoft compilers on Windows #### Borland/CodeGear C++ This subsection describes the necessary steps to use Distutils with the Borland C++ compiler version 5.5. First you have to know that Borland’s object file format (OMF) is different from the format used by the Python version you can download from the Python or ActiveState Web site. (Python is built with Microsoft Visual C++, which uses COFF as the object file format.) For this reason you have to convert Python’s library `python25.lib` into the Borland format. You can do this as follows: ``` coff2omf python25.lib python25_bcpp.lib ``` The `coff2omf` program comes with the Borland compiler. The file `python25.lib` is in the `Libs` directory of your Python installation. If your extension uses other libraries (zlib, …) you have to convert them too. The converted files have to reside in the same directories as the normal libraries. How does Distutils manage to use these libraries with their changed names? If the extension needs a library (eg. `foo`) Distutils checks first if it finds a library with suffix `_bcpp` (eg. `foo_bcpp.lib`) and then uses this library. In the case it doesn’t find such a special library it uses the default name (`foo.lib`.) [1](#id4) To let Distutils compile your extension with Borland C++ you now have to type: ``` python setup.py build --compiler=bcpp ``` If you want to use the Borland C++ compiler as the default, you could specify this in your personal or system-wide configuration file for Distutils (see section [Distutils Configuration Files](#inst-config-files).) See also [C++Builder Compiler](https://www.embarcadero.com/products) Information about the free C++ compiler from Borland, including links to the download pages. [Creating Python Extensions Using Borland’s Free Compiler](http://www.cyberus.ca/~g_will/pyExtenDL.shtml) Document describing how to use Borland’s free command-line C++ compiler to build Python. #### GNU C / Cygwin / MinGW This section describes the necessary steps to use Distutils with the GNU C/C++ compilers in their Cygwin and MinGW distributions. [2](#id5) For a Python interpreter that was built with Cygwin, everything should work without any of these following steps. Not all extensions can be built with MinGW or Cygwin, but many can. Extensions most likely to not work are those that use C++ or depend on Microsoft Visual C extensions. To let Distutils compile your extension with Cygwin you have to type: ``` python setup.py build --compiler=cygwin ``` and for Cygwin in no-cygwin mode [3](#id6) or for MinGW type: ``` python setup.py build --compiler=mingw32 ``` If you want to use any of these options/compilers as default, you should consider writing it in your personal or system-wide configuration file for Distutils (see section [Distutils Configuration Files](#inst-config-files).) ##### Older Versions of Python and MinGW The following instructions only apply if you’re using a version of Python inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with binutils-2.13.90-20030111-1). These compilers require some special libraries. This task is more complex than for Borland’s C++, because there is no program to convert the library. First you have to create a list of symbols which the Python DLL exports. (You can find a good program for this task at <https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/>). ``` pexports python25.dll >python25.def ``` The location of an installed `python25.dll` will depend on the installation options and the version and language of Windows. In a “just for me” installation, it will appear in the root of the installation directory. In a shared installation, it will be located in the system directory. Then you can create from these information an import library for gcc. ``` /cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a ``` The resulting library has to be placed in the same directory as `python25.lib`. (Should be the `libs` directory under your Python installation directory.) If your extension uses other libraries (zlib,…) you might have to convert them too. The converted files have to reside in the same directories as the normal libraries do. See also [Building Python modules on MS Windows platform with MinGW](http://old.zope.org/Members/als/tips/win32_mingw_modules) Information about building the required libraries for the MinGW environment. #### Footnotes `1` This also means you could replace all existing COFF-libraries with OMF-libraries of the same name. `2` Check <https://www.sourceware.org/cygwin/> for more information `3` Then you have no POSIX emulation available, but you also don’t need `cygwin1.dll`.
programming_docs
python Installing Python Modules Installing Python Modules ========================= Email [[email protected]](mailto:distutils-sig%40python.org) As a popular open source development project, Python has an active supporting community of contributors and users that also make their software available for other Python developers to use under open source license terms. This allows Python users to share and collaborate effectively, benefiting from the solutions others have already created to common (and sometimes even rare!) problems, as well as potentially contributing their own solutions to the common pool. This guide covers the installation part of the process. For a guide to creating and sharing your own Python projects, refer to the [distribution guide](../distributing/index#distributing-index). Note For corporate and other institutional users, be aware that many organisations have their own policies around using and contributing to open source software. Please take such policies into account when making use of the distribution and installation tools provided with Python. Key terms --------- * `pip` is the preferred installer program. Starting with Python 3.4, it is included by default with the Python binary installers. * A *virtual environment* is a semi-isolated Python environment that allows packages to be installed for use by a particular application, rather than being installed system wide. * `venv` is the standard tool for creating virtual environments, and has been part of Python since Python 3.3. Starting with Python 3.4, it defaults to installing `pip` into all created virtual environments. * `virtualenv` is a third party alternative (and predecessor) to `venv`. It allows virtual environments to be used on versions of Python prior to 3.4, which either don’t provide `venv` at all, or aren’t able to automatically install `pip` into created environments. * The [Python Package Index](https://pypi.org) is a public repository of open source licensed packages made available for use by other Python users. * the [Python Packaging Authority](https://www.pypa.io/) is the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation, and issue trackers on both [GitHub](https://github.com/pypa) and [Bitbucket](https://bitbucket.org/pypa/). * `distutils` is the original build and distribution system first added to the Python standard library in 1998. While direct use of `distutils` is being phased out, it still laid the foundation for the current packaging and distribution infrastructure, and it not only remains part of the standard library, but its name lives on in other ways (such as the name of the mailing list used to coordinate Python packaging standards development). Changed in version 3.5: The use of `venv` is now recommended for creating virtual environments. See also [Python Packaging User Guide: Creating and using virtual environments](https://packaging.python.org/installing/#creating-virtual-environments) Basic usage ----------- The standard packaging tools are all designed to be used from the command line. The following command will install the latest version of a module and its dependencies from the Python Package Index: ``` python -m pip install SomePackage ``` Note For POSIX users (including macOS and Linux users), the examples in this guide assume the use of a [virtual environment](../glossary#term-virtual-environment). For Windows users, the examples in this guide assume that the option to adjust the system PATH environment variable was selected when installing Python. It’s also possible to specify an exact or minimum version directly on the command line. When using comparator operators such as `>`, `<` or some other special character which get interpreted by shell, the package name and the version should be enclosed within double quotes: ``` python -m pip install SomePackage==1.0.4 # specific version python -m pip install "SomePackage>=1.0.4" # minimum version ``` Normally, if a suitable module is already installed, attempting to install it again will have no effect. Upgrading existing modules must be requested explicitly: ``` python -m pip install --upgrade SomePackage ``` More information and resources regarding `pip` and its capabilities can be found in the [Python Packaging User Guide](https://packaging.python.org). Creation of virtual environments is done through the [`venv`](../library/venv#module-venv "venv: Creation of virtual environments.") module. Installing packages into an active virtual environment uses the commands shown above. See also [Python Packaging User Guide: Installing Python Distribution Packages](https://packaging.python.org/installing/) How do I …? ----------- These are quick answers or links for some common tasks. ### … install `pip` in versions of Python prior to Python 3.4? Python only started bundling `pip` with Python 3.4. For earlier versions, `pip` needs to be “bootstrapped” as described in the Python Packaging User Guide. See also [Python Packaging User Guide: Requirements for Installing Packages](https://packaging.python.org/installing/#requirements-for-installing-packages) ### … install packages just for the current user? Passing the `--user` option to `python -m pip install` will install a package just for the current user, rather than for all users of the system. ### … install scientific Python packages? A number of scientific Python packages have complex binary dependencies, and aren’t currently easy to install using `pip` directly. At this point in time, it will often be easier for users to install these packages by [other means](https://packaging.python.org/science/) rather than attempting to install them with `pip`. See also [Python Packaging User Guide: Installing Scientific Packages](https://packaging.python.org/science/) ### … work with multiple versions of Python installed in parallel? On Linux, macOS, and other POSIX systems, use the versioned Python commands in combination with the `-m` switch to run the appropriate copy of `pip`: ``` python2 -m pip install SomePackage # default Python 2 python2.7 -m pip install SomePackage # specifically Python 2.7 python3 -m pip install SomePackage # default Python 3 python3.4 -m pip install SomePackage # specifically Python 3.4 ``` Appropriately versioned `pip` commands may also be available. On Windows, use the `py` Python launcher in combination with the `-m` switch: ``` py -2 -m pip install SomePackage # default Python 2 py -2.7 -m pip install SomePackage # specifically Python 2.7 py -3 -m pip install SomePackage # default Python 3 py -3.4 -m pip install SomePackage # specifically Python 3.4 ``` Common installation issues -------------------------- ### Installing into the system Python on Linux On Linux systems, a Python installation will typically be included as part of the distribution. Installing into this Python installation requires root access to the system, and may interfere with the operation of the system package manager and other components of the system if a component is unexpectedly upgraded using `pip`. On such systems, it is often better to use a virtual environment or a per-user installation when installing packages with `pip`. ### Pip not installed It is possible that `pip` does not get installed by default. One potential fix is: ``` python -m ensurepip --default-pip ``` There are also additional resources for [installing pip.](https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel) ### Installing binary extensions Python has typically relied heavily on source based distribution, with end users being expected to compile extension modules from source as part of the installation process. With the introduction of support for the binary `wheel` format, and the ability to publish wheels for at least Windows and macOS through the Python Package Index, this problem is expected to diminish over time, as users are more regularly able to install pre-built extensions rather than needing to build them themselves. Some of the solutions for installing [scientific software](https://packaging.python.org/science/) that are not yet available as pre-built `wheel` files may also help with obtaining other binary extensions without needing to build them locally. See also [Python Packaging User Guide: Binary Extensions](https://packaging.python.org/extensions/) python Design and History FAQ Design and History FAQ ====================== * [Why does Python use indentation for grouping of statements?](#why-does-python-use-indentation-for-grouping-of-statements) * [Why am I getting strange results with simple arithmetic operations?](#why-am-i-getting-strange-results-with-simple-arithmetic-operations) * [Why are floating-point calculations so inaccurate?](#why-are-floating-point-calculations-so-inaccurate) * [Why are Python strings immutable?](#why-are-python-strings-immutable) * [Why must ‘self’ be used explicitly in method definitions and calls?](#why-must-self-be-used-explicitly-in-method-definitions-and-calls) * [Why can’t I use an assignment in an expression?](#why-can-t-i-use-an-assignment-in-an-expression) * [Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?](#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list) * [Why is join() a string method instead of a list or tuple method?](#why-is-join-a-string-method-instead-of-a-list-or-tuple-method) * [How fast are exceptions?](#how-fast-are-exceptions) * [Why isn’t there a switch or case statement in Python?](#why-isn-t-there-a-switch-or-case-statement-in-python) * [Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?](#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation) * [Why can’t lambda expressions contain statements?](#why-can-t-lambda-expressions-contain-statements) * [Can Python be compiled to machine code, C or some other language?](#can-python-be-compiled-to-machine-code-c-or-some-other-language) * [How does Python manage memory?](#how-does-python-manage-memory) * [Why doesn’t CPython use a more traditional garbage collection scheme?](#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme) * [Why isn’t all memory freed when CPython exits?](#why-isn-t-all-memory-freed-when-cpython-exits) * [Why are there separate tuple and list data types?](#why-are-there-separate-tuple-and-list-data-types) * [How are lists implemented in CPython?](#how-are-lists-implemented-in-cpython) * [How are dictionaries implemented in CPython?](#how-are-dictionaries-implemented-in-cpython) * [Why must dictionary keys be immutable?](#why-must-dictionary-keys-be-immutable) * [Why doesn’t list.sort() return the sorted list?](#why-doesn-t-list-sort-return-the-sorted-list) * [How do you specify and enforce an interface spec in Python?](#how-do-you-specify-and-enforce-an-interface-spec-in-python) * [Why is there no goto?](#why-is-there-no-goto) * [Why can’t raw strings (r-strings) end with a backslash?](#why-can-t-raw-strings-r-strings-end-with-a-backslash) * [Why doesn’t Python have a “with” statement for attribute assignments?](#why-doesn-t-python-have-a-with-statement-for-attribute-assignments) * [Why don’t generators support the with statement?](#why-don-t-generators-support-the-with-statement) * [Why are colons required for the if/while/def/class statements?](#why-are-colons-required-for-the-if-while-def-class-statements) * [Why does Python allow commas at the end of lists and tuples?](#why-does-python-allow-commas-at-the-end-of-lists-and-tuples) Why does Python use indentation for grouping of statements? ----------------------------------------------------------- Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program. Most people learn to love this feature after a while. Since there are no begin/end brackets there cannot be a disagreement between grouping perceived by the parser and the human reader. Occasionally C programmers will encounter a fragment of code like this: ``` if (x <= y) x++; y--; z++; ``` Only the `x++` statement is executed if the condition is true, but the indentation leads many to believe otherwise. Even experienced C programmers will sometimes stare at it a long time wondering as to why `y` is being decremented even for `x > y`. Because there are no begin/end brackets, Python is much less prone to coding-style conflicts. In C there are many different ways to place the braces. After becoming used to reading and writing code using a particular style, it is normal to feel somewhat uneasy when reading (or being required to write) in a different one. Many coding styles place begin/end brackets on a line by themselves. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program. Ideally, a function should fit on one screen (say, 20–30 lines). 20 lines of Python can do a lot more work than 20 lines of C. This is not solely due to the lack of begin/end brackets – the lack of declarations and the high-level data types are also responsible – but the indentation-based syntax certainly helps. Why am I getting strange results with simple arithmetic operations? ------------------------------------------------------------------- See the next question. Why are floating-point calculations so inaccurate? -------------------------------------------------- Users are often surprised by results like this: ``` >>> 1.2 - 1.0 0.19999999999999996 ``` and think it is a bug in Python. It’s not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers. The [`float`](../library/functions#float "float") type in CPython uses a C `double` for storage. A [`float`](../library/functions#float "float") object’s value is stored in binary floating-point with a fixed precision (typically 53 bits) and Python uses C operations, which in turn rely on the hardware implementation in the processor, to perform floating-point operations. This means that as far as floating-point operations are concerned, Python behaves like many popular languages including C and Java. Many numbers that can be written easily in decimal notation cannot be expressed exactly in binary floating-point. For example, after: ``` >>> x = 1.2 ``` the value stored for `x` is a (very good) approximation to the decimal value `1.2`, but is not exactly equal to it. On a typical machine, the actual stored value is: ``` 1.0011001100110011001100110011001100110011001100110011 (binary) ``` which is exactly: ``` 1.1999999999999999555910790149937383830547332763671875 (decimal) ``` The typical precision of 53 bits provides Python floats with 15–16 decimal digits of accuracy. For a fuller explanation, please see the [floating point arithmetic](../tutorial/floatingpoint#tut-fp-issues) chapter in the Python tutorial. Why are Python strings immutable? --------------------------------- There are several advantages. One is performance: knowing that a string is immutable means we can allocate space for it at creation time, and the storage requirements are fixed and unchanging. This is also one of the reasons for the distinction between tuples and lists. Another advantage is that strings in Python are considered as “elemental” as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else. Why must ‘self’ be used explicitly in method definitions and calls? ------------------------------------------------------------------- The idea was borrowed from Modula-3. It turns out to be very useful, for a variety of reasons. First, it’s more obvious that you are using a method or instance attribute instead of a local variable. Reading `self.x` or `self.meth()` makes it absolutely clear that an instance variable or method is used even if you don’t know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or easily recognizable) – but in Python, there are no local variable declarations, so you’d have to look up the class definition to be sure. Some C++ and Java coding standards call for instance attributes to have an `m_` prefix, so this explicitness is still useful in those languages, too. Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class. In C++, if you want to use a method from a base class which is overridden in a derived class, you have to use the `::` operator – in Python you can write `baseclass.methodname(self, <argument list>)`. This is particularly useful for [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") methods, and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehow. Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value is assigned in a function body (and that aren’t explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn’t have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit `self.var` solves this nicely. Similarly, for using instance variables, having to write `self.var` means that references to unqualified names inside a method don’t have to search the instance’s directories. To put it another way, local variables and instance variables live in two different namespaces, and you need to tell Python which namespace to use. Why can’t I use an assignment in an expression? ----------------------------------------------- Starting in Python 3.8, you can! Assignment expressions using the walrus operator `:=` assign a variable in an expression: ``` while chunk := fp.read(200): print(chunk) ``` See [**PEP 572**](https://www.python.org/dev/peps/pep-0572) for more information. Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))? ---------------------------------------------------------------------------------------------------------------- As Guido said: (a) For some operations, prefix notation just reads better than postfix – prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x\*(a+b) into x\*a + x\*b to the clumsiness of doing the same thing using a raw OO notation. (b) When I read code that says len(x) I *know* that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method. —<https://mail.python.org/pipermail/python-3000/2006-November/004643.html> Why is join() a string method instead of a list or tuple method? ---------------------------------------------------------------- Strings became much more like other standard types starting in Python 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. Most of these new methods have been widely accepted, but the one which appears to make some programmers feel uncomfortable is: ``` ", ".join(['1', '2', '4', '8', '16']) ``` which gives the result: ``` "1, 2, 4, 8, 16" ``` There are two common arguments against this usage. The first runs along the lines of: “It looks really ugly using a method of a string literal (string constant)”, to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals. The second objection is typically cast as: “I am really telling a sequence to join its members together with a string constant”. Sadly, you aren’t. For some reason there seems to be much less difficulty with having [`split()`](../library/stdtypes#str.split "str.split") as a string method, since in that case it is easy to see that ``` "1, 2, 4, 8, 16".split(", ") ``` is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). [`join()`](../library/stdtypes#str.join "str.join") is a string method because in using it you are telling the separator string to iterate over a sequence of strings and insert itself between adjacent elements. This method can be used with any argument which obeys the rules for sequence objects, including any new classes you might define yourself. Similar methods exist for bytes and bytearray objects. How fast are exceptions? ------------------------ A try/except block is extremely efficient if no exceptions are raised. Actually catching an exception is expensive. In versions of Python prior to 2.0 it was common to use this idiom: ``` try: value = mydict[key] except KeyError: mydict[key] = getvalue(key) value = mydict[key] ``` This only made sense when you expected the dict to have the key almost all the time. If that wasn’t the case, you coded it like this: ``` if key in mydict: value = mydict[key] else: value = mydict[key] = getvalue(key) ``` For this specific case, you could also use `value = dict.setdefault(key, getvalue(key))`, but only if the `getvalue()` call is cheap enough because it is evaluated in all cases. Why isn’t there a switch or case statement in Python? ----------------------------------------------------- You can do this easily enough with a sequence of `if... elif... elif... else`. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See [**PEP 275**](https://www.python.org/dev/peps/pep-0275) for complete details and the current status. For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example: ``` functions = {'a': function_1, 'b': function_2, 'c': self.method_1} func = functions[value] func() ``` For calling methods on objects, you can simplify yet further by using the [`getattr()`](../library/functions#getattr "getattr") built-in to retrieve methods with a particular name: ``` class MyVisitor: def visit_a(self): ... def dispatch(self, value): method_name = 'visit_' + str(value) method = getattr(self, method_name) method() ``` It’s suggested that you use a prefix for the method names, such as `visit_` in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object. Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation? -------------------------------------------------------------------------------------------------------- Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for each Python stack frame. Also, extensions can call back into Python at almost random moments. Therefore, a complete threads implementation requires thread support for C. Answer 2: Fortunately, there is [Stackless Python](https://github.com/stackless-dev/stackless/wiki), which has a completely redesigned interpreter loop that avoids the C stack. Why can’t lambda expressions contain statements? ------------------------------------------------ Python lambda expressions cannot contain statements because Python’s syntactic framework can’t handle statements nested inside expressions. However, in Python, this is not a serious problem. Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function. Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda instead of a locally-defined function is that you don’t need to invent a name for the function – but that’s just a local variable to which the function object (which is exactly the same type of object that a lambda expression yields) is assigned! Can Python be compiled to machine code, C or some other language? ----------------------------------------------------------------- [Cython](http://cython.org/) compiles a modified version of Python with optional annotations into C extensions. [Nuitka](http://www.nuitka.net/) is an up-and-coming compiler of Python into C++ code, aiming to support the full Python language. For compiling to Java you can consider [VOC](https://voc.readthedocs.io). How does Python manage memory? ------------------------------ The details of Python memory management depend on the implementation. The standard implementation of Python, [CPython](../glossary#term-cpython), uses reference counting to detect inaccessible objects, and another mechanism to collect reference cycles, periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. The [`gc`](../library/gc#module-gc "gc: Interface to the cycle-detecting garbage collector.") module provides functions to perform a garbage collection, obtain debugging statistics, and tune the collector’s parameters. Other implementations (such as [Jython](http://www.jython.org) or [PyPy](http://www.pypy.org)), however, can rely on a different mechanism such as a full-blown garbage collector. This difference can cause some subtle porting problems if your Python code depends on the behavior of the reference counting implementation. In some Python implementations, the following code (which is fine in CPython) will probably run out of file descriptors: ``` for file in very_long_list_of_files: f = open(file) c = f.read(1) ``` Indeed, using CPython’s reference counting and destructor scheme, each new assignment to *f* closes the previous file. With a traditional GC, however, those file objects will only get collected (and closed) at varying and possibly long intervals. If you want to write code that will work with any Python implementation, you should explicitly close the file or use the [`with`](../reference/compound_stmts#with) statement; this will work regardless of memory management scheme: ``` for file in very_long_list_of_files: with open(file) as f: c = f.read(1) ``` Why doesn’t CPython use a more traditional garbage collection scheme? --------------------------------------------------------------------- For one thing, this is not a C standard feature and hence it’s not portable. (Yes, we know about the Boehm GC library. It has bits of assembler code for *most* common platforms, not for all of them, and although it is mostly transparent, it isn’t completely transparent; patches are required to get Python to work with it.) Traditional GC also becomes a problem when Python is embedded into other applications. While in a standalone Python it’s fine to replace the standard malloc() and free() with versions provided by the GC library, an application embedding Python may want to have its *own* substitute for malloc() and free(), and may not want Python’s. Right now, CPython works with anything that implements malloc() and free() properly. Why isn’t all memory freed when CPython exits? ---------------------------------------------- Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object. If you want to force Python to delete certain things on deallocation use the [`atexit`](../library/atexit#module-atexit "atexit: Register and execute cleanup functions.") module to run a function that will force those deletions. Why are there separate tuple and list data types? ------------------------------------------------- Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they’re small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, `os.listdir('.')` returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory. Tuples are immutable, meaning that once a tuple has been created, you can’t replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list’s elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys. How are lists implemented in CPython? ------------------------------------- CPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure. This makes indexing a list `a[i]` an operation whose cost is independent of the size of the list or the value of the index. When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize. How are dictionaries implemented in CPython? -------------------------------------------- CPython’s dictionaries are implemented as resizable hash tables. Compared to B-trees, this gives better performance for lookup (the most common operation by far) under most circumstances, and the implementation is simpler. Dictionaries work by computing a hash code for each key stored in the dictionary using the [`hash()`](../library/functions#hash "hash") built-in function. The hash code varies widely depending on the key and a per-process seed; for example, “Python” could hash to -539294296 while “python”, a string that differs by a single bit, could hash to 1142331976. The hash code is then used to calculate a location in an internal array where the value will be stored. Assuming that you’re storing keys that all have different hash values, this means that dictionaries take constant time – O(1), in Big-O notation – to retrieve a key. Why must dictionary keys be immutable? -------------------------------------- The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key. If the key were a mutable object, its value could change, and thus its hash could also change. But since whoever changes the key object can’t tell that it was being used as a dictionary key, it can’t move the entry around in the dictionary. Then, when you try to look up the same object in the dictionary it won’t be found because its hash value is different. If you tried to look up the old value it wouldn’t be found either, because the value of the object found in that hash bin would be different. If you want a dictionary indexed with a list, simply convert the list to a tuple first; the function `tuple(L)` creates a tuple with the same entries as the list `L`. Tuples are immutable and can therefore be used as dictionary keys. Some unacceptable solutions that have been proposed: * Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.: ``` mydict = {[1, 2]: '12'} print(mydict[[1, 2]]) ``` would raise a [`KeyError`](../library/exceptions#KeyError "KeyError") exception because the id of the `[1, 2]` used in the second line differs from that in the first line. In other words, dictionary keys should be compared using `==`, not using [`is`](../reference/expressions#is). * Make a copy when using a list as a key. This doesn’t work because the list, being a mutable object, could contain a reference to itself, and then the copying code would run into an infinite loop. * Allow lists as keys but tell the user not to modify them. This would allow a class of hard-to-track bugs in programs when you forgot or modified a list by accident. It also invalidates an important invariant of dictionaries: every value in `d.keys()` is usable as a key of the dictionary. * Mark lists as read-only once they are used as a dictionary key. The problem is that it’s not just the top-level object that could change its value; you could use a tuple containing a list as a key. Entering anything as a key into a dictionary would require marking all objects reachable from there as read-only – and again, self-referential objects could cause an infinite loop. There is a trick to get around this if you need to, but use it at your own risk: You can wrap a mutable structure inside a class instance which has both a [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__") and a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method. You must then make sure that the hash value for all such wrapper objects that reside in a dictionary (or other hash based structure), remain fixed while the object is in the dictionary (or other structure). ``` class ListWrapper: def __init__(self, the_list): self.the_list = the_list def __eq__(self, other): return self.the_list == other.the_list def __hash__(self): l = self.the_list result = 98767 - len(l)*555 for i, el in enumerate(l): try: result = result + (hash(el) % 9999999) * 1001 + i except Exception: result = (result % 7777777) + i * 333 return result ``` Note that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflow. Furthermore it must always be the case that if `o1 == o2` (ie `o1.__eq__(o2) is True`) then `hash(o1) == hash(o2)` (ie, `o1.__hash__() == o2.__hash__()`), regardless of whether the object is in a dictionary or not. If you fail to meet these restrictions dictionaries and other hash based structures will misbehave. In the case of ListWrapper, whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies. Don’t do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly. Consider yourself warned. Why doesn’t list.sort() return the sorted list? ----------------------------------------------- In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, [`list.sort()`](../library/stdtypes#list.sort "list.sort") sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around. If you want to return a new list, use the built-in [`sorted()`](../library/functions#sorted "sorted") function instead. This function creates a new list from a provided iterable, sorts it and returns it. For example, here’s how to iterate over the keys of a dictionary in sorted order: ``` for key in sorted(mydict): ... # do whatever with mydict[key]... ``` How do you specify and enforce an interface spec in Python? ----------------------------------------------------------- An interface specification for a module as provided by languages such as C++ and Java describes the prototypes for the methods and functions of the module. Many feel that compile-time enforcement of interface specifications helps in the construction of large programs. Python 2.6 adds an [`abc`](../library/abc#module-abc "abc: Abstract base classes according to :pep:`3119`.") module that lets you define Abstract Base Classes (ABCs). You can then use [`isinstance()`](../library/functions#isinstance "isinstance") and [`issubclass()`](../library/functions#issubclass "issubclass") to check whether an instance or a class implements a particular ABC. The [`collections.abc`](../library/collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") module defines a set of useful ABCs such as [`Iterable`](../library/collections.abc#collections.abc.Iterable "collections.abc.Iterable"), [`Container`](../library/collections.abc#collections.abc.Container "collections.abc.Container"), and [`MutableMapping`](../library/collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping"). For Python, many of the advantages of interface specifications can be obtained by an appropriate test discipline for components. A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple “self test.” Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface. The [`doctest`](../library/doctest#module-doctest "doctest: Test pieces of code within docstrings.") and [`unittest`](../library/unittest#module-unittest "unittest: Unit testing framework for Python.") modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module. An appropriate testing discipline can help build large complex applications in Python as well as having interface specifications would. In fact, it can be better because an interface specification cannot test certain properties of a program. For example, the `append()` method is expected to add new elements to the end of some internal list; an interface specification cannot test that your `append()` implementation will actually do this correctly, but it’s trivial to check this property in a test suite. Writing test suites is very helpful, and you might want to design your code to make it easily tested. One increasingly popular technique, test-driven development, calls for writing parts of the test suite first, before you write any of the actual code. Of course Python allows you to be sloppy and not write test cases at all. Why is there no goto? --------------------- In the 1970s people realized that unrestricted goto could lead to messy “spaghetti” code that was hard to understand and revise. In a high-level language, it is also unneeded as long as there are ways to branch (in Python, with `if` statements and `or`, `and`, and `if-else` expressions) and loop (with `while` and `for` statements, possibly containing `continue` and `break`). One can also use exceptions to provide a “structured goto” that works even across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the “go” or “goto” constructs of C, Fortran, and other languages. For example: ``` class label(Exception): pass # declare a label try: ... if condition: raise label() # goto label ... except label: # where to goto pass ... ``` This doesn’t allow you to jump into the middle of a loop, but that’s usually considered an abuse of goto anyway. Use sparingly. Why can’t raw strings (r-strings) end with a backslash? ------------------------------------------------------- More precisely, they can’t end with an odd number of backslashes: the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string. Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose. If you’re trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: ``` f = open("/mydir/file.txt") # works fine! ``` If you’re trying to build a pathname for a DOS command, try e.g. one of ``` dir = r"\this\is\my\dos\dir" "\\" dir = r"\this\is\my\dos\dir\ "[:-1] dir = "\\this\\is\\my\\dos\\dir\\" ``` Why doesn’t Python have a “with” statement for attribute assignments? --------------------------------------------------------------------- Python has a ‘with’ statement that wraps the execution of a block, calling code on the entrance and exit from the block. Some languages have a construct that looks like this: ``` with obj: a = 1 # equivalent to obj.a = 1 total = total + 1 # obj.total = obj.total + 1 ``` In Python, such a construct would be ambiguous. Other languages, such as Object Pascal, Delphi, and C++, use static types, so it’s possible to know, in an unambiguous way, what member is being assigned to. This is the main point of static typing – the compiler *always* knows the scope of every variable at compile time. Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This makes it impossible to know, from a simple reading, what attribute is being referenced: a local one, a global one, or a member attribute? For instance, take the following incomplete snippet: ``` def foo(a): with a: print(x) ``` The snippet assumes that “a” must have a member attribute called “x”. However, there is nothing in Python that tells the interpreter this. What should happen if “a” is, let us say, an integer? If there is a global variable named “x”, will it be used inside the with block? As you see, the dynamic nature of Python makes such choices much harder. The primary benefit of “with” and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of: ``` function(args).mydict[index][index].a = 21 function(args).mydict[index][index].b = 42 function(args).mydict[index][index].c = 63 ``` write this: ``` ref = function(args).mydict[index][index] ref.a = 21 ref.b = 42 ref.c = 63 ``` This also has the side-effect of increasing execution speed because name bindings are resolved at run-time in Python, and the second version only needs to perform the resolution once. Why don’t generators support the with statement? ------------------------------------------------ For technical reasons, a generator used directly as a context manager would not work correctly. When, as is most common, a generator is used as an iterator run to completion, no closing is needed. When it is, wrap it as “contextlib.closing(generator)” in the ‘with’ statement. Why are colons required for the if/while/def/class statements? -------------------------------------------------------------- The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this: ``` if a == b print(a) ``` versus ``` if a == b: print(a) ``` Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English. Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text. Why does Python allow commas at the end of lists and tuples? ------------------------------------------------------------ Python lets you add a trailing comma at the end of lists, tuples, and dictionaries: ``` [1, 2, 3,] ('a', 'b', 'c',) d = { "A": [1, 5], "B": [6, 7], # last trailing comma is optional but good style } ``` There are several reasons to allow this. When you have a literal value for a list, tuple, or dictionary spread across multiple lines, it’s easier to add more elements because you don’t have to remember to add a comma to the previous line. The lines can also be reordered without creating a syntax error. Accidentally omitting the comma can lead to errors that are hard to diagnose. For example: ``` x = [ "fee", "fie" "foo", "fum" ] ``` This list looks like it has four elements, but it actually contains three: “fee”, “fiefoo” and “fum”. Always adding the comma avoids this source of error. Allowing the trailing comma may also make programmatic code generation easier.
programming_docs
python Python Frequently Asked Questions Python Frequently Asked Questions ================================= * [General Python FAQ](general) * [Programming FAQ](programming) * [Design and History FAQ](design) * [Library and Extension FAQ](library) * [Extending/Embedding FAQ](extending) * [Python on Windows FAQ](windows) * [Graphic User Interface FAQ](gui) * [“Why is Python Installed on my Computer?” FAQ](installed) python Python on Windows FAQ Python on Windows FAQ ===================== * [How do I run a Python program under Windows?](#how-do-i-run-a-python-program-under-windows) * [How do I make Python scripts executable?](#how-do-i-make-python-scripts-executable) * [Why does Python sometimes take so long to start?](#why-does-python-sometimes-take-so-long-to-start) * [How do I make an executable from a Python script?](#how-do-i-make-an-executable-from-a-python-script) * [Is a `*.pyd` file the same as a DLL?](#is-a-pyd-file-the-same-as-a-dll) * [How can I embed Python into a Windows application?](#how-can-i-embed-python-into-a-windows-application) * [How do I keep editors from inserting tabs into my Python source?](#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source) * [How do I check for a keypress without blocking?](#how-do-i-check-for-a-keypress-without-blocking) How do I run a Python program under Windows? -------------------------------------------- This is not necessarily a straightforward question. If you are already familiar with running programs from the Windows command line then everything will seem obvious; otherwise, you might need a little more guidance. Unless you use some sort of integrated development environment, you will end up *typing* Windows commands into what is referred to as a “Command prompt window”. Usually you can create such a window from your search bar by searching for `cmd`. You should be able to recognize when you have started such a window because you will see a Windows “command prompt”, which usually looks like this: ``` C:\> ``` The letter may be different, and there might be other things after it, so you might just as easily see something like: ``` D:\YourName\Projects\Python> ``` depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs. You need to realize that your Python scripts have to be processed by another program called the Python *interpreter*. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python? First, you need to make sure that your command window recognises the word “py” as an instruction to start the interpreter. If you have opened a command window, you should try entering the command `py` and hitting return: ``` C:\Users\YourName> py ``` You should then see something like: ``` Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ``` You have started the interpreter in “interactive mode”. That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python’s strongest features. Check it by entering a few expressions of your choice and seeing the results: ``` >>> print("Hello") Hello >>> "Hello" * 3 'HelloHelloHello' ``` Many people use the interactive mode as a convenient yet highly programmable calculator. When you want to end your interactive Python session, call the [`exit()`](../library/constants#exit "exit") function or hold the `Ctrl` key down while you enter a `Z`, then hit the “`Enter`” key to get back to your Windows command prompt. You may also find that you have a Start-menu entry such as Start ‣ Programs ‣ Python 3.x ‣ Python (command line) that results in you seeing the `>>>` prompt in a new window. If so, the window will disappear after you call the [`exit()`](../library/constants#exit "exit") function or enter the `Ctrl-Z` character; Windows is running a single “python” command in the window, and closes it when you terminate the interpreter. Now that we know the `py` command is recognized, you can give your Python script to it. You’ll have to give either an absolute or a relative path to the Python script. Let’s say your Python script is located in your desktop and is named `hello.py`, and your command prompt is nicely opened in your home directory so you’re seeing something similar to: ``` C:\Users\YourName> ``` So now you’ll ask the `py` command to give your script to Python by typing `py` followed by your script path: ``` C:\Users\YourName> py Desktop\hello.py hello ``` How do I make Python scripts executable? ---------------------------------------- On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (`D:\Program Files\Python\python.exe "%1" %*`). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable. Why does Python sometimes take so long to start? ------------------------------------------------ Usually Python starts very quickly on Windows, but occasionally there are bug reports that Python suddenly begins to take a long time to start up. This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identically. The problem may be caused by a misconfiguration of virus checking software on the problem machine. Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem. Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically. McAfee, when configured to scan all file system read activity, is a particular offender. How do I make an executable from a Python script? ------------------------------------------------- See [How can I create a stand-alone binary from a Python script?](programming#faq-create-standalone-binary) for a list of tools that can be used to make executables. Is a `*.pyd` file the same as a DLL? ------------------------------------ Yes, .pyd files are dll’s, but there are a few differences. If you have a DLL named `foo.pyd`, then it must have a function `PyInit_foo()`. You can then write Python “import foo”, and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call `PyInit_foo()` to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present. Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say `import foo`. In a DLL, linkage is declared in the source code with `__declspec(dllexport)`. In a .pyd, linkage is defined in a list of available functions. How can I embed Python into a Windows application? -------------------------------------------------- Embedding the Python interpreter in a Windows app can be summarized as follows: 1. Do \_not\_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key undocumented fact.) Instead, link to `python*NN*.dll`; it is typically installed in `C:\Windows\System`. *NN* is the Python version, a number such as “33” for Python 3.3. You can link to Python in two different ways. Load-time linking means linking against `python*NN*.lib`, while run-time linking means linking against `python*NN*.dll`. (General note: `python*NN*.lib` is the so-called “import lib” corresponding to `python*NN*.dll`. It merely defines symbols for the linker.) Run-time linking greatly simplifies link options; everything happens at run time. Your code must load `python*NN*.dll` using the Windows `LoadLibraryEx()` routine. The code must also use access routines and data in `python*NN*.dll` (that is, Python’s C API’s) using pointers obtained by the Windows `GetProcAddress()` routine. Macros can make using these pointers transparent to any C code that calls routines in Python’s C API. 2. If you use SWIG, it is easy to create a Python “extension module” that will make the app’s data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link *into* your .exe file (!) You do \_not\_ have to create a DLL file, and this also simplifies linking. 3. SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class. The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.) 4. In short, you can use the following code to initialize the Python interpreter with your extension module. ``` #include "python.h" ... Py_Initialize(); // Initialize Python. initmyAppc(); // Initialize (import) the helper class. PyRun_SimpleString("import myApp"); // Import the shadow class. ``` 5. There are two problems with Python’s C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll. Problem 1: The so-called “Very High Level” functions that take FILE \* arguments will not work in a multi-compiler environment because each compiler’s notion of a struct FILE will be different. From an implementation standpoint these are very \_low\_ level functions. Problem 2: SWIG generates the following code when generating wrappers to void functions: ``` Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; ``` Alas, Py\_None is a macro that expands to a reference to a complex data structure called \_Py\_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by: ``` return Py_BuildValue(""); ``` It may be possible to use SWIG’s `%typemap` command to make the change automatically, though I have not been able to get this to work (I’m a complete SWIG newbie). 6. Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app’s windowing system. Rather, you (or the wxPythonWindow class) should create a “native” interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python’s i/o to \_any\_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods. How do I keep editors from inserting tabs into my Python source? ---------------------------------------------------------------- The FAQ does not recommend using tabs, and the Python style guide, [**PEP 8**](https://www.python.org/dev/peps/pep-0008), recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default. Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools ‣ Options ‣ Tabs, and for file type “Default” set “Tab size” and “Indent size” to 4, and select the “Insert spaces” radio button. Python raises [`IndentationError`](../library/exceptions#IndentationError "IndentationError") or [`TabError`](../library/exceptions#TabError "TabError") if mixed tabs and spaces are causing problems in leading whitespace. You may also run the [`tabnanny`](../library/tabnanny#module-tabnanny "tabnanny: Tool for detecting white space related problems in Python source files in a directory tree.") module to check a directory tree in batch mode. How do I check for a keypress without blocking? ----------------------------------------------- Use the [`msvcrt`](../library/msvcrt#module-msvcrt "msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)") module. This is a standard Windows-specific extension module. It defines a function `kbhit()` which checks whether a keyboard hit is present, and `getch()` which gets one character without echoing it. python Library and Extension FAQ Library and Extension FAQ ========================= * [General Library Questions](#general-library-questions) + [How do I find a module or application to perform task X?](#how-do-i-find-a-module-or-application-to-perform-task-x) + [Where is the math.py (socket.py, regex.py, etc.) source file?](#where-is-the-math-py-socket-py-regex-py-etc-source-file) + [How do I make a Python script executable on Unix?](#how-do-i-make-a-python-script-executable-on-unix) + [Is there a curses/termcap package for Python?](#is-there-a-curses-termcap-package-for-python) + [Is there an equivalent to C’s onexit() in Python?](#is-there-an-equivalent-to-c-s-onexit-in-python) + [Why don’t my signal handlers work?](#why-don-t-my-signal-handlers-work) * [Common tasks](#common-tasks) + [How do I test a Python program or component?](#how-do-i-test-a-python-program-or-component) + [How do I create documentation from doc strings?](#how-do-i-create-documentation-from-doc-strings) + [How do I get a single keypress at a time?](#how-do-i-get-a-single-keypress-at-a-time) * [Threads](#threads) + [How do I program using threads?](#how-do-i-program-using-threads) + [None of my threads seem to run: why?](#none-of-my-threads-seem-to-run-why) + [How do I parcel out work among a bunch of worker threads?](#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads) + [What kinds of global value mutation are thread-safe?](#what-kinds-of-global-value-mutation-are-thread-safe) + [Can’t we get rid of the Global Interpreter Lock?](#can-t-we-get-rid-of-the-global-interpreter-lock) * [Input and Output](#input-and-output) + [How do I delete a file? (And other file questions…)](#how-do-i-delete-a-file-and-other-file-questions) + [How do I copy a file?](#how-do-i-copy-a-file) + [How do I read (or write) binary data?](#how-do-i-read-or-write-binary-data) + [I can’t seem to use os.read() on a pipe created with os.popen(); why?](#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why) + [How do I access the serial (RS232) port?](#how-do-i-access-the-serial-rs232-port) + [Why doesn’t closing sys.stdout (stdin, stderr) really close it?](#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it) * [Network/Internet Programming](#network-internet-programming) + [What WWW tools are there for Python?](#what-www-tools-are-there-for-python) + [How can I mimic CGI form submission (METHOD=POST)?](#how-can-i-mimic-cgi-form-submission-method-post) + [What module should I use to help with generating HTML?](#what-module-should-i-use-to-help-with-generating-html) + [How do I send mail from a Python script?](#how-do-i-send-mail-from-a-python-script) + [How do I avoid blocking in the connect() method of a socket?](#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket) * [Databases](#databases) + [Are there any interfaces to database packages in Python?](#are-there-any-interfaces-to-database-packages-in-python) + [How do you implement persistent objects in Python?](#how-do-you-implement-persistent-objects-in-python) * [Mathematics and Numerics](#mathematics-and-numerics) + [How do I generate random numbers in Python?](#how-do-i-generate-random-numbers-in-python) General Library Questions ------------------------- ### How do I find a module or application to perform task X? Check [the Library Reference](../library/index#library-index) to see if there’s a relevant standard library module. (Eventually you’ll learn what’s in the standard library and will be able to skip this step.) For third-party packages, search the [Python Package Index](https://pypi.org) or try [Google](https://www.google.com) or another Web search engine. Searching for “Python” plus a keyword or two for your topic of interest will usually find something helpful. ### Where is the math.py (socket.py, regex.py, etc.) source file? If you can’t find a source file for a module it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like `mathmodule.c`, somewhere in a C source directory (not on the Python Path). There are (at least) three kinds of modules in Python: 1. modules written in Python (.py); 2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); 3. modules written in C and linked with the interpreter; to get a list of these, type: ``` import sys print(sys.builtin_module_names) ``` ### How do I make a Python script executable on Unix? You need to do two things: the script file’s mode must be executable and the first line must begin with `#!` followed by the path of the Python interpreter. The first is done by executing `chmod +x scriptfile` or perhaps `chmod 755 scriptfile`. The second can be done in a number of ways. The most straightforward way is to write ``` #!/usr/local/bin/python ``` as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the **env** program. Almost all Unix variants support the following, assuming the Python interpreter is in a directory on the user’s `PATH`: ``` #!/usr/bin/env python ``` *Don’t* do this for CGI scripts. The `PATH` variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user’s environment is so full that the **/usr/bin/env** program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky): ``` #! /bin/sh """:" exec python $0 ${1+"$@"} """ ``` The minor disadvantage is that this defines the script’s \_\_doc\_\_ string. However, you can fix that by adding ``` __doc__ = """...Whatever...""" ``` ### Is there a curses/termcap package for Python? For Unix variants: The standard Python source distribution comes with a curses module in the [Modules](https://github.com/python/cpython/tree/3.9/Modules) subdirectory, though it’s not compiled by default. (Note that this is not available in the Windows distribution – there is no curses module for Windows.) The [`curses`](../library/curses#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour, alternative character set support, pads, and mouse support. This means the module isn’t compatible with operating systems that only have BSD curses, but there don’t seem to be any currently maintained OSes that fall into this category. ### Is there an equivalent to C’s onexit() in Python? The [`atexit`](../library/atexit#module-atexit "atexit: Register and execute cleanup functions.") module provides a register function that is similar to C’s `onexit()`. ### Why don’t my signal handlers work? The most common problem is that the signal handler is declared with the wrong argument list. It is called as ``` handler(signum, frame) ``` so it should be declared with two parameters: ``` def handler(signum, frame): ... ``` Common tasks ------------ ### How do I test a Python program or component? Python comes with two testing frameworks. The [`doctest`](../library/doctest#module-doctest "doctest: Test pieces of code within docstrings.") module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring. The [`unittest`](../library/unittest#module-unittest "unittest: Unit testing framework for Python.") module is a fancier testing framework modelled on Java and Smalltalk testing frameworks. To make testing easier, you should use good modular design in your program. Your program should have almost all functionality encapsulated in either functions or class methods – and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do. The “global main logic” of your program may be as simple as ``` if __name__ == "__main__": main_logic() ``` at the bottom of the main module of your program. Once your program is organized as a tractable collection of function and class behaviours, you should write test functions that exercise the behaviours. A test suite that automates a sequence of tests can be associated with each module. This sounds like a lot of work, but since Python is so terse and flexible it’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier. “Support modules” that are not intended to be the main module of a program may include a self-test of the module. ``` if __name__ == "__main__": self_test() ``` Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python. ### How do I create documentation from doc strings? The [`pydoc`](../library/pydoc#module-pydoc "pydoc: Documentation generator and online help system.") module can create HTML from the doc strings in your Python source code. An alternative for creating API documentation purely from docstrings is [epydoc](http://epydoc.sourceforge.net/). [Sphinx](http://sphinx-doc.org) can also include docstring content. ### How do I get a single keypress at a time? For Unix variants there are several solutions. It’s straightforward to do this using curses, but curses is a fairly large module to learn. Threads ------- ### How do I program using threads? Be sure to use the [`threading`](../library/threading#module-threading "threading: Thread-based parallelism.") module and not the [`_thread`](../library/_thread#module-_thread "_thread: Low-level threading API.") module. The [`threading`](../library/threading#module-threading "threading: Thread-based parallelism.") module builds convenient abstractions on top of the low-level primitives provided by the [`_thread`](../library/_thread#module-_thread "_thread: Low-level threading API.") module. ### None of my threads seem to run: why? As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work. A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish: ``` import threading, time def thread_task(name, n): for i in range(n): print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) # <---------------------------! ``` But now (on many platforms) the threads don’t run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn’t start a new thread until the previous thread is blocked. A simple fix is to add a tiny sleep to the start of the run function: ``` def thread_task(name, n): time.sleep(0.001) # <--------------------! for i in range(n): print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) ``` Instead of trying to guess a good delay value for [`time.sleep()`](../library/time#time.sleep "time.sleep"), it’s better to use some kind of semaphore mechanism. One idea is to use the [`queue`](../library/queue#module-queue "queue: A synchronized queue class.") module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads. ### How do I parcel out work among a bunch of worker threads? The easiest way is to use the [`concurrent.futures`](../library/concurrent.futures#module-concurrent.futures "concurrent.futures: Execute computations concurrently using threads or processes.") module, especially the [`ThreadPoolExecutor`](../library/concurrent.futures#concurrent.futures.ThreadPoolExecutor "concurrent.futures.ThreadPoolExecutor") class. Or, if you want fine control over the dispatching algorithm, you can write your own logic manually. Use the [`queue`](../library/queue#module-queue "queue: A synchronized queue class.") module to create a queue containing a list of jobs. The [`Queue`](../library/queue#queue.Queue "queue.Queue") class maintains a list of objects and has a `.put(obj)` method that adds items to the queue and a `.get()` method to return them. The class will take care of the locking necessary to ensure that each job is handed out exactly once. Here’s a trivial example: ``` import threading, queue, time # The worker thread gets jobs off the queue. When the queue is empty, it # assumes there will be no more work and exits. # (Realistically workers will run until terminated.) def worker(): print('Running worker') time.sleep(0.1) while True: try: arg = q.get(block=False) except queue.Empty: print('Worker', threading.currentThread(), end=' ') print('queue empty') break else: print('Worker', threading.currentThread(), end=' ') print('running with argument', arg) time.sleep(0.5) # Create queue q = queue.Queue() # Start a pool of 5 workers for i in range(5): t = threading.Thread(target=worker, name='worker %i' % (i+1)) t.start() # Begin adding work to the queue for i in range(50): q.put(i) # Give threads time to run print('Main thread sleeping') time.sleep(5) ``` When run, this will produce the following output: ``` Running worker Running worker Running worker Running worker Running worker Main thread sleeping Worker <Thread(worker 1, started 130283832797456)> running with argument 0 Worker <Thread(worker 2, started 130283824404752)> running with argument 1 Worker <Thread(worker 3, started 130283816012048)> running with argument 2 Worker <Thread(worker 4, started 130283807619344)> running with argument 3 Worker <Thread(worker 5, started 130283799226640)> running with argument 4 Worker <Thread(worker 1, started 130283832797456)> running with argument 5 ... ``` Consult the module’s documentation for more details; the [`Queue`](../library/queue#queue.Queue "queue.Queue") class provides a featureful interface. ### What kinds of global value mutation are thread-safe? A [global interpreter lock](../glossary#term-global-interpreter-lock) (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via [`sys.setswitchinterval()`](../library/sys#sys.setswitchinterval "sys.setswitchinterval"). Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program. In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are. For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints): ``` L.append(x) L1.extend(L2) x = L[i] x = L.pop() L1[i:j] = L2 L.sort() x = y x.field = y D[x] = y D1.update(D2) D.keys() ``` These aren’t: ``` i = i+1 L.append(L[-1]) L[i] = L[j] D[x] = D[x] + 1 ``` Operations that replace other objects may invoke those other objects’ [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex! ### Can’t we get rid of the Global Interpreter Lock? The [global interpreter lock](../glossary#term-global-interpreter-lock) (GIL) is often seen as a hindrance to Python’s deployment on high-end multiprocessor server machines, because a multi-threaded Python program effectively only uses one CPU, due to the insistence that (almost) all Python code can only run while the GIL is held. Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive patch set (the “free threading” patches) that removed the GIL and replaced it with fine-grained locking. Adam Olsen recently did a similar experiment in his [python-safethread](https://code.google.com/archive/p/python-safethread) project. Unfortunately, both experiments exhibited a sharp drop in single-thread performance (at least 30% slower), due to the amount of fine-grained locking necessary to compensate for the removal of the GIL. This doesn’t mean that you can’t make good use of Python on multi-CPU machines! You just have to be creative with dividing the work up between multiple *processes* rather than multiple *threads*. The [`ProcessPoolExecutor`](../library/concurrent.futures#concurrent.futures.ProcessPoolExecutor "concurrent.futures.ProcessPoolExecutor") class in the new [`concurrent.futures`](../library/concurrent.futures#module-concurrent.futures "concurrent.futures: Execute computations concurrently using threads or processes.") module provides an easy way of doing so; the [`multiprocessing`](../library/multiprocessing#module-multiprocessing "multiprocessing: Process-based parallelism.") module provides a lower-level API in case you want more control over dispatching of tasks. Judicious use of C extensions will also help; if you use a C extension to perform a time-consuming task, the extension can release the GIL while the thread of execution is in the C code and allow other threads to get some work done. Some standard library modules such as [`zlib`](../library/zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.") and [`hashlib`](../library/hashlib#module-hashlib "hashlib: Secure hash and message digest algorithms.") already do this. It has been suggested that the GIL should be a per-interpreter-state lock rather than truly global; interpreters then wouldn’t be able to share objects. Unfortunately, this isn’t likely to happen either. It would be a tremendous amount of work, because many object implementations currently have global state. For example, small integers and short strings are cached; these caches would have to be moved to the interpreter state. Other object types have their own free list; these free lists would have to be moved to the interpreter state. And so on. And I doubt that it can even be done in finite time, because the same problem exists for 3rd party extensions. It is likely that 3rd party extensions are being written at a faster rate than you can convert them to store all their global state in the interpreter state. And finally, once you have multiple interpreters not sharing any state, what have you gained over running each interpreter in a separate process? Input and Output ---------------- ### How do I delete a file? (And other file questions…) Use `os.remove(filename)` or `os.unlink(filename)`; for documentation, see the [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces.") module. The two functions are identical; [`unlink()`](../library/os#os.unlink "os.unlink") is simply the name of the Unix system call for this function. To remove a directory, use [`os.rmdir()`](../library/os#os.rmdir "os.rmdir"); use [`os.mkdir()`](../library/os#os.mkdir "os.mkdir") to create one. `os.makedirs(path)` will create any intermediate directories in `path` that don’t exist. `os.removedirs(path)` will remove intermediate directories as long as they’re empty; if you want to delete an entire directory tree and its contents, use [`shutil.rmtree()`](../library/shutil#shutil.rmtree "shutil.rmtree"). To rename a file, use `os.rename(old_path, new_path)`. To truncate a file, open it using `f = open(filename, "rb+")`, and use `f.truncate(offset)`; offset defaults to the current seek position. There’s also `os.ftruncate(fd, offset)` for files opened with [`os.open()`](../library/os#os.open "os.open"), where *fd* is the file descriptor (a small integer). The [`shutil`](../library/shutil#module-shutil "shutil: High-level file operations, including copying.") module also contains a number of functions to work on files including [`copyfile()`](../library/shutil#shutil.copyfile "shutil.copyfile"), [`copytree()`](../library/shutil#shutil.copytree "shutil.copytree"), and [`rmtree()`](../library/shutil#shutil.rmtree "shutil.rmtree"). ### How do I copy a file? The [`shutil`](../library/shutil#module-shutil "shutil: High-level file operations, including copying.") module contains a [`copyfile()`](../library/shutil#shutil.copyfile "shutil.copyfile") function. Note that on MacOS 9 it doesn’t copy the resource fork and Finder info. ### How do I read (or write) binary data? To read or write complex binary data formats, it’s best to use the [`struct`](../library/struct#module-struct "struct: Interpret bytes as packed binary data.") module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa. For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file: ``` import struct with open(filename, "rb") as f: s = f.read(8) x, y, z = struct.unpack(">hhl", s) ``` The ‘>’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string. For data that is more regular (e.g. a homogeneous list of ints or floats), you can also use the [`array`](../library/array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module. Note To read and write binary data, it is mandatory to open the file in binary mode (here, passing `"rb"` to [`open()`](../library/functions#open "open")). If you use `"r"` instead (the default), the file will be open in text mode and `f.read()` will return [`str`](../library/stdtypes#str "str") objects rather than [`bytes`](../library/stdtypes#bytes "bytes") objects. ### I can’t seem to use os.read() on a pipe created with os.popen(); why? [`os.read()`](../library/os#os.read "os.read") is a low-level function which takes a file descriptor, a small integer representing the opened file. [`os.popen()`](../library/os#os.popen "os.popen") creates a high-level file object, the same type returned by the built-in [`open()`](../library/functions#open "open") function. Thus, to read *n* bytes from a pipe *p* created with [`os.popen()`](../library/os#os.popen "os.popen"), you need to use `p.read(n)`. ### How do I access the serial (RS232) port? For Win32, OSX, Linux, BSD, Jython, IronPython: <https://pypi.org/project/pyserial/> For Unix, see a Usenet post by Mitch Chapman: <https://groups.google.com/[email protected]> ### Why doesn’t closing sys.stdout (stdin, stderr) really close it? Python [file objects](../glossary#term-file-object) are a high-level layer of abstraction on low-level C file descriptors. For most file objects you create in Python via the built-in [`open()`](../library/functions#open "open") function, `f.close()` marks the Python file object as being closed from Python’s point of view, and also arranges to close the underlying C file descriptor. This also happens automatically in `f`’s destructor, when `f` becomes garbage. But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running `sys.stdout.close()` marks the Python-level file object as being closed, but does *not* close the associated C file descriptor. To close the underlying C file descriptor for one of these three, you should first be sure that’s what you really want to do (e.g., you may confuse extension modules trying to do I/O). If it is, use [`os.close()`](../library/os#os.close "os.close"): ``` os.close(stdin.fileno()) os.close(stdout.fileno()) os.close(stderr.fileno()) ``` Or you can use the numeric constants 0, 1 and 2, respectively. Network/Internet Programming ---------------------------- ### What WWW tools are there for Python? See the chapters titled [Internet Protocols and Support](../library/internet#internet) and [Internet Data Handling](../library/netdata#netdata) in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems. A summary of available frameworks is maintained by Paul Boddie at <https://wiki.python.org/moin/WebProgramming>. Cameron Laird maintains a useful set of pages about Python web technologies at <http://phaseit.net/claird/comp.lang.python/web_python>. ### How can I mimic CGI form submission (METHOD=POST)? I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily? Yes. Here’s a simple example that uses [`urllib.request`](../library/urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs."): ``` #!/usr/local/bin/python import urllib.request # build the query string qs = "First=Josephine&MI=Q&Last=Public" # connect and send the server a path req = urllib.request.urlopen('http://www.some-server.out-there' '/cgi-bin/some-cgi-script', data=qs) with req: msg, hdrs = req.read(), req.info() ``` Note that in general for percent-encoded POST operations, query strings must be quoted using [`urllib.parse.urlencode()`](../library/urllib.parse#urllib.parse.urlencode "urllib.parse.urlencode"). For example, to send `name=Guy Steele, Jr.`: ``` >>> import urllib.parse >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'}) 'name=Guy+Steele%2C+Jr.' ``` See also [HOWTO Fetch Internet Resources Using The urllib Package](../howto/urllib2#urllib-howto) for extensive examples. ### What module should I use to help with generating HTML? You can find a collection of useful links on the [Web Programming wiki page](https://wiki.python.org/moin/WebProgramming). ### How do I send mail from a Python script? Use the standard library module [`smtplib`](../library/smtplib#module-smtplib "smtplib: SMTP protocol client (requires sockets)."). Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener. ``` import sys, smtplib fromaddr = input("From: ") toaddrs = input("To: ").split(',') print("Enter message, end with ^D:") msg = '' while True: line = sys.stdin.readline() if not line: break msg += line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() ``` A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is `/usr/lib/sendmail`, sometimes `/usr/sbin/sendmail`. The sendmail manual page will help you out. Here’s some sample code: ``` import os SENDMAIL = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s -t -i" % SENDMAIL, "w") p.write("To: [email protected]\n") p.write("Subject: test\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write("some more text\n") sts = p.close() if sts != 0: print("Sendmail exit status", sts) ``` ### How do I avoid blocking in the connect() method of a socket? The [`select`](../library/select#module-select "select: Wait for I/O completion on multiple streams.") module is commonly used to help with asynchronous I/O on sockets. To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you do the `socket.connect()`, you will either connect immediately (unlikely) or get an exception that contains the error number as `.errno`. `errno.EINPROGRESS` indicates that the connection is in progress, but hasn’t finished yet. Different OSes will return different values, so you’re going to have to check what’s returned on your system. You can use the `socket.connect_ex()` method to avoid creating an exception. It will just return the errno value. To poll, you can call `socket.connect_ex()` again later – `0` or `errno.EISCONN` indicate that you’re connected – or you can pass this socket to [`select.select()`](../library/select#select.select "select.select") to check if it’s writable. Note The [`asyncio`](../library/asyncio#module-asyncio "asyncio: Asynchronous I/O.") module provides a general purpose single-threaded and concurrent asynchronous library, which can be used for writing non-blocking network code. The third-party [Twisted](https://twistedmatrix.com/trac/) library is a popular and feature-rich alternative. Databases --------- ### Are there any interfaces to database packages in Python? Yes. Interfaces to disk-based hashes such as [`DBM`](../library/dbm#module-dbm.ndbm "dbm.ndbm: The standard \"database\" interface, based on ndbm. (Unix)") and [`GDBM`](../library/dbm#module-dbm.gnu "dbm.gnu: GNU's reinterpretation of dbm. (Unix)") are also included with standard Python. There is also the [`sqlite3`](../library/sqlite3#module-sqlite3 "sqlite3: A DB-API 2.0 implementation using SQLite 3.x.") module, which provides a lightweight disk-based relational database. Support for most relational databases is available. See the [DatabaseProgramming wiki page](https://wiki.python.org/moin/DatabaseProgramming) for details. ### How do you implement persistent objects in Python? The [`pickle`](../library/pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") library module solves this in a very general way (though you still can’t store things like open files, sockets or windows), and the [`shelve`](../library/shelve#module-shelve "shelve: Python object persistence.") library module uses pickle and (g)dbm to create persistent mappings containing arbitrary Python objects. Mathematics and Numerics ------------------------ ### How do I generate random numbers in Python? The standard module [`random`](../library/random#module-random "random: Generate pseudo-random numbers with various common distributions.") implements a random number generator. Usage is simple: ``` import random random.random() ``` This returns a random floating point number in the range [0, 1). There are also many other specialized generators in this module, such as: * `randrange(a, b)` chooses an integer in the range [a, b). * `uniform(a, b)` chooses a floating point number in the range [a, b). * `normalvariate(mean, sdev)` samples the normal (Gaussian) distribution. Some higher-level functions operate on sequences directly, such as: * `choice(S)` chooses a random element from a given sequence. * `shuffle(L)` shuffles a list in-place, i.e. permutes it randomly. There’s also a `Random` class you can instantiate to create independent multiple random number generators.
programming_docs
python “Why is Python Installed on my Computer?” FAQ “Why is Python Installed on my Computer?” FAQ ============================================= What is Python? --------------- Python is a programming language. It’s used for many different applications. It’s used in some high schools and colleges as an introductory programming language because Python is easy to learn, but it’s also used by professional software developers at places such as Google, NASA, and Lucasfilm Ltd. If you wish to learn more about Python, start with the [Beginner’s Guide to Python](https://wiki.python.org/moin/BeginnersGuide). Why is Python installed on my machine? -------------------------------------- If you find Python installed on your system but don’t remember installing it, there are several possible ways it could have gotten there. * Perhaps another user on the computer wanted to learn programming and installed it; you’ll have to figure out who’s been using the machine and might have installed it. * A third-party application installed on the machine might have been written in Python and included a Python installation. There are many such applications, from GUI programs to network servers and administrative scripts. * Some Windows machines also have Python installed. At this writing we’re aware of computers from Hewlett-Packard and Compaq that include Python. Apparently some of HP/Compaq’s administrative tools are written in Python. * Many Unix-compatible operating systems, such as macOS and some Linux distributions, have Python installed by default; it’s included in the base installation. Can I delete Python? -------------------- That depends on where Python came from. If someone installed it deliberately, you can remove it without hurting anything. On Windows, use the Add/Remove Programs icon in the Control Panel. If Python was installed by a third-party application, you can also remove it, but that application will no longer work. You should use that application’s uninstaller rather than removing Python directly. If Python came with your operating system, removing it is not recommended. If you remove it, whatever tools were written in Python will no longer run, and some of them might be important to you. Reinstalling the whole system would then be required to fix things again. python Programming FAQ Programming FAQ =============== * [General Questions](#general-questions) + [Is there a source code level debugger with breakpoints, single-stepping, etc.?](#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc) + [Are there tools to help find bugs or perform static analysis?](#are-there-tools-to-help-find-bugs-or-perform-static-analysis) + [How can I create a stand-alone binary from a Python script?](#how-can-i-create-a-stand-alone-binary-from-a-python-script) + [Are there coding standards or a style guide for Python programs?](#are-there-coding-standards-or-a-style-guide-for-python-programs) * [Core Language](#core-language) + [Why am I getting an UnboundLocalError when the variable has a value?](#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) + [What are the rules for local and global variables in Python?](#what-are-the-rules-for-local-and-global-variables-in-python) + [Why do lambdas defined in a loop with different values all return the same result?](#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) + [How do I share global variables across modules?](#how-do-i-share-global-variables-across-modules) + [What are the “best practices” for using import in a module?](#what-are-the-best-practices-for-using-import-in-a-module) + [Why are default values shared between objects?](#why-are-default-values-shared-between-objects) + [How can I pass optional or keyword parameters from one function to another?](#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another) + [What is the difference between arguments and parameters?](#what-is-the-difference-between-arguments-and-parameters) + [Why did changing list ‘y’ also change list ‘x’?](#why-did-changing-list-y-also-change-list-x) + [How do I write a function with output parameters (call by reference)?](#how-do-i-write-a-function-with-output-parameters-call-by-reference) + [How do you make a higher order function in Python?](#how-do-you-make-a-higher-order-function-in-python) + [How do I copy an object in Python?](#how-do-i-copy-an-object-in-python) + [How can I find the methods or attributes of an object?](#how-can-i-find-the-methods-or-attributes-of-an-object) + [How can my code discover the name of an object?](#how-can-my-code-discover-the-name-of-an-object) + [What’s up with the comma operator’s precedence?](#what-s-up-with-the-comma-operator-s-precedence) + [Is there an equivalent of C’s “?:” ternary operator?](#is-there-an-equivalent-of-c-s-ternary-operator) + [Is it possible to write obfuscated one-liners in Python?](#is-it-possible-to-write-obfuscated-one-liners-in-python) + [What does the slash(/) in the parameter list of a function mean?](#what-does-the-slash-in-the-parameter-list-of-a-function-mean) * [Numbers and strings](#numbers-and-strings) + [How do I specify hexadecimal and octal integers?](#how-do-i-specify-hexadecimal-and-octal-integers) + [Why does -22 // 10 return -3?](#why-does-22-10-return-3) + [How do I get int literal attribute instead of SyntaxError?](#how-do-i-get-int-literal-attribute-instead-of-syntaxerror) + [How do I convert a string to a number?](#how-do-i-convert-a-string-to-a-number) + [How do I convert a number to a string?](#how-do-i-convert-a-number-to-a-string) + [How do I modify a string in place?](#how-do-i-modify-a-string-in-place) + [How do I use strings to call functions/methods?](#how-do-i-use-strings-to-call-functions-methods) + [Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?](#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings) + [Is there a scanf() or sscanf() equivalent?](#is-there-a-scanf-or-sscanf-equivalent) + [What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?](#what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean) * [Performance](#performance) + [My program is too slow. How do I speed it up?](#my-program-is-too-slow-how-do-i-speed-it-up) + [What is the most efficient way to concatenate many strings together?](#what-is-the-most-efficient-way-to-concatenate-many-strings-together) * [Sequences (Tuples/Lists)](#sequences-tuples-lists) + [How do I convert between tuples and lists?](#how-do-i-convert-between-tuples-and-lists) + [What’s a negative index?](#what-s-a-negative-index) + [How do I iterate over a sequence in reverse order?](#how-do-i-iterate-over-a-sequence-in-reverse-order) + [How do you remove duplicates from a list?](#how-do-you-remove-duplicates-from-a-list) + [How do you remove multiple items from a list](#how-do-you-remove-multiple-items-from-a-list) + [How do you make an array in Python?](#how-do-you-make-an-array-in-python) + [How do I create a multidimensional list?](#how-do-i-create-a-multidimensional-list) + [How do I apply a method to a sequence of objects?](#how-do-i-apply-a-method-to-a-sequence-of-objects) + [Why does a\_tuple[i] += [‘item’] raise an exception when the addition works?](#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) + [I want to do a complicated sort: can you do a Schwartzian Transform in Python?](#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python) + [How can I sort one list by values from another list?](#how-can-i-sort-one-list-by-values-from-another-list) * [Objects](#objects) + [What is a class?](#what-is-a-class) + [What is a method?](#what-is-a-method) + [What is self?](#what-is-self) + [How do I check if an object is an instance of a given class or of a subclass of it?](#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it) + [What is delegation?](#what-is-delegation) + [How do I call a method defined in a base class from a derived class that overrides it?](#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it) + [How can I organize my code to make it easier to change the base class?](#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class) + [How do I create static class data and static class methods?](#how-do-i-create-static-class-data-and-static-class-methods) + [How can I overload constructors (or methods) in Python?](#how-can-i-overload-constructors-or-methods-in-python) + [I try to use \_\_spam and I get an error about \_SomeClassName\_\_spam.](#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam) + [My class defines \_\_del\_\_ but it is not called when I delete the object.](#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object) + [How do I get a list of all instances of a given class?](#how-do-i-get-a-list-of-all-instances-of-a-given-class) + [Why does the result of `id()` appear to be not unique?](#why-does-the-result-of-id-appear-to-be-not-unique) + [When can I rely on identity tests with the is operator?](#when-can-i-rely-on-identity-tests-with-the-is-operator) + [How can a subclass control what data is stored in an immutable instance?](#how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance) * [Modules](#modules) + [How do I create a .pyc file?](#how-do-i-create-a-pyc-file) + [How do I find the current module name?](#how-do-i-find-the-current-module-name) + [How can I have modules that mutually import each other?](#how-can-i-have-modules-that-mutually-import-each-other) + [\_\_import\_\_(‘x.y.z’) returns <module ‘x’>; how do I get z?](#import-x-y-z-returns-module-x-how-do-i-get-z) + [When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?](#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen) General Questions ----------------- ### Is there a source code level debugger with breakpoints, single-stepping, etc.? Yes. Several debuggers for Python are described below, and the built-in function [`breakpoint()`](../library/functions#breakpoint "breakpoint") allows you to drop into any of them. The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is [`documented in the Library Reference Manual`](../library/pdb#module-pdb "pdb: The Python debugger for interactive interpreters."). You can also write your own debugger by using the code for pdb as an example. The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger. PythonWin is a Python IDE that includes a GUI debugger based on pdb. The PythonWin debugger colors breakpoints and has quite a few cool features such as debugging non-PythonWin programs. PythonWin is available as part of [pywin32](https://github.com/mhammond/pywin32) project and as a part of the [ActivePython](https://www.activestate.com/products/python/) distribution. [Eric](http://eric-ide.python-projects.org/) is an IDE built on PyQt and the Scintilla editing component. [trepan3k](https://github.com/rocky/python3-trepan/) is a gdb-like debugger. [Visual Studio Code](https://code.visualstudio.com/) is an IDE with debugging tools that integrates with version-control software. There are a number of commercial Python IDEs that include graphical debuggers. They include: * [Wing IDE](https://wingware.com/) * [Komodo IDE](https://www.activestate.com/products/komodo-ide/) * [PyCharm](https://www.jetbrains.com/pycharm/) ### Are there tools to help find bugs or perform static analysis? Yes. [Pylint](https://www.pylint.org/) and [Pyflakes](https://github.com/PyCQA/pyflakes) do basic checking that will help you catch bugs sooner. Static type checkers such as [Mypy](http://mypy-lang.org/), [Pyre](https://pyre-check.org/), and [Pytype](https://github.com/google/pytype) can check type hints in Python source code. ### How can I create a stand-alone binary from a Python script? You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable. One is to use the freeze tool, which is included in the Python source tree as `Tools/freeze`. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules. It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script. The following packages can help with the creation of console and GUI executables: * [Nuitka](https://nuitka.net/) (Cross-platform) * [PyInstaller](http://www.pyinstaller.org/) (Cross-platform) * [PyOxidizer](https://pyoxidizer.readthedocs.io/en/stable/) (Cross-platform) * [cx\_Freeze](https://marcelotduarte.github.io/cx_Freeze/) (Cross-platform) * [py2app](https://github.com/ronaldoussoren/py2app) (macOS only) * [py2exe](http://www.py2exe.org/) (Windows only) ### Are there coding standards or a style guide for Python programs? Yes. The coding style required for standard library modules is documented as [**PEP 8**](https://www.python.org/dev/peps/pep-0008). Core Language ------------- ### Why am I getting an UnboundLocalError when the variable has a value? It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. This code: ``` >>> x = 10 >>> def bar(): ... print(x) >>> bar() 10 ``` works, but this code: ``` >>> x = 10 >>> def foo(): ... print(x) ... x += 1 ``` results in an UnboundLocalError: ``` >>> foo() Traceback (most recent call last): ... UnboundLocalError: local variable 'x' referenced before assignment ``` This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to `x`, the compiler recognizes it as a local variable. Consequently when the earlier `print(x)` attempts to print the uninitialized local variable and an error results. In the example above you can access the outer scope variable by declaring it global: ``` >>> x = 10 >>> def foobar(): ... global x ... print(x) ... x += 1 >>> foobar() 10 ``` This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope: ``` >>> print(x) 11 ``` You can do a similar thing in a nested scope using the [`nonlocal`](../reference/simple_stmts#nonlocal) keyword: ``` >>> def foo(): ... x = 10 ... def bar(): ... nonlocal x ... print(x) ... x += 1 ... bar() ... print(x) >>> foo() 10 11 ``` ### What are the rules for local and global variables in Python? In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring [`global`](../reference/simple_stmts#global) for assigned variables provides a bar against unintended side-effects. On the other hand, if `global` was required for all global references, you’d be using `global` all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the `global` declaration for identifying side-effects. ### Why do lambdas defined in a loop with different values all return the same result? Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.: ``` >>> squares = [] >>> for x in range(5): ... squares.append(lambda: x**2) ``` This gives you a list that contains 5 lambdas that calculate `x**2`. You might expect that, when called, they would return, respectively, `0`, `1`, `4`, `9`, and `16`. However, when you actually try you will see that they all return `16`: ``` >>> squares[2]() 16 >>> squares[4]() 16 ``` This happens because `x` is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of `x` is `4`, so all the functions now return `4**2`, i.e. `16`. You can also verify this by changing the value of `x` and see how the results of the lambdas change: ``` >>> x = 8 >>> squares[2]() 64 ``` In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global `x`: ``` >>> squares = [] >>> for x in range(5): ... squares.append(lambda n=x: n**2) ``` Here, `n=x` creates a new variable `n` local to the lambda and computed when the lambda is defined so that it has the same value that `x` had at that point in the loop. This means that the value of `n` will be `0` in the first lambda, `1` in the second, `2` in the third, and so on. Therefore each lambda will now return the correct result: ``` >>> squares[2]() 4 >>> squares[4]() 16 ``` Note that this behaviour is not peculiar to lambdas, but applies to regular functions too. ### How do I share global variables across modules? The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: config.py: ``` x = 0 # Default value of the 'x' configuration setting ``` mod.py: ``` import config config.x = 1 ``` main.py: ``` import config import mod print(config.x) ``` Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason. ### What are the “best practices” for using import in a module? In general, don’t use `from modulename import *`. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names. Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space. It’s good practice if you import modules in the following order: 1. standard library modules – e.g. `sys`, `os`, `getopt`, `re` 2. third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc. 3. locally-developed modules It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says: Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd. In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import. It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option. Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in [`sys.modules`](../library/sys#sys.modules "sys.modules"). ### Why are default values shared between objects? This type of bug commonly bites neophyte programmers. Consider this function: ``` def foo(mydict={}): # Danger: shared reference to one dict for all calls ... compute something ... mydict[key] = value return mydict ``` The first time you call this function, `mydict` contains a single item. The second time, `mydict` contains two items because when `foo()` begins executing, `mydict` starts out with an item already in it. It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object. By definition, immutable objects such as numbers, strings, tuples, and `None`, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use `None` as the default value and inside the function, check if the parameter is `None` and create a new list/dictionary/whatever if it is. For example, don’t write: ``` def foo(mydict={}): ... ``` but: ``` def foo(mydict=None): if mydict is None: mydict = {} # create a new dict for local namespace ``` This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this: ``` # Callers can only provide two parameters and optionally pass _cache by keyword def expensive(arg1, arg2, *, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result ``` You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste. ### How can I pass optional or keyword parameters from one function to another? Collect the arguments using the `*` and `**` specifiers in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using `*` and `**`: ``` def f(x, *args, **kwargs): ... kwargs['width'] = '14.3c' ... g(x, *args, **kwargs) ``` ### What is the difference between arguments and parameters? [Parameters](../glossary#term-parameter) are defined by the names that appear in a function definition, whereas [arguments](../glossary#term-argument) are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition: ``` def func(foo, bar=None, **kwargs): pass ``` *foo*, *bar* and *kwargs* are parameters of `func`. However, when calling `func`, for example: ``` func(42, bar=314, extra=somevar) ``` the values `42`, `314`, and `somevar` are arguments. ### Why did changing list ‘y’ also change list ‘x’? If you wrote code like: ``` >>> x = [] >>> y = x >>> y.append(10) >>> y [10] >>> x [10] ``` you might be wondering why appending an element to `y` changed `x` too. There are two factors that produce this result: 1. Variables are simply names that refer to objects. Doing `y = x` doesn’t create a copy of the list – it creates a new variable `y` that refers to the same object `x` refers to. This means that there is only one object (the list), and both `x` and `y` refer to it. 2. Lists are [mutable](../glossary#term-mutable), which means that you can change their content. After the call to `append()`, the content of the mutable object has changed from `[]` to `[10]`. Since both the variables refer to the same object, using either name accesses the modified value `[10]`. If we instead assign an immutable object to `x`: ``` >>> x = 5 # ints are immutable >>> y = x >>> x = x + 1 # 5 can't be mutated, we are creating a new object here >>> x 6 >>> y 5 ``` we can see that in this case `x` and `y` are not equal anymore. This is because integers are [immutable](../glossary#term-immutable), and when we do `x = x + 1` we are not mutating the int `5` by incrementing its value; instead, we are creating a new object (the int `6`) and assigning it to `x` (that is, changing which object `x` refers to). After this assignment we have two objects (the ints `6` and `5`) and two variables that refer to them (`x` now refers to `6` but `y` still refers to `5`). Some operations (for example `y.append(10)` and `y.sort()`) mutate the object, whereas superficially similar operations (for example `y = y + [10]` and `sorted(y)`) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return `None` to help avoid getting the two types of operations confused. So if you mistakenly write `y.sort()` thinking it will give you a sorted copy of `y`, you’ll instead end up with `None`, which will likely cause your program to generate an easily diagnosed error. However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, `+=` mutates lists but not tuples or ints (`a_list += [1, 2, 3]` is equivalent to `a_list.extend([1, 2, 3])` and mutates `a_list`, whereas `some_tuple += (1, 2, 3)` and `some_int += 1` create new objects). In other words: * If we have a mutable object ([`list`](../library/stdtypes#list "list"), [`dict`](../library/stdtypes#dict "dict"), [`set`](../library/stdtypes#set "set"), etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change. * If we have an immutable object ([`str`](../library/stdtypes#str "str"), [`int`](../library/functions#int "int"), [`tuple`](../library/stdtypes#tuple "tuple"), etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object. If you want to know if two variables refer to the same object or not, you can use the [`is`](../reference/expressions#is) operator, or the built-in function [`id()`](../library/functions#id "id"). ### How do I write a function with output parameters (call by reference)? Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways. 1. By returning a tuple of the results: ``` >>> def func1(a, b): ... a = 'new-value' # a and b are local names ... b = b + 1 # assigned to new objects ... return a, b # return new values ... >>> x, y = 'old-value', 99 >>> func1(x, y) ('new-value', 100) ``` This is almost always the clearest solution. 2. By using global variables. This isn’t thread-safe, and is not recommended. 3. By passing a mutable (changeable in-place) object: ``` >>> def func2(a): ... a[0] = 'new-value' # 'a' references a mutable list ... a[1] = a[1] + 1 # changes a shared object ... >>> args = ['old-value', 99] >>> func2(args) >>> args ['new-value', 100] ``` 4. By passing in a dictionary that gets mutated: ``` >>> def func3(args): ... args['a'] = 'new-value' # args is a mutable dictionary ... args['b'] = args['b'] + 1 # change it in-place ... >>> args = {'a': 'old-value', 'b': 99} >>> func3(args) >>> args {'a': 'new-value', 'b': 100} ``` 5. Or bundle up values in a class instance: ``` >>> class Namespace: ... def __init__(self, /, **args): ... for key, value in args.items(): ... setattr(self, key, value) ... >>> def func4(args): ... args.a = 'new-value' # args is a mutable Namespace ... args.b = args.b + 1 # change object in-place ... >>> args = Namespace(a='old-value', b=99) >>> func4(args) >>> vars(args) {'a': 'new-value', 'b': 100} ``` There’s almost never a good reason to get this complicated. Your best choice is to return a tuple containing the multiple results. ### How do you make a higher order function in Python? You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define `linear(a,b)` which returns a function `f(x)` that computes the value `a*x+b`. Using nested scopes: ``` def linear(a, b): def result(x): return a * x + b return result ``` Or using a callable object: ``` class linear: def __init__(self, a, b): self.a, self.b = a, b def __call__(self, x): return self.a * x + self.b ``` In both cases, ``` taxes = linear(0.3, 2) ``` gives a callable object where `taxes(10e6) == 0.3 * 10e6 + 2`. The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance: ``` class exponential(linear): # __init__ inherited def __call__(self, x): return self.a * (x ** self.b) ``` Object can encapsulate state for several methods: ``` class counter: value = 0 def set(self, x): self.value = x def up(self): self.value = self.value + 1 def down(self): self.value = self.value - 1 count = counter() inc, dec, reset = count.up, count.down, count.set ``` Here `inc()`, `dec()` and `reset()` act like functions which share the same counting variable. ### How do I copy an object in Python? In general, try [`copy.copy()`](../library/copy#copy.copy "copy.copy") or [`copy.deepcopy()`](../library/copy#copy.deepcopy "copy.deepcopy") for the general case. Not all objects can be copied, but most can. Some objects can be copied more easily. Dictionaries have a [`copy()`](../library/stdtypes#dict.copy "dict.copy") method: ``` newdict = olddict.copy() ``` Sequences can be copied by slicing: ``` new_l = l[:] ``` ### How can I find the methods or attributes of an object? For an instance x of a user-defined class, `dir(x)` returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. ### How can my code discover the name of an object? Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; the same is true of `def` and `class` statements, but in that case the value is a callable. Consider the following code: ``` >>> class A: ... pass ... >>> B = A >>> a = B() >>> b = a >>> print(b) <__main__.A object at 0x16D07CC> >>> print(a) <__main__.A object at 0x16D07CC> ``` Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance’s name is a or b, since both names are bound to the same value. Generally speaking it should not be necessary for your code to “know the names” of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question: The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care – so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)… ….and don’t be surprised if you’ll find that it’s known by many names, or no name at all! ### What’s up with the comma operator’s precedence? Comma is not an operator in Python. Consider this session: ``` >>> "a" in "b", "a" (False, 'a') ``` Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered: ``` ("a" in "b"), "a" ``` not: ``` "a" in ("b", "a") ``` The same is true of the various assignment operators (`=`, `+=` etc). They are not truly operators but syntactic delimiters in assignment statements. ### Is there an equivalent of C’s “?:” ternary operator? Yes, there is. The syntax is as follows: ``` [on_true] if [expression] else [on_false] x, y = 50, 25 small = x if x < y else y ``` Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators: ``` [expression] and [on_true] or [on_false] ``` However, this idiom is unsafe, as it can give wrong results when *on\_true* has a false boolean value. Therefore, it is always better to use the `... if ... else ...` form. ### Is it possible to write obfuscated one-liners in Python? Yes. Usually this is done by nesting [`lambda`](../reference/expressions#lambda) within `lambda`. See the following three examples, due to Ulf Bartelt: ``` from functools import reduce # Primes < 1000 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000))))) # First 10 Fibonacci numbers print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f), range(10)))) # Mandelbrot set print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y, Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM, Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro, i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr( 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)) # \___ ___/ \___ ___/ | | |__ lines on screen # V V | |______ columns on screen # | | |__________ maximum of "iterations" # | |_________________ range on y axis # |____________________________ range on x axis ``` Don’t try this at home, kids! ### What does the slash(/) in the parameter list of a function mean? A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, [`divmod()`](../library/functions#divmod "divmod") is a function that accepts positional-only parameters. Its documentation looks like this: ``` >>> help(divmod) Help on built-in function divmod in module builtins: divmod(x, y, /) Return the tuple (x//y, x%y). Invariant: div*y + mod == x. ``` The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling [`divmod()`](../library/functions#divmod "divmod") with keyword arguments would lead to an error: ``` >>> divmod(x=3, y=4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: divmod() takes no keyword arguments ``` Numbers and strings ------------------- ### How do I specify hexadecimal and octal integers? To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase “o”. For example, to set the variable “a” to the octal value “10” (8 in decimal), type: ``` >>> a = 0o10 >>> a 8 ``` Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter: ``` >>> a = 0xa5 >>> a 165 >>> b = 0XB2 >>> b 178 ``` ### Why does -22 // 10 return -3? It’s primarily driven by the desire that `i % j` have the same sign as `j`. If you want that, and also want: ``` i == (i // j) * j + (i % j) ``` then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate `i // j` need to make `i % j` have the same sign as `i`. There are few real use cases for `i % j` when `j` is negative. When `j` is positive, there are many, and in virtually all of them it’s more useful for `i % j` to be `>= 0`. If the clock says 10 now, what did it say 200 hours ago? `-190 % 12 == 2` is useful; `-190 % 12 == -10` is a bug waiting to bite. ### How do I get int literal attribute instead of SyntaxError? Trying to lookup an `int` literal attribute in the normal manner gives a syntax error because the period is seen as a decimal point: ``` >>> 1.__class__ File "<stdin>", line 1 1.__class__ ^ SyntaxError: invalid decimal literal ``` The solution is to separate the literal from the period with either a space or parentheses. ``` >>> 1 .__class__ <class 'int'> >>> (1).__class__ <class 'int'> ``` ### How do I convert a string to a number? For integers, use the built-in [`int()`](../library/functions#int "int") type constructor, e.g. `int('144') == 144`. Similarly, [`float()`](../library/functions#float "float") converts to floating-point, e.g. `float('144') == 144.0`. By default, these interpret the number as decimal, so that `int('0144') == 144` holds true, and `int('0x144')` raises [`ValueError`](../library/exceptions#ValueError "ValueError"). `int(string, base)` takes the base to convert from as a second optional argument, so `int( '0x144', 16) == 324`. If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex number. Do not use the built-in function [`eval()`](../library/functions#eval "eval") if all you need is to convert strings to numbers. [`eval()`](../library/functions#eval "eval") will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass `__import__('os').system("rm -rf $HOME")` which would erase your home directory. [`eval()`](../library/functions#eval "eval") also has the effect of interpreting numbers as Python expressions, so that e.g. `eval('09')` gives a syntax error because Python does not allow leading ‘0’ in a decimal number (except ‘0’). ### How do I convert a number to a string? To convert, e.g., the number 144 to the string ‘144’, use the built-in type constructor [`str()`](../library/stdtypes#str "str"). If you want a hexadecimal or octal representation, use the built-in functions [`hex()`](../library/functions#hex "hex") or [`oct()`](../library/functions#oct "oct"). For fancy formatting, see the [Formatted string literals](../reference/lexical_analysis#f-strings) and [Format String Syntax](../library/string#formatstrings) sections, e.g. `"{:04d}".format(144)` yields `'0144'` and `"{:.3f}".format(1.0/3.0)` yields `'0.333'`. ### How do I modify a string in place? You can’t, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an [`io.StringIO`](../library/io#io.StringIO "io.StringIO") object or the [`array`](../library/array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module: ``` >>> import io >>> s = "Hello, world" >>> sio = io.StringIO(s) >>> sio.getvalue() 'Hello, world' >>> sio.seek(7) 7 >>> sio.write("there!") 6 >>> sio.getvalue() 'Hello, there!' >>> import array >>> a = array.array('u', s) >>> print(a) array('u', 'Hello, world') >>> a[0] = 'y' >>> print(a) array('u', 'yello, world') >>> a.tounicode() 'yello, world' ``` ### How do I use strings to call functions/methods? There are various techniques. * The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct: ``` def a(): pass def b(): pass dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs dispatch[get_input()]() # Note trailing parens to call function ``` * Use the built-in function [`getattr()`](../library/functions#getattr "getattr"): ``` import foo getattr(foo, 'bar')() ``` Note that [`getattr()`](../library/functions#getattr "getattr") works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this: ``` class Foo: def do_foo(self): ... def do_bar(self): ... f = getattr(foo_instance, 'do_' + opname) f() ``` * Use [`locals()`](../library/functions#locals "locals") to resolve the function name: ``` def myFunc(): print("hello") fname = "myFunc" f = locals()[fname] f() ``` ### Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings? You can use `S.rstrip("\r\n")` to remove all occurrences of any line terminator from the end of the string `S` without removing other trailing whitespace. If the string `S` represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed: ``` >>> lines = ("line 1 \r\n" ... "\r\n" ... "\r\n") >>> lines.rstrip("\n\r") 'line 1 ' ``` Since this is typically only desired when reading text one line at a time, using `S.rstrip()` this way works well. ### Is there a scanf() or sscanf() equivalent? Not as such. For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the [`split()`](../library/stdtypes#str.split "str.split") method of string objects and then convert decimal strings to numeric values using [`int()`](../library/functions#int "int") or [`float()`](../library/functions#float "float"). `split()` supports an optional “sep” parameter which is useful if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions are more powerful than C’s `sscanf()` and better suited for the task. ### What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean? See the [Unicode HOWTO](../howto/unicode#unicode-howto). Performance ----------- ### My program is too slow. How do I speed it up? That’s a tough one, in general. First, here are a list of things to remember before diving further: * Performance characteristics vary across Python implementations. This FAQ focuses on [CPython](../glossary#term-cpython). * Behaviour can vary across operating systems, especially when talking about I/O or multi-threading. * You should always find the hot spots in your program *before* attempting to optimize any code (see the [`profile`](../library/profile#module-profile "profile: Python source profiler.") module). * Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the [`timeit`](../library/timeit#module-timeit "timeit: Measure the execution time of small code snippets.") module). * It is highly recommended to have good code coverage (through unit testing or any other technique) before potentially introducing regressions hidden in sophisticated optimizations. That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels: * Making your algorithms faster (or changing to faster ones) can yield much larger benefits than trying to sprinkle micro-optimization tricks all over your code. * Use the right data structures. Study documentation for the [Built-in Types](../library/stdtypes#bltin-types) and the [`collections`](../library/collections#module-collections "collections: Container datatypes") module. * When the standard library provides a primitive for doing something, it is likely (although not guaranteed) to be faster than any alternative you may come up with. This is doubly true for primitives written in C, such as builtins and some extension types. For example, be sure to use either the [`list.sort()`](../library/stdtypes#list.sort "list.sort") built-in method or the related [`sorted()`](../library/functions#sorted "sorted") function to do sorting (and see the [Sorting HOW TO](../howto/sorting#sortinghowto) for examples of moderately advanced usage). * Abstractions tend to create indirections and force the interpreter to work more. If the levels of indirection outweigh the amount of useful work done, your program will be slower. You should avoid excessive abstraction, especially under the form of tiny functions or methods (which are also often detrimental to readability). If you have reached the limit of what pure Python can allow, there are tools to take you further away. For example, [Cython](http://cython.org) can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. Cython can take advantage of compilation (and optional type annotations) to make your code significantly faster than when interpreted. If you are confident in your C programming skills, you can also [write a C extension module](../extending/index#extending-index) yourself. See also The wiki page devoted to [performance tips](https://wiki.python.org/moin/PythonSpeed/PerformanceTips). ### What is the most efficient way to concatenate many strings together? [`str`](../library/stdtypes#str "str") and [`bytes`](../library/stdtypes#bytes "bytes") objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length. To accumulate many [`str`](../library/stdtypes#str "str") objects, the recommended idiom is to place them into a list and call [`str.join()`](../library/stdtypes#str.join "str.join") at the end: ``` chunks = [] for s in my_strings: chunks.append(s) result = ''.join(chunks) ``` (another reasonably efficient idiom is to use [`io.StringIO`](../library/io#io.StringIO "io.StringIO")) To accumulate many [`bytes`](../library/stdtypes#bytes "bytes") objects, the recommended idiom is to extend a [`bytearray`](../library/stdtypes#bytearray "bytearray") object using in-place concatenation (the `+=` operator): ``` result = bytearray() for b in my_bytes_objects: result += b ``` Sequences (Tuples/Lists) ------------------------ ### How do I convert between tuples and lists? The type constructor `tuple(seq)` converts any sequence (actually, any iterable) into a tuple with the same items in the same order. For example, `tuple([1, 2, 3])` yields `(1, 2, 3)` and `tuple('abc')` yields `('a', 'b', 'c')`. If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call [`tuple()`](../library/stdtypes#tuple "tuple") when you aren’t sure that an object is already a tuple. The type constructor `list(seq)` converts any sequence or iterable into a list with the same items in the same order. For example, `list((1, 2, 3))` yields `[1, 2, 3]` and `list('abc')` yields `['a', 'b', 'c']`. If the argument is a list, it makes a copy just like `seq[:]` would. ### What’s a negative index? Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of `seq[-n]` as the same as `seq[len(seq)-n]`. Using negative indices can be very convenient. For example `S[:-1]` is all of the string except for its last character, which is useful for removing the trailing newline from a string. ### How do I iterate over a sequence in reverse order? Use the [`reversed()`](../library/functions#reversed "reversed") built-in function: ``` for x in reversed(sequence): ... # do something with x ... ``` This won’t touch your original sequence, but build a new copy with reversed order to iterate over. ### How do you remove duplicates from a list? See the Python Cookbook for a long discussion of many ways to do this: <https://code.activestate.com/recipes/52560/> If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go: ``` if mylist: mylist.sort() last = mylist[-1] for i in range(len(mylist)-2, -1, -1): if last == mylist[i]: del mylist[i] else: last = mylist[i] ``` If all elements of the list may be used as set keys (i.e. they are all [hashable](../glossary#term-hashable)) this is often faster ``` mylist = list(set(mylist)) ``` This converts the list into a set, thereby removing duplicates, and then back into a list. ### How do you remove multiple items from a list As with removing duplicates, explicitly iterating in reverse with a delete condition is one possibility. However, it is easier and faster to use slice replacement with an implicit or explicit forward iteration. Here are three variations.: ``` mylist[:] = filter(keep_function, mylist) mylist[:] = (x for x in mylist if keep_condition) mylist[:] = [x for x in mylist if keep_condition] ``` The list comprehension may be fastest. ### How do you make an array in Python? Use a list: ``` ["this", 1, "is", "an", "array"] ``` Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types. The `array` module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that NumPy and other third party packages define array-like structures with various characteristics as well. To get Lisp-style linked lists, you can emulate cons cells using tuples: ``` lisp_list = ("like", ("this", ("example", None) ) ) ``` If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is `lisp_list[0]` and the analogue of cdr is `lisp_list[1]`. Only do this if you’re sure you really need to, because it’s usually a lot slower than using Python lists. ### How do I create a multidimensional list? You probably tried to make a multidimensional array like this: ``` >>> A = [[None] * 2] * 3 ``` This looks correct if you print it: ``` >>> A [[None, None], [None, None], [None, None]] ``` But when you assign a value, it shows up in multiple places: ``` >>> A[0][0] = 5 >>> A [[5, None], [5, None], [5, None]] ``` The reason is that replicating a list with `*` doesn’t create copies, it only creates references to the existing objects. The `*3` creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want. The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list: ``` A = [None] * 3 for i in range(3): A[i] = [None] * 2 ``` This generates a list containing 3 different lists of length two. You can also use a list comprehension: ``` w, h = 2, 3 A = [[None] * w for i in range(h)] ``` Or, you can use an extension that provides a matrix datatype; [NumPy](http://www.numpy.org/) is the best known. ### How do I apply a method to a sequence of objects? Use a list comprehension: ``` result = [obj.method() for obj in mylist] ``` ### Why does a\_tuple[i] += [‘item’] raise an exception when the addition works? This is because of a combination of the fact that augmented assignment operators are *assignment* operators, and the difference between mutable and immutable objects in Python. This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we’ll use a `list` and `+=` as our exemplar. If you wrote: ``` >>> a_tuple = (1, 2) >>> a_tuple[0] += 1 Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment ``` The reason for the exception should be immediately clear: `1` is added to the object `a_tuple[0]` points to (`1`), producing the result object, `2`, but when we attempt to assign the result of the computation, `2`, to element `0` of the tuple, we get an error because we can’t change what an element of a tuple points to. Under the covers, what this augmented assignment statement is doing is approximately this: ``` >>> result = a_tuple[0] + 1 >>> a_tuple[0] = result Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment ``` It is the assignment part of the operation that produces the error, since a tuple is immutable. When you write something like: ``` >>> a_tuple = (['foo'], 'bar') >>> a_tuple[0] += ['item'] Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment ``` The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked: ``` >>> a_tuple[0] ['foo', 'item'] ``` To see why this happens, you need to know that (a) if an object implements an `__iadd__` magic method, it gets called when the `+=` augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists, `__iadd__` is equivalent to calling `extend` on the list and returning the list. That’s why we say that for lists, `+=` is a “shorthand” for `list.extend`: ``` >>> a_list = [] >>> a_list += [1] >>> a_list [1] ``` This is equivalent to: ``` >>> result = a_list.__iadd__([1]) >>> a_list = result ``` The object pointed to by a\_list has been mutated, and the pointer to the mutated object is assigned back to `a_list`. The end result of the assignment is a no-op, since it is a pointer to the same object that `a_list` was previously pointing to, but the assignment still happens. Thus, in our tuple example what is happening is equivalent to: ``` >>> result = a_tuple[0].__iadd__(['item']) >>> a_tuple[0] = result Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment ``` The `__iadd__` succeeds, and thus the list is extended, but even though `result` points to the same object that `a_tuple[0]` already points to, that final assignment still results in an error, because tuples are immutable. ### I want to do a complicated sort: can you do a Schwartzian Transform in Python? The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its “sort value”. In Python, use the `key` argument for the [`list.sort()`](../library/stdtypes#list.sort "list.sort") method: ``` Isorted = L[:] Isorted.sort(key=lambda s: int(s[10:15])) ``` ### How can I sort one list by values from another list? Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want. ``` >>> list1 = ["what", "I'm", "sorting", "by"] >>> list2 = ["something", "else", "to", "sort"] >>> pairs = zip(list1, list2) >>> pairs = sorted(pairs) >>> pairs [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')] >>> result = [x[1] for x in pairs] >>> result ['else', 'sort', 'to', 'something'] ``` Objects ------- ### What is a class? A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype. A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic `Mailbox` class that provides basic accessor methods for a mailbox, and subclasses such as `MboxMailbox`, `MaildirMailbox`, `OutlookMailbox` that handle various specific mailbox formats. ### What is a method? A method is a function on some object `x` that you normally call as `x.name(arguments...)`. Methods are defined as functions inside the class definition: ``` class C: def meth(self, arg): return arg * 2 + self.attribute ``` ### What is self? Self is merely a conventional name for the first argument of a method. A method defined as `meth(self, a, b, c)` should be called as `x.meth(a, b, c)` for some instance `x` of the class in which the definition occurs; the called method will think it is called as `meth(x, a, b, c)`. See also [Why must ‘self’ be used explicitly in method definitions and calls?](design#why-self). ### How do I check if an object is an instance of a given class or of a subclass of it? Use the built-in function `isinstance(obj, cls)`. You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. `isinstance(obj, (class1, class2, ...))`, and can also check whether an object is one of Python’s built-in types, e.g. `isinstance(obj, str)` or `isinstance(obj, (int, float, complex))`. Note that [`isinstance()`](../library/functions#isinstance "isinstance") also checks for virtual inheritance from an [abstract base class](../glossary#term-abstract-base-class). So, the test will return `True` for a registered class even if hasn’t directly or indirectly inherited from it. To test for “true inheritance”, scan the [MRO](../glossary#term-mro) of the class: ``` from collections.abc import Mapping class P: pass class C(P): pass Mapping.register(P) ``` ``` >>> c = C() >>> isinstance(c, C) # direct True >>> isinstance(c, P) # indirect True >>> isinstance(c, Mapping) # virtual True # Actual inheritance chain >>> type(c).__mro__ (<class 'C'>, <class 'P'>, <class 'object'>) # Test for "true inheritance" >>> Mapping in type(c).__mro__ False ``` Note that most programs do not use [`isinstance()`](../library/functions#isinstance "isinstance") on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something: ``` def search(obj): if isinstance(obj, Mailbox): ... # code to search a mailbox elif isinstance(obj, Document): ... # code to search a document elif ... ``` A better approach is to define a `search()` method on all the classes and just call it: ``` class Mailbox: def search(self): ... # code to search a mailbox class Document: def search(self): ... # code to search a document obj.search() ``` ### What is delegation? Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object `x` and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you’re interested in changing and delegates all other methods to the corresponding method of `x`. Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase: ``` class UpperOut: def __init__(self, outfile): self._outfile = outfile def write(self, s): self._outfile.write(s.upper()) def __getattr__(self, name): return getattr(self._outfile, name) ``` Here the `UpperOut` class redefines the `write()` method to convert the argument string to uppercase before calling the underlying `self._outfile.write()` method. All other methods are delegated to the underlying `self._outfile` object. The delegation is accomplished via the `__getattr__` method; consult [the language reference](../reference/datamodel#attribute-access) for more information about controlling attribute access. Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") method too, and it must do so carefully. The basic implementation of [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") is roughly equivalent to the following: ``` class X: ... def __setattr__(self, name, value): self.__dict__[name] = value ... ``` Most [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") implementations must modify `self.__dict__` to store local state for self without causing an infinite recursion. ### How do I call a method defined in a base class from a derived class that overrides it? Use the built-in [`super()`](../library/functions#super "super") function: ``` class Derived(Base): def meth(self): super(Derived, self).meth() ``` For version prior to 3.0, you may be using classic classes: For a class definition such as `class Derived(Base): ...` you can call method `meth()` defined in `Base` (or one of `Base`’s base classes) as `Base.meth(self, arguments...)`. Here, `Base.meth` is an unbound method, so you need to provide the `self` argument. ### How can I organize my code to make it easier to change the base class? You could assign the base class to an alias and derive from the alias. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example: ``` class Base: ... BaseAlias = Base class Derived(BaseAlias): ... ``` ### How do I create static class data and static class methods? Both static data and static methods (in the sense of C++ or Java) are supported in Python. For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment: ``` class C: count = 0 # number of times C.__init__ called def __init__(self): C.count = C.count + 1 def getcount(self): return C.count # or return self.count ``` `c.count` also refers to `C.count` for any `c` such that `isinstance(c, C)` holds, unless overridden by `c` itself or by some class on the base-class search path from `c.__class__` back to `C`. Caution: within a method of C, an assignment like `self.count = 42` creates a new and unrelated instance named “count” in `self`’s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not: ``` C.count = 314 ``` Static methods are possible: ``` class C: @staticmethod def static(arg1, arg2, arg3): # No 'self' parameter! ... ``` However, a far more straightforward way to get the effect of a static method is via a simple module-level function: ``` def getcount(): return C.count ``` If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation. ### How can I overload constructors (or methods) in Python? This answer actually applies to all methods, but the question usually comes up first in the context of constructors. In C++ you’d write ``` class C { C() { cout << "No arguments\n"; } C(int i) { cout << "Argument is " << i << "\n"; } } ``` In Python you have to write a single constructor that catches all cases using default arguments. For example: ``` class C: def __init__(self, i=None): if i is None: print("No arguments") else: print("Argument is", i) ``` This is not entirely equivalent, but close enough in practice. You could also try a variable-length argument list, e.g. ``` def __init__(self, *args): ... ``` The same approach works for all method definitions. ### I try to use \_\_spam and I get an error about \_SomeClassName\_\_spam. Variable names with double leading underscores are “mangled” to provide a simple but effective way to define class private variables. Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where `classname` is the current class name with any leading underscores stripped. This doesn’t guarantee privacy: an outside user can still deliberately access the “\_classname\_\_spam” attribute, and private values are visible in the object’s `__dict__`. Many Python programmers never bother to use private variable names at all. ### My class defines \_\_del\_\_ but it is not called when I delete the object. There are several possible reasons for this. The del statement does not necessarily call [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") – it simply decrements the object’s reference count, and if this reaches zero [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") is called. If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method may be called at an inconvenient and random time. This is inconvenient if you’re trying to reproduce a problem. Worse, the order in which object’s [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") methods are executed is arbitrary. You can run [`gc.collect()`](../library/gc#gc.collect "gc.collect") to force a collection, but there *are* pathological cases where objects will never be collected. Despite the cycle collector, it’s still a good idea to define an explicit `close()` method on objects to be called whenever you’re done with them. The `close()` method can then remove attributes that refer to subobjects. Don’t call [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") directly – [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") should call `close()` and `close()` should make sure that it can be called more than once for the same object. Another way to avoid cyclical references is to use the [`weakref`](../library/weakref#module-weakref "weakref: Support for weak references and weak dictionaries.") module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!). Finally, if your [`__del__()`](../reference/datamodel#object.__del__ "object.__del__") method raises an exception, a warning message is printed to [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). ### How do I get a list of all instances of a given class? Python does not keep track of all instances of a class (or of a built-in type). You can program the class’s constructor to keep track of all instances by keeping a list of weak references to each instance. ### Why does the result of `id()` appear to be not unique? The [`id()`](../library/functions#id "id") builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object’s memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example: ``` >>> id(1000) 13901272 >>> id(2000) 13901272 ``` The two ids belong to different integer objects that are created before, and deleted immediately after execution of the `id()` call. To be sure that objects whose id you want to examine are still alive, create another reference to the object: ``` >>> a = 1000; b = 2000 >>> id(a) 13901272 >>> id(b) 13891296 ``` ### When can I rely on identity tests with the is operator? The `is` operator tests for object identity. The test `a is b` is equivalent to `id(a) == id(b)`. The most important property of an identity test is that an object is always identical to itself, `a is a` always returns `True`. Identity tests are usually faster than equality tests. And unlike equality tests, identity tests are guaranteed to return a boolean `True` or `False`. However, identity tests can *only* be substituted for equality tests when object identity is assured. Generally, there are three circumstances where identity is guaranteed: 1) Assignments create new names but do not change object identity. After the assignment `new = old`, it is guaranteed that `new is old`. 2) Putting an object in a container that stores object references does not change object identity. After the list assignment `s[0] = x`, it is guaranteed that `s[0] is x`. 3) If an object is a singleton, it means that only one instance of that object can exist. After the assignments `a = None` and `b = None`, it is guaranteed that `a is b` because `None` is a singleton. In most other circumstances, identity tests are inadvisable and equality tests are preferred. In particular, identity tests should not be used to check constants such as [`int`](../library/functions#int "int") and [`str`](../library/stdtypes#str "str") which aren’t guaranteed to be singletons: ``` >>> a = 1000 >>> b = 500 >>> c = b + 500 >>> a is c False >>> a = 'Python' >>> b = 'Py' >>> c = b + 'thon' >>> a is c False ``` Likewise, new instances of mutable containers are never identical: ``` >>> a = [] >>> b = [] >>> a is b False ``` In the standard library code, you will see several common patterns for correctly using identity tests: 1) As recommended by [**PEP 8**](https://www.python.org/dev/peps/pep-0008), an identity test is the preferred way to check for `None`. This reads like plain English in code and avoids confusion with other objects that may have boolean values that evaluate to false. 2) Detecting optional arguments can be tricky when `None` is a valid input value. In those situations, you can create a singleton sentinel object guaranteed to be distinct from other objects. For example, here is how to implement a method that behaves like [`dict.pop()`](../library/stdtypes#dict.pop "dict.pop"): ``` _sentinel = object() def pop(self, key, default=_sentinel): if key in self: value = self[key] del self[key] return value if default is _sentinel: raise KeyError(key) return default ``` 3) Container implementations sometimes need to augment equality tests with identity tests. This prevents the code from being confused by objects such as `float('NaN')` that are not equal to themselves. For example, here is the implementation of `collections.abc.Sequence.__contains__()`: ``` def __contains__(self, value): for v in self: if v is value or v == value: return True return False ``` ### How can a subclass control what data is stored in an immutable instance? When subclassing an immutable type, override the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method instead of the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method. The latter only runs *after* an instance is created, which is too late to alter data in an immutable instance. All of these immutable classes have a different signature than their parent class: ``` from datetime import date class FirstOfMonthDate(date): "Always choose the first day of the month" def __new__(cls, year, month, day): return super().__new__(cls, year, month, 1) class NamedInt(int): "Allow text names for some numbers" xlat = {'zero': 0, 'one': 1, 'ten': 10} def __new__(cls, value): value = cls.xlat.get(value, value) return super().__new__(cls, value) class TitleStr(str): "Convert str to name suitable for a URL path" def __new__(cls, s): s = s.lower().replace(' ', '-') s = ''.join([c for c in s if c.isalnum() or c == '-']) return super().__new__(cls, s) ``` The classes can be used like this: ``` >>> FirstOfMonthDate(2012, 2, 14) FirstOfMonthDate(2012, 2, 1) >>> NamedInt('ten') 10 >>> NamedInt(20) 20 >>> TitleStr('Blog: Why Python Rocks') 'blog-why-python-rocks' ``` Modules ------- ### How do I create a .pyc file? When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a `.pyc` file containing the compiled code should be created in a `__pycache__` subdirectory of the directory containing the `.py` file. The `.pyc` file will have a filename that starts with the same name as the `.py` file, and ends with `.pyc`, with a middle component that depends on the particular `python` binary that created it. (See [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) for details.) One reason that a `.pyc` file may not be created is a permissions problem with the directory containing the source file, meaning that the `__pycache__` subdirectory cannot be created. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. Unless the [`PYTHONDONTWRITEBYTECODE`](../using/cmdline#envvar-PYTHONDONTWRITEBYTECODE) environment variable is set, creation of a .pyc file is automatic if you’re importing a module and Python has the ability (permissions, free space, etc…) to create a `__pycache__` subdirectory and write the compiled module to that subdirectory. Running Python on a top level script is not considered an import and no `.pyc` will be created. For example, if you have a top-level module `foo.py` that imports another module `xyz.py`, when you run `foo` (by typing `python foo.py` as a shell command), a `.pyc` will be created for `xyz` because `xyz` is imported, but no `.pyc` file will be created for `foo` since `foo.py` isn’t being imported. If you need to create a `.pyc` file for `foo` – that is, to create a `.pyc` file for a module that is not imported – you can, using the [`py_compile`](../library/py_compile#module-py_compile "py_compile: Generate byte-code files from Python source files.") and [`compileall`](../library/compileall#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") modules. The [`py_compile`](../library/py_compile#module-py_compile "py_compile: Generate byte-code files from Python source files.") module can manually compile any module. One way is to use the `compile()` function in that module interactively: ``` >>> import py_compile >>> py_compile.compile('foo.py') ``` This will write the `.pyc` to a `__pycache__` subdirectory in the same location as `foo.py` (or you can override that with the optional parameter `cfile`). You can also automatically compile all files in a directory or directories using the [`compileall`](../library/compileall#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") module. You can do it from the shell prompt by running `compileall.py` and providing the path of a directory containing Python files to compile: ``` python -m compileall . ``` ### How do I find the current module name? A module can find out its own module name by looking at the predefined global variable `__name__`. If this has the value `'__main__'`, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking `__name__`: ``` def main(): print('Running test...') ... if __name__ == '__main__': main() ``` ### How can I have modules that mutually import each other? Suppose you have the following modules: foo.py: ``` from bar import bar_var foo_var = 1 ``` bar.py: ``` from foo import foo_var bar_var = 2 ``` The problem is that the interpreter will perform the following steps: * main imports foo * Empty globals for foo are created * foo is compiled and starts executing * foo imports bar * Empty globals for bar are created * bar is compiled and starts executing * bar imports foo (which is a no-op since there already is a module named foo) * bar.foo\_var = foo.foo\_var The last step fails, because Python isn’t done with interpreting `foo` yet and the global symbol dictionary for `foo` is still empty. The same thing happens when you use `import foo`, and then try to access `foo.foo_var` in global code. There are (at least) three possible workarounds for this problem. Guido van Rossum recommends avoiding all uses of `from <module> import ...`, and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as `<module>.<name>`. Jim Roskind suggests performing steps in the following order in each module: * exports (globals, functions, and classes that don’t need imported base classes) * `import` statements * active code (including globals that are initialized from imported values). Van Rossum doesn’t like this approach much because the imports appear in a strange place, but it does work. Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place. These solutions are not mutually exclusive. ### \_\_import\_\_(‘x.y.z’) returns <module ‘x’>; how do I get z? Consider using the convenience function [`import_module()`](../library/importlib#importlib.import_module "importlib.import_module") from [`importlib`](../library/importlib#module-importlib "importlib: The implementation of the import machinery.") instead: ``` z = importlib.import_module('x.y.z') ``` ### When I edit an imported module and reimport it, the changes don’t show up. Why does this happen? For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn’t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force re-reading of a changed module, do this: ``` import importlib import modname importlib.reload(modname) ``` Warning: this technique is not 100% fool-proof. In particular, modules containing statements like ``` from modname import some_objects ``` will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will *not* be updated to use the new class definition. This can result in the following paradoxical behaviour: ``` >>> import importlib >>> import cls >>> c = cls.C() # Create an instance of C >>> importlib.reload(cls) <module 'cls' from 'cls.py'> >>> isinstance(c, cls.C) # isinstance is false?!? False ``` The nature of the problem is made clear if you print out the “identity” of the class objects: ``` >>> hex(id(c.__class__)) '0x7352a0' >>> hex(id(cls.C)) '0x4198d0' ```
programming_docs
python Extending/Embedding FAQ Extending/Embedding FAQ ======================= * [Can I create my own functions in C?](#can-i-create-my-own-functions-in-c) * [Can I create my own functions in C++?](#id1) * [Writing C is hard; are there any alternatives?](#writing-c-is-hard-are-there-any-alternatives) * [How can I execute arbitrary Python statements from C?](#how-can-i-execute-arbitrary-python-statements-from-c) * [How can I evaluate an arbitrary Python expression from C?](#how-can-i-evaluate-an-arbitrary-python-expression-from-c) * [How do I extract C values from a Python object?](#how-do-i-extract-c-values-from-a-python-object) * [How do I use Py\_BuildValue() to create a tuple of arbitrary length?](#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length) * [How do I call an object’s method from C?](#how-do-i-call-an-object-s-method-from-c) * [How do I catch the output from PyErr\_Print() (or anything that prints to stdout/stderr)?](#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr) * [How do I access a module written in Python from C?](#how-do-i-access-a-module-written-in-python-from-c) * [How do I interface to C++ objects from Python?](#how-do-i-interface-to-c-objects-from-python) * [I added a module using the Setup file and the make fails; why?](#i-added-a-module-using-the-setup-file-and-the-make-fails-why) * [How do I debug an extension?](#how-do-i-debug-an-extension) * [I want to compile a Python module on my Linux system, but some files are missing. Why?](#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why) * [How do I tell “incomplete input” from “invalid input”?](#how-do-i-tell-incomplete-input-from-invalid-input) * [How do I find undefined g++ symbols \_\_builtin\_new or \_\_pure\_virtual?](#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual) * [Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?](#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance) Can I create my own functions in C? ----------------------------------- Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C. This is explained in the document [Extending and Embedding the Python Interpreter](../extending/index#extending-index). Most intermediate or advanced Python books will also cover this topic. Can I create my own functions in C++? ------------------------------------- Yes, using the C compatibility features found in C++. Place `extern "C" { ... }` around the Python include files and put `extern "C"` before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea. Writing C is hard; are there any alternatives? ---------------------------------------------- There are a number of alternatives to writing your own C extensions, depending on what you’re trying to do. [Cython](http://cython.org) and its relative [Pyrex](https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) are compilers that accept a slightly modified form of Python and generate the corresponding C code. Cython and Pyrex make it possible to write an extension without having to learn Python’s C API. If you need to interface to some C or C++ library for which no Python extension currently exists, you can try wrapping the library’s data types and functions with a tool such as [SWIG](http://www.swig.org). [SIP](https://riverbankcomputing.com/software/sip/intro), [CXX](http://cxx.sourceforge.net/) [Boost](http://www.boost.org/libs/python/doc/index.html), or [Weave](https://github.com/scipy/weave) are also alternatives for wrapping C++ libraries. How can I execute arbitrary Python statements from C? ----------------------------------------------------- The highest-level function to do this is [`PyRun_SimpleString()`](../c-api/veryhigh#c.PyRun_SimpleString "PyRun_SimpleString") which takes a single string argument to be executed in the context of the module `__main__` and returns `0` for success and `-1` when an exception occurred (including [`SyntaxError`](../library/exceptions#SyntaxError "SyntaxError")). If you want more control, use [`PyRun_String()`](../c-api/veryhigh#c.PyRun_String "PyRun_String"); see the source for [`PyRun_SimpleString()`](../c-api/veryhigh#c.PyRun_SimpleString "PyRun_SimpleString") in `Python/pythonrun.c`. How can I evaluate an arbitrary Python expression from C? --------------------------------------------------------- Call the function [`PyRun_String()`](../c-api/veryhigh#c.PyRun_String "PyRun_String") from the previous question with the start symbol [`Py_eval_input`](../c-api/veryhigh#c.Py_eval_input "Py_eval_input"); it parses an expression, evaluates it and returns its value. How do I extract C values from a Python object? ----------------------------------------------- That depends on the object’s type. If it’s a tuple, [`PyTuple_Size()`](../c-api/tuple#c.PyTuple_Size "PyTuple_Size") returns its length and [`PyTuple_GetItem()`](../c-api/tuple#c.PyTuple_GetItem "PyTuple_GetItem") returns the item at a specified index. Lists have similar functions, `PyListSize()` and [`PyList_GetItem()`](../c-api/list#c.PyList_GetItem "PyList_GetItem"). For bytes, [`PyBytes_Size()`](../c-api/bytes#c.PyBytes_Size "PyBytes_Size") returns its length and [`PyBytes_AsStringAndSize()`](../c-api/bytes#c.PyBytes_AsStringAndSize "PyBytes_AsStringAndSize") provides a pointer to its value and its length. Note that Python bytes objects may contain null bytes so C’s `strlen()` should not be used. To test the type of an object, first make sure it isn’t `NULL`, and then use [`PyBytes_Check()`](../c-api/bytes#c.PyBytes_Check "PyBytes_Check"), [`PyTuple_Check()`](../c-api/tuple#c.PyTuple_Check "PyTuple_Check"), [`PyList_Check()`](../c-api/list#c.PyList_Check "PyList_Check"), etc. There is also a high-level API to Python objects which is provided by the so-called ‘abstract’ interface – read `Include/abstract.h` for further details. It allows interfacing with any kind of Python sequence using calls like [`PySequence_Length()`](../c-api/sequence#c.PySequence_Length "PySequence_Length"), [`PySequence_GetItem()`](../c-api/sequence#c.PySequence_GetItem "PySequence_GetItem"), etc. as well as many other useful protocols such as numbers ([`PyNumber_Index()`](../c-api/number#c.PyNumber_Index "PyNumber_Index") et al.) and mappings in the PyMapping APIs. How do I use Py\_BuildValue() to create a tuple of arbitrary length? -------------------------------------------------------------------- You can’t. Use [`PyTuple_Pack()`](../c-api/tuple#c.PyTuple_Pack "PyTuple_Pack") instead. How do I call an object’s method from C? ---------------------------------------- The [`PyObject_CallMethod()`](../c-api/call#c.PyObject_CallMethod "PyObject_CallMethod") function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with [`Py_BuildValue()`](../c-api/arg#c.Py_BuildValue "Py_BuildValue"), and the argument values: ``` PyObject * PyObject_CallMethod(PyObject *object, const char *method_name, const char *arg_format, ...); ``` This works for any object that has methods – whether built-in or user-defined. You are responsible for eventually [`Py_DECREF()`](../c-api/refcounting#c.Py_DECREF "Py_DECREF")’ing the return value. To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming the file object pointer is “f”): ``` res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); if (res == NULL) { ... an exception occurred ... } else { Py_DECREF(res); } ``` Note that since [`PyObject_CallObject()`](../c-api/call#c.PyObject_CallObject "PyObject_CallObject") *always* wants a tuple for the argument list, to call a function without arguments, pass “()” for the format, and to call a function with one argument, surround the argument in parentheses, e.g. “(i)”. How do I catch the output from PyErr\_Print() (or anything that prints to stdout/stderr)? ----------------------------------------------------------------------------------------- In Python code, define an object that supports the `write()` method. Assign this object to [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") and [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). Call print\_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your `write()` method sends it. The easiest way to do this is to use the [`io.StringIO`](../library/io#io.StringIO "io.StringIO") class: ``` >>> import io, sys >>> sys.stdout = io.StringIO() >>> print('foo') >>> print('hello world!') >>> sys.stderr.write(sys.stdout.getvalue()) foo hello world! ``` A custom object to do the same would look like this: ``` >>> import io, sys >>> class StdoutCatcher(io.TextIOBase): ... def __init__(self): ... self.data = [] ... def write(self, stuff): ... self.data.append(stuff) ... >>> import sys >>> sys.stdout = StdoutCatcher() >>> print('foo') >>> print('hello world!') >>> sys.stderr.write(''.join(sys.stdout.data)) foo hello world! ``` How do I access a module written in Python from C? -------------------------------------------------- You can get a pointer to the module object as follows: ``` module = PyImport_ImportModule("<modulename>"); ``` If the module hasn’t been imported yet (i.e. it is not yet present in [`sys.modules`](../library/sys#sys.modules "sys.modules")), this initializes the module; otherwise it simply returns the value of `sys.modules["<modulename>"]`. Note that it doesn’t enter the module into any namespace – it only ensures it has been initialized and is stored in [`sys.modules`](../library/sys#sys.modules "sys.modules"). You can then access the module’s attributes (i.e. any name defined in the module) as follows: ``` attr = PyObject_GetAttrString(module, "<attrname>"); ``` Calling [`PyObject_SetAttrString()`](../c-api/object#c.PyObject_SetAttrString "PyObject_SetAttrString") to assign to variables in the module also works. How do I interface to C++ objects from Python? ---------------------------------------------- Depending on your requirements, there are many approaches. To do this manually, begin by reading [the “Extending and Embedding” document](../extending/index#extending-index). Realize that for the Python run-time system, there isn’t a whole lot of difference between C and C++ – so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects. For C++ libraries, see [Writing C is hard; are there any alternatives?](#c-wrapper-software). I added a module using the Setup file and the make fails; why? -------------------------------------------------------------- Setup must end in a newline, if there is no newline there, the build process fails. (Fixing this requires some ugly shell script hackery, and this bug is so minor that it doesn’t seem worth the effort.) How do I debug an extension? ---------------------------- When using GDB with dynamically loaded extensions, you can’t set a breakpoint in your extension until your extension is loaded. In your `.gdbinit` file (or interactively), add the command: ``` br _PyImport_LoadDynamicModule ``` Then, when you run GDB: ``` $ gdb /local/bin/python gdb) run myscript.py gdb) continue # repeat until your extension is loaded gdb) finish # so that your extension is loaded gdb) br myfunction.c:50 gdb) continue ``` I want to compile a Python module on my Linux system, but some files are missing. Why? -------------------------------------------------------------------------------------- Most packaged versions of Python don’t include the `/usr/lib/python2.*x*/config/` directory, which contains various files required for compiling Python extensions. For Red Hat, install the python-devel RPM to get the necessary files. For Debian, run `apt-get install python-dev`. How do I tell “incomplete input” from “invalid input”? ------------------------------------------------------ Sometimes you want to emulate the Python interactive interpreter’s behavior, where it gives you a continuation prompt when the input is incomplete (e.g. you typed the start of an “if” statement or you didn’t close your parentheses or triple string quotes), but it gives you a syntax error message immediately when the input is invalid. In Python you can use the [`codeop`](../library/codeop#module-codeop "codeop: Compile (possibly incomplete) Python code.") module, which approximates the parser’s behavior sufficiently. IDLE uses this, for example. The easiest way to do it in C is to call [`PyRun_InteractiveLoop()`](../c-api/veryhigh#c.PyRun_InteractiveLoop "PyRun_InteractiveLoop") (perhaps in a separate thread) and let the Python interpreter handle the input for you. You can also set the [`PyOS_ReadlineFunctionPointer()`](../c-api/veryhigh#c.PyOS_ReadlineFunctionPointer "PyOS_ReadlineFunctionPointer") to point at your custom input function. See `Modules/readline.c` and `Parser/myreadline.c` for more hints. How do I find undefined g++ symbols \_\_builtin\_new or \_\_pure\_virtual? -------------------------------------------------------------------------- To dynamically load g++ extension modules, you must recompile Python, relink it using g++ (change LINKCC in the Python Modules Makefile), and link your extension module using g++ (e.g., `g++ -shared -o mymodule.so mymodule.o`). Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? ---------------------------------------------------------------------------------------------------------------- Yes, you can inherit from built-in classes such as [`int`](../library/functions#int "int"), [`list`](../library/stdtypes#list "list"), [`dict`](../library/stdtypes#dict "dict"), etc. The Boost Python Library (BPL, <http://www.boost.org/libs/python/doc/index.html>) provides a way of doing this from C++ (i.e. you can inherit from an extension class written in C++ using the BPL). python Graphic User Interface FAQ Graphic User Interface FAQ ========================== * [General GUI Questions](#general-gui-questions) * [What GUI toolkits exist for Python?](#what-gui-toolkits-exist-for-python) * [Tkinter questions](#tkinter-questions) + [How do I freeze Tkinter applications?](#how-do-i-freeze-tkinter-applications) + [Can I have Tk events handled while waiting for I/O?](#can-i-have-tk-events-handled-while-waiting-for-i-o) + [I can’t get key bindings to work in Tkinter: why?](#i-can-t-get-key-bindings-to-work-in-tkinter-why) General GUI Questions --------------------- What GUI toolkits exist for Python? ----------------------------------- Standard builds of Python include an object-oriented interface to the Tcl/Tk widget set, called [tkinter](../library/tk#tkinter). This is probably the easiest to install (since it comes included with most [binary distributions](https://www.python.org/downloads/) of Python) and use. For more info about Tk, including pointers to the source, see the [Tcl/Tk home page](https://www.tcl.tk). Tcl/Tk is fully portable to the macOS, Windows, and Unix platforms. Depending on what platform(s) you are aiming at, there are also several alternatives. A [list of cross-platform](https://wiki.python.org/moin/GuiProgramming#Cross-Platform_Frameworks) and [platform-specific](https://wiki.python.org/moin/GuiProgramming#Platform-specific_Frameworks) GUI frameworks can be found on the python wiki. Tkinter questions ----------------- ### How do I freeze Tkinter applications? Freeze is a tool to create stand-alone applications. When freezing Tkinter applications, the applications will not be truly stand-alone, as the application will still need the Tcl and Tk libraries. One solution is to ship the application with the Tcl and Tk libraries, and point to them at run-time using the `TCL_LIBRARY` and `TK_LIBRARY` environment variables. To get truly stand-alone applications, the Tcl scripts that form the library have to be integrated into the application as well. One tool supporting that is SAM (stand-alone modules), which is part of the Tix distribution (<http://tix.sourceforge.net/>). Build Tix with SAM enabled, perform the appropriate call to `Tclsam_init()`, etc. inside Python’s `Modules/tkappinit.c`, and link with libtclsam and libtksam (you might include the Tix libraries as well). ### Can I have Tk events handled while waiting for I/O? On platforms other than Windows, yes, and you don’t even need threads! But you’ll have to restructure your I/O code a bit. Tk has the equivalent of Xt’s `XtAddInput()` call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. See [File Handlers](../library/tkinter#tkinter-file-handlers). ### I can’t get key bindings to work in Tkinter: why? An often-heard complaint is that event handlers bound to events with the `bind()` method don’t get handled even when the appropriate key is pressed. The most common cause is that the widget to which the binding applies doesn’t have “keyboard focus”. Check out the Tk documentation for the focus command. Usually a widget is given the keyboard focus by clicking in it (but not for labels; see the takefocus option). python General Python FAQ General Python FAQ ================== * [General Information](#general-information) + [What is Python?](#what-is-python) + [What is the Python Software Foundation?](#what-is-the-python-software-foundation) + [Are there copyright restrictions on the use of Python?](#are-there-copyright-restrictions-on-the-use-of-python) + [Why was Python created in the first place?](#why-was-python-created-in-the-first-place) + [What is Python good for?](#what-is-python-good-for) + [How does the Python version numbering scheme work?](#how-does-the-python-version-numbering-scheme-work) + [How do I obtain a copy of the Python source?](#how-do-i-obtain-a-copy-of-the-python-source) + [How do I get documentation on Python?](#how-do-i-get-documentation-on-python) + [I’ve never programmed before. Is there a Python tutorial?](#i-ve-never-programmed-before-is-there-a-python-tutorial) + [Is there a newsgroup or mailing list devoted to Python?](#is-there-a-newsgroup-or-mailing-list-devoted-to-python) + [How do I get a beta test version of Python?](#how-do-i-get-a-beta-test-version-of-python) + [How do I submit bug reports and patches for Python?](#how-do-i-submit-bug-reports-and-patches-for-python) + [Are there any published articles about Python that I can reference?](#are-there-any-published-articles-about-python-that-i-can-reference) + [Are there any books on Python?](#are-there-any-books-on-python) + [Where in the world is www.python.org located?](#where-in-the-world-is-www-python-org-located) + [Why is it called Python?](#why-is-it-called-python) + [Do I have to like “Monty Python’s Flying Circus”?](#do-i-have-to-like-monty-python-s-flying-circus) * [Python in the real world](#python-in-the-real-world) + [How stable is Python?](#how-stable-is-python) + [How many people are using Python?](#how-many-people-are-using-python) + [Have any significant projects been done in Python?](#have-any-significant-projects-been-done-in-python) + [What new developments are expected for Python in the future?](#what-new-developments-are-expected-for-python-in-the-future) + [Is it reasonable to propose incompatible changes to Python?](#is-it-reasonable-to-propose-incompatible-changes-to-python) + [Is Python a good language for beginning programmers?](#is-python-a-good-language-for-beginning-programmers) General Information ------------------- ### What is Python? Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. It supports multiple programming paradigms beyond object-oriented programming, such as procedural and functional programming. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants including Linux and macOS, and on Windows. To find out more, start with [The Python Tutorial](../tutorial/index#tutorial-index). The [Beginner’s Guide to Python](https://wiki.python.org/moin/BeginnersGuide) links to other introductory tutorials and resources for learning Python. ### What is the Python Software Foundation? The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF’s home page is at <https://www.python.org/psf/>. Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via [the PSF donation page](https://www.python.org/psf/donations/). ### Are there copyright restrictions on the use of Python? You can do anything you want with the source, as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce. If you honor the copyright rules, it’s OK to use Python for commercial use, to sell copies of Python in source or binary form (modified or unmodified), or to sell products that incorporate Python in some form. We would still like to know about all commercial use of Python, of course. See [the PSF license page](https://www.python.org/psf/license/) to find further explanations and a link to the full text of the license. The Python logo is trademarked, and in certain cases permission is required to use it. Consult [the Trademark Usage Policy](https://www.python.org/psf/trademarks/) for more information. ### Why was Python created in the first place? Here’s a *very* brief summary of what started it all, written by Guido van Rossum: I had extensive experience with implementing an interpreted language in the ABC group at CWI, and from working with this group I had learned a lot about language design. This is the origin of many Python features, including the use of indentation for statement grouping and the inclusion of very-high-level data types (although the details are all different in Python). I had a number of gripes about the ABC language, but also liked many of its features. It was impossible to extend the ABC language (or its implementation) to remedy my complaints – in fact its lack of extensibility was one of its biggest problems. I had some experience with using Modula-2+ and talked with the designers of Modula-3 and read the Modula-3 report. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features. I was working in the Amoeba distributed operating system group at CWI. We needed a better way to do system administration than by writing either C programs or Bourne shell scripts, since Amoeba had its own system call interface which wasn’t easily accessible from the Bourne shell. My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language feature. It occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need. I realized that it would be foolish to write an Amoeba-specific language, so I decided that I needed a language that was generally extensible. During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements. In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the `Misc/HISTORY` file. ### What is Python good for? Python is a high-level general-purpose programming language that can be applied to many different classes of problems. The language comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP/IP sockets). Look at the table of contents for [The Python Standard Library](../library/index#library-index) to get an idea of what’s available. A wide variety of third-party extensions are also available. Consult [the Python Package Index](https://pypi.org) to find packages of interest to you. ### How does the Python version numbering scheme work? Python versions are numbered A.B.C or A.B. A is the major version number – it is only incremented for really major changes in the language. B is the minor version number, incremented for less earth-shattering changes. C is the micro-level – it is incremented for each bugfix release. See [**PEP 6**](https://www.python.org/dev/peps/pep-0006) for more information about bugfix releases. Not all releases are bugfix releases. In the run-up to a new major release, a series of development releases are made, denoted as alpha, beta, or release candidate. Alphas are early releases in which interfaces aren’t yet finalized; it’s not unexpected to see an interface change between two alpha releases. Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs. Alpha, beta and release candidate versions have an additional suffix. The suffix for an alpha version is “aN” for some small number N, the suffix for a beta version is “bN” for some small number N, and the suffix for a release candidate version is “rcN” for some small number N. In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0rcN, and *those* precede 2.0. You may also find version numbers with a “+” suffix, e.g. “2.2+”. These are unreleased versions, built directly from the CPython development repository. In practice, after a final minor release is made, the version is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”. See also the documentation for [`sys.version`](../library/sys#sys.version "sys.version"), [`sys.hexversion`](../library/sys#sys.hexversion "sys.hexversion"), and [`sys.version_info`](../library/sys#sys.version_info "sys.version_info"). ### How do I obtain a copy of the Python source? The latest Python source distribution is always available from python.org, at <https://www.python.org/downloads/>. The latest development sources can be obtained at <https://github.com/python/cpython/>. The source distribution is a gzipped tar file containing the complete C source, Sphinx-formatted documentation, Python library modules, example programs, and several useful pieces of freely distributable software. The source will compile and run out of the box on most UNIX platforms. Consult the [Getting Started section of the Python Developer’s Guide](https://devguide.python.org/setup/) for more information on getting the source code and compiling it. ### How do I get documentation on Python? The standard documentation for the current stable version of Python is available at <https://docs.python.org/3/>. PDF, plain text, and downloadable HTML versions are also available at <https://docs.python.org/3/download.html>. The documentation is written in reStructuredText and processed by [the Sphinx documentation tool](http://sphinx-doc.org/). The reStructuredText source for the documentation is part of the Python source distribution. ### I’ve never programmed before. Is there a Python tutorial? There are numerous tutorials and books available. The standard documentation includes [The Python Tutorial](../tutorial/index#tutorial-index). Consult [the Beginner’s Guide](https://wiki.python.org/moin/BeginnersGuide) to find information for beginning Python programmers, including lists of tutorials. ### Is there a newsgroup or mailing list devoted to Python? There is a newsgroup, *comp.lang.python*, and a mailing list, [python-list](https://mail.python.org/mailman/listinfo/python-list). The newsgroup and mailing list are gatewayed into each other – if you can read news it’s unnecessary to subscribe to the mailing list. *comp.lang.python* is high-traffic, receiving hundreds of postings every day, and Usenet readers are often more able to cope with this volume. Announcements of new software releases and events can be found in comp.lang.python.announce, a low-traffic moderated list that receives about five postings per day. It’s available as [the python-announce mailing list](https://mail.python.org/mailman/listinfo/python-announce-list). More info about other mailing lists and newsgroups can be found at <https://www.python.org/community/lists/>. ### How do I get a beta test version of Python? Alpha and beta releases are available from <https://www.python.org/downloads/>. All releases are announced on the comp.lang.python and comp.lang.python.announce newsgroups and on the Python home page at <https://www.python.org/>; an RSS feed of news is available. You can also access the development version of Python through Git. See [The Python Developer’s Guide](https://devguide.python.org/) for details. ### How do I submit bug reports and patches for Python? To report a bug or submit a patch, please use the Roundup installation at <https://bugs.python.org/>. You must have a Roundup account to report bugs; this makes it possible for us to contact you if we have follow-up questions. It will also enable Roundup to send you updates as we act on your bug. If you had previously used SourceForge to report bugs to Python, you can obtain your Roundup password through Roundup’s [password reset procedure](https://bugs.python.org/user?@template=forgotten). For more information on how Python is developed, consult [the Python Developer’s Guide](https://devguide.python.org/). ### Are there any published articles about Python that I can reference? It’s probably best to cite your favorite book about Python. The very first article about Python was written in 1991 and is now quite outdated. Guido van Rossum and Jelke de Boer, “Interactively Testing Remote Servers Using the Python Programming Language”, CWI Quarterly, Volume 4, Issue 4 (December 1991), Amsterdam, pp 283–303. ### Are there any books on Python? Yes, there are many, and more are being published. See the python.org wiki at <https://wiki.python.org/moin/PythonBooks> for a list. You can also search online bookstores for “Python” and filter out the Monty Python references; or perhaps search for “Python” and “language”. ### Where in the world is www.python.org located? The Python project’s infrastructure is located all over the world and is managed by the Python Infrastructure Team. Details [here](http://infra.psf.io). ### Why is it called Python? When he began implementing Python, Guido van Rossum was also reading the published scripts from [“Monty Python’s Flying Circus”](https://en.wikipedia.org/wiki/Monty_Python), a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python. ### Do I have to like “Monty Python’s Flying Circus”? No, but it helps. :) Python in the real world ------------------------ ### How stable is Python? Very stable. New, stable releases have been coming out roughly every 6 to 18 months since 1991, and this seems likely to continue. As of version 3.9, Python will have a major new release every 12 months ([**PEP 602**](https://www.python.org/dev/peps/pep-0602)). The developers issue “bugfix” releases of older versions, so the stability of existing releases gradually improves. Bugfix releases, indicated by a third component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability; only fixes for known problems are included in a bugfix release, and it’s guaranteed that interfaces will remain the same throughout a series of bugfix releases. The latest stable releases can always be found on the [Python download page](https://www.python.org/downloads/). There are two production-ready versions of Python: 2.x and 3.x. The recommended version is 3.x, which is supported by most widely used libraries. Although 2.x is still widely used, [it is not maintained anymore](https://www.python.org/dev/peps/pep-0373/). ### How many people are using Python? There are probably millions of users, though it’s difficult to obtain an exact count. Python is available for free download, so there are no sales figures, and it’s available from many different sites and packaged with many Linux distributions, so download statistics don’t tell the whole story either. The comp.lang.python newsgroup is very active, but not all Python users post to the group or even read it. ### Have any significant projects been done in Python? See <https://www.python.org/about/success> for a list of projects that use Python. Consulting the proceedings for [past Python conferences](https://www.python.org/community/workshops/) will reveal contributions from many different companies and organizations. High-profile Python projects include [the Mailman mailing list manager](http://www.list.org) and [the Zope application server](http://www.zope.org). Several Linux distributions, most notably [Red Hat](https://www.redhat.com), have written part or all of their installer and system administration software in Python. Companies that use Python internally include Google, Yahoo, and Lucasfilm Ltd. ### What new developments are expected for Python in the future? See <https://www.python.org/dev/peps/> for the Python Enhancement Proposals (PEPs). PEPs are design documents describing a suggested new feature for Python, providing a concise technical specification and a rationale. Look for a PEP titled “Python X.Y Release Schedule”, where X.Y is a version that hasn’t been publicly released yet. New development is discussed on [the python-dev mailing list](https://mail.python.org/mailman/listinfo/python-dev/). ### Is it reasonable to propose incompatible changes to Python? In general, no. There are already millions of lines of Python code around the world, so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon. Even if you can provide a conversion program, there’s still the problem of updating all documentation; many books have been written about Python, and we don’t want to invalidate them all at a single stroke. Providing a gradual upgrade path is necessary if a feature has to be changed. [**PEP 5**](https://www.python.org/dev/peps/pep-0005) describes the procedure followed for introducing backward-incompatible changes while minimizing disruption for users. ### Is Python a good language for beginning programmers? Yes. It is still common to start students with a procedural and statically typed language such as Pascal, C, or a subset of C++ or Java. Students may be better served by learning Python as their first language. Python has a very simple and consistent syntax and a large standard library and, most importantly, using Python in a beginning programming course lets students concentrate on important programming skills such as problem decomposition and data type design. With Python, students can be quickly introduced to basic concepts such as loops and procedures. They can probably even work with user-defined objects in their very first course. For a student who has never programmed before, using a statically typed language seems unnatural. It presents additional complexity that the student must master and slows the pace of the course. The students are trying to learn to think like a computer, decompose problems, design consistent interfaces, and encapsulate data. While learning to use a statically typed language is important in the long term, it is not necessarily the best topic to address in the students’ first programming course. Many other aspects of Python make it a good first language. Like Java, Python has a large standard library so that students can be assigned programming projects very early in the course that *do* something. Assignments aren’t restricted to the standard four-function calculator and check balancing programs. By using the standard library, students can gain the satisfaction of working on realistic applications as they learn the fundamentals of programming. Using the standard library also teaches students about code reuse. Third-party modules such as PyGame are also helpful in extending the students’ reach. Python’s interactive interpreter enables students to test language features while they’re programming. They can keep a window with the interpreter running while they enter their program’s source in another window. If they can’t remember the methods for a list, they can do something like this: ``` >>> L = [] >>> dir(L) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> [d for d in dir(L) if '__' not in d] ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> help(L.append) Help on built-in function append: append(...) L.append(object) -> None -- append object to end >>> L.append(1) >>> L [1] ``` With the interpreter, documentation is never far from the student as they are programming. There are also good IDEs for Python. IDLE is a cross-platform IDE for Python that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. Emacs users will be happy to know that there is a very good Python mode for Emacs. All of these programming environments provide syntax highlighting, auto-indenting, and access to the interactive interpreter while coding. Consult [the Python wiki](https://wiki.python.org/moin/PythonEditors) for a full list of Python editing environments. If you want to discuss Python’s use in education, you may be interested in joining [the edu-sig mailing list](https://www.python.org/community/sigs/current/edu-sig).
programming_docs
python Using Python on Unix platforms Using Python on Unix platforms =============================== 2.1. Getting and installing the latest version of Python --------------------------------------------------------- ### 2.1.1. On Linux Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source. In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links: See also <https://www.debian.org/doc/manuals/maint-guide/first.en.html> for Debian users <https://en.opensuse.org/Portal:Packaging> for OpenSuse users <https://docs-old.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html> for Fedora users <http://www.slackbook.org/html/package-management-making-packages.html> for Slackware users ### 2.1.2. On FreeBSD and OpenBSD * FreeBSD users, to add the package use: ``` pkg install python3 ``` * OpenBSD users, to add the package use: ``` pkg_add -r python pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz ``` For example i386 users get the 2.5.1 version of Python using: ``` pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` ### 2.1.3. On OpenSolaris You can get Python from [OpenCSW](https://www.opencsw.org/). Various versions of Python are available and can be installed with e.g. `pkgutil -i python27`. 2.2. Building Python --------------------- If you want to compile CPython yourself, first thing you should do is get the [source](https://www.python.org/downloads/source/). You can download either the latest release’s source or just grab a fresh [clone](https://devguide.python.org/setup/#getting-the-source-code). (If you want to contribute patches, you will need a clone.) The build process consists of the usual commands: ``` ./configure make make install ``` Configuration options and caveats for specific Unix platforms are extensively documented in the [README.rst](https://github.com/python/cpython/tree/3.9/README.rst) file in the root of the Python source tree. Warning `make install` can overwrite or masquerade the `python3` binary. `make altinstall` is therefore recommended instead of `make install` since it only installs `*exec\_prefix*/bin/python*version*`. 2.3. Python-related paths and files ------------------------------------ These are subject to difference depending on local installation conventions; `prefix` (`${prefix}`) and `exec_prefix` (`${exec_prefix}`) are installation-dependent and should be interpreted as for GNU software; they may be the same. For example, on most Linux systems, the default for both is `/usr`. | File/directory | Meaning | | --- | --- | | `*exec\_prefix*/bin/python3` | Recommended location of the interpreter. | | `*prefix*/lib/python*version*`, `*exec\_prefix*/lib/python*version*` | Recommended locations of the directories containing the standard modules. | | `*prefix*/include/python*version*`, `*exec\_prefix*/include/python*version*` | Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter. | 2.4. Miscellaneous ------------------- To easily use Python scripts on Unix, you need to make them executable, e.g. with ``` $ chmod +x script ``` and put an appropriate Shebang line at the top of the script. A good choice is usually ``` #!/usr/bin/env python3 ``` which searches for the Python interpreter in the whole `PATH`. However, some Unices may not have the **env** command, so you may need to hardcode `/usr/bin/python3` as the interpreter path. To use shell commands in your Python scripts, look at the [`subprocess`](../library/subprocess#module-subprocess "subprocess: Subprocess management.") module. python Python Setup and Usage Python Setup and Usage ====================== This part of the documentation is devoted to general information on the setup of the Python environment on different platforms, the invocation of the interpreter and things that make working with Python easier. * [1. Command line and environment](cmdline) + [1.1. Command line](cmdline#command-line) - [1.1.1. Interface options](cmdline#interface-options) - [1.1.2. Generic options](cmdline#generic-options) - [1.1.3. Miscellaneous options](cmdline#miscellaneous-options) - [1.1.4. Options you shouldn’t use](cmdline#options-you-shouldn-t-use) + [1.2. Environment variables](cmdline#environment-variables) - [1.2.1. Debug-mode variables](cmdline#debug-mode-variables) * [2. Using Python on Unix platforms](unix) + [2.1. Getting and installing the latest version of Python](unix#getting-and-installing-the-latest-version-of-python) - [2.1.1. On Linux](unix#on-linux) - [2.1.2. On FreeBSD and OpenBSD](unix#on-freebsd-and-openbsd) - [2.1.3. On OpenSolaris](unix#on-opensolaris) + [2.2. Building Python](unix#building-python) + [2.3. Python-related paths and files](unix#python-related-paths-and-files) + [2.4. Miscellaneous](unix#miscellaneous) * [3. Using Python on Windows](windows) + [3.1. The full installer](windows#the-full-installer) - [3.1.1. Installation steps](windows#installation-steps) - [3.1.2. Removing the MAX\_PATH Limitation](windows#removing-the-max-path-limitation) - [3.1.3. Installing Without UI](windows#installing-without-ui) - [3.1.4. Installing Without Downloading](windows#installing-without-downloading) - [3.1.5. Modifying an install](windows#modifying-an-install) + [3.2. The Microsoft Store package](windows#the-microsoft-store-package) - [3.2.1. Known Issues](windows#known-issues) + [3.3. The nuget.org packages](windows#the-nuget-org-packages) + [3.4. The embeddable package](windows#the-embeddable-package) - [3.4.1. Python Application](windows#python-application) - [3.4.2. Embedding Python](windows#embedding-python) + [3.5. Alternative bundles](windows#alternative-bundles) + [3.6. Configuring Python](windows#configuring-python) - [3.6.1. Excursus: Setting environment variables](windows#excursus-setting-environment-variables) - [3.6.2. Finding the Python executable](windows#finding-the-python-executable) + [3.7. UTF-8 mode](windows#utf-8-mode) + [3.8. Python Launcher for Windows](windows#python-launcher-for-windows) - [3.8.1. Getting started](windows#getting-started) * [3.8.1.1. From the command-line](windows#from-the-command-line) * [3.8.1.2. Virtual environments](windows#virtual-environments) * [3.8.1.3. From a script](windows#from-a-script) * [3.8.1.4. From file associations](windows#from-file-associations) - [3.8.2. Shebang Lines](windows#shebang-lines) - [3.8.3. Arguments in shebang lines](windows#arguments-in-shebang-lines) - [3.8.4. Customization](windows#customization) * [3.8.4.1. Customization via INI files](windows#customization-via-ini-files) * [3.8.4.2. Customizing default Python versions](windows#customizing-default-python-versions) - [3.8.5. Diagnostics](windows#diagnostics) + [3.9. Finding modules](windows#finding-modules) + [3.10. Additional modules](windows#additional-modules) - [3.10.1. PyWin32](windows#pywin32) - [3.10.2. cx\_Freeze](windows#cx-freeze) + [3.11. Compiling Python on Windows](windows#compiling-python-on-windows) + [3.12. Other Platforms](windows#other-platforms) * [4. Using Python on a Mac](mac) + [4.1. Getting and Installing MacPython](mac#getting-and-installing-macpython) - [4.1.1. How to run a Python script](mac#how-to-run-a-python-script) - [4.1.2. Running scripts with a GUI](mac#running-scripts-with-a-gui) - [4.1.3. Configuration](mac#configuration) + [4.2. The IDE](mac#the-ide) + [4.3. Installing Additional Python Packages](mac#installing-additional-python-packages) + [4.4. GUI Programming on the Mac](mac#gui-programming-on-the-mac) + [4.5. Distributing Python Applications on the Mac](mac#distributing-python-applications-on-the-mac) + [4.6. Other Resources](mac#other-resources) * [5. Editors and IDEs](editors) python Command line and environment Command line and environment ============================= The CPython interpreter scans the command line and the environment for various settings. **CPython implementation detail:** Other implementations’ command line schemes may differ. See [Alternate Implementations](../reference/introduction#implementations) for further resources. 1.1. Command line ------------------ When invoking Python, you may specify any of these options: ``` python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args] ``` The most common use case is, of course, a simple invocation of a script: ``` python myscript.py ``` ### 1.1.1. Interface options The interpreter interface resembles that of the UNIX shell, but provides some additional methods of invocation: * When called with standard input connected to a tty device, it prompts for commands and executes them until an EOF (an end-of-file character, you can produce that with `Ctrl-D` on UNIX or `Ctrl-Z, Enter` on Windows) is read. * When called with a file name argument or with a file as standard input, it reads and executes a script from that file. * When called with a directory name argument, it reads and executes an appropriately named script from that directory. * When called with `-c command`, it executes the Python statement(s) given as *command*. Here *command* may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements! * When called with `-m module-name`, the given module is located on the Python module path and executed as a script. In non-interactive mode, the entire input is parsed before it is executed. An interface option terminates the list of options consumed by the interpreter, all consecutive arguments will end up in [`sys.argv`](../library/sys#sys.argv "sys.argv") – note that the first element, subscript zero (`sys.argv[0]`), is a string reflecting the program’s source. `-c <command>` Execute the Python code in *command*. *command* can be one or more statements separated by newlines, with significant leading whitespace as in normal module code. If this option is given, the first element of [`sys.argv`](../library/sys#sys.argv "sys.argv") will be `"-c"` and the current directory will be added to the start of [`sys.path`](../library/sys#sys.path "sys.path") (allowing modules in that directory to be imported as top level modules). Raises an [auditing event](../library/sys#auditing) `cpython.run_command` with argument `command`. `-m <module-name>` Search [`sys.path`](../library/sys#sys.path "sys.path") for the named module and execute its contents as the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module. Since the argument is a *module* name, you must not give a file extension (`.py`). The module name should be a valid absolute Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen). Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute `<pkg>.__main__` as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument. Note This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available. If this option is given, the first element of [`sys.argv`](../library/sys#sys.argv "sys.argv") will be the full path to the module file (while the module file is being located, the first element will be set to `"-m"`). As with the [`-c`](#cmdoption-c) option, the current directory will be added to the start of [`sys.path`](../library/sys#sys.path "sys.path"). [`-I`](#id2) option can be used to run the script in isolated mode where [`sys.path`](../library/sys#sys.path "sys.path") contains neither the current directory nor the user’s site-packages directory. All `PYTHON*` environment variables are ignored, too. Many standard library modules contain code that is invoked on their execution as a script. An example is the [`timeit`](../library/timeit#module-timeit "timeit: Measure the execution time of small code snippets.") module: ``` python -m timeit -s 'setup here' 'benchmarked code here' python -m timeit -h # for details ``` Raises an [auditing event](../library/sys#auditing) `cpython.run_module` with argument `module-name`. See also [`runpy.run_module()`](../library/runpy#runpy.run_module "runpy.run_module") Equivalent functionality directly available to Python code [**PEP 338**](https://www.python.org/dev/peps/pep-0338) – Executing modules as scripts Changed in version 3.1: Supply the package name to run a `__main__` submodule. Changed in version 3.4: namespace packages are also supported `-` Read commands from standard input ([`sys.stdin`](../library/sys#sys.stdin "sys.stdin")). If standard input is a terminal, [`-i`](#cmdoption-i) is implied. If this option is given, the first element of [`sys.argv`](../library/sys#sys.argv "sys.argv") will be `"-"` and the current directory will be added to the start of [`sys.path`](../library/sys#sys.path "sys.path"). Raises an [auditing event](../library/sys#auditing) `cpython.run_stdin` with no arguments. `<script>` Execute the Python code contained in *script*, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a `__main__.py` file, or a zipfile containing a `__main__.py` file. If this option is given, the first element of [`sys.argv`](../library/sys#sys.argv "sys.argv") will be the script name as given on the command line. If the script name refers directly to a Python file, the directory containing that file is added to the start of [`sys.path`](../library/sys#sys.path "sys.path"), and the file is executed as the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module. If the script name refers to a directory or zipfile, the script name is added to the start of [`sys.path`](../library/sys#sys.path "sys.path") and the `__main__.py` file in that location is executed as the [`__main__`](../library/__main__#module-__main__ "__main__: The environment where the top-level script is run.") module. [`-I`](#id2) option can be used to run the script in isolated mode where [`sys.path`](../library/sys#sys.path "sys.path") contains neither the script’s directory nor the user’s site-packages directory. All `PYTHON*` environment variables are ignored, too. Raises an [auditing event](../library/sys#auditing) `cpython.run_file` with argument `filename`. See also [`runpy.run_path()`](../library/runpy#runpy.run_path "runpy.run_path") Equivalent functionality directly available to Python code If no interface option is given, [`-i`](#cmdoption-i) is implied, `sys.argv[0]` is an empty string (`""`) and the current directory will be added to the start of [`sys.path`](../library/sys#sys.path "sys.path"). Also, tab-completion and history editing is automatically enabled, if available on your platform (see [Readline configuration](../library/site#rlcompleter-config)). See also [Invoking the Interpreter](../tutorial/interpreter#tut-invoking) Changed in version 3.4: Automatic enabling of tab-completion and history editing. ### 1.1.2. Generic options `-?` `-h` `--help` Print a short description of all command line options. `-V` `--version` Print the Python version number and exit. Example output could be: ``` Python 3.8.0b2+ ``` When given twice, print more information about the build, like: ``` Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00) [GCC 6.2.0 20161005] ``` New in version 3.6: The `-VV` option. ### 1.1.3. Miscellaneous options `-b` Issue a warning when comparing [`bytes`](../library/stdtypes#bytes "bytes") or [`bytearray`](../library/stdtypes#bytearray "bytearray") with [`str`](../library/stdtypes#str "str") or [`bytes`](../library/stdtypes#bytes "bytes") with [`int`](../library/functions#int "int"). Issue an error when the option is given twice (`-bb`). Changed in version 3.5: Affects comparisons of [`bytes`](../library/stdtypes#bytes "bytes") with [`int`](../library/functions#int "int"). `-B` If given, Python won’t try to write `.pyc` files on the import of source modules. See also [`PYTHONDONTWRITEBYTECODE`](#envvar-PYTHONDONTWRITEBYTECODE). `--check-hash-based-pycs default|always|never` Control the validation behavior of hash-based `.pyc` files. See [Cached bytecode invalidation](../reference/import#pyc-invalidation). When set to `default`, checked and unchecked hash-based bytecode cache files are validated according to their default semantics. When set to `always`, all hash-based `.pyc` files, whether checked or unchecked, are validated against their corresponding source file. When set to `never`, hash-based `.pyc` files are not validated against their corresponding source files. The semantics of timestamp-based `.pyc` files are unaffected by this option. `-d` Turn on parser debugging output (for expert only, depending on compilation options). See also [`PYTHONDEBUG`](#envvar-PYTHONDEBUG). `-E` Ignore all `PYTHON*` environment variables, e.g. [`PYTHONPATH`](#envvar-PYTHONPATH) and [`PYTHONHOME`](#envvar-PYTHONHOME), that might be set. `-i` When a script is passed as first argument or the [`-c`](#cmdoption-c) option is used, enter interactive mode after executing the script or the command, even when [`sys.stdin`](../library/sys#sys.stdin "sys.stdin") does not appear to be a terminal. The [`PYTHONSTARTUP`](#envvar-PYTHONSTARTUP) file is not read. This can be useful to inspect global variables or a stack trace when a script raises an exception. See also [`PYTHONINSPECT`](#envvar-PYTHONINSPECT). `-I` Run Python in isolated mode. This also implies -E and -s. In isolated mode [`sys.path`](../library/sys#sys.path "sys.path") contains neither the script’s directory nor the user’s site-packages directory. All `PYTHON*` environment variables are ignored, too. Further restrictions may be imposed to prevent the user from injecting malicious code. New in version 3.4. `-O` Remove assert statements and any code conditional on the value of [`__debug__`](../library/constants#__debug__ "__debug__"). Augment the filename for compiled ([bytecode](../glossary#term-bytecode)) files by adding `.opt-1` before the `.pyc` extension (see [**PEP 488**](https://www.python.org/dev/peps/pep-0488)). See also [`PYTHONOPTIMIZE`](#envvar-PYTHONOPTIMIZE). Changed in version 3.5: Modify `.pyc` filenames according to [**PEP 488**](https://www.python.org/dev/peps/pep-0488). `-OO` Do [`-O`](#cmdoption-o) and also discard docstrings. Augment the filename for compiled ([bytecode](../glossary#term-bytecode)) files by adding `.opt-2` before the `.pyc` extension (see [**PEP 488**](https://www.python.org/dev/peps/pep-0488)). Changed in version 3.5: Modify `.pyc` filenames according to [**PEP 488**](https://www.python.org/dev/peps/pep-0488). `-q` Don’t display the copyright and version messages even in interactive mode. New in version 3.2. `-R` Turn on hash randomization. This option only has an effect if the [`PYTHONHASHSEED`](#envvar-PYTHONHASHSEED) environment variable is set to `0`, since hash randomization is enabled by default. On previous versions of Python, this option turns on hash randomization, so that the [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") values of str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python. Hash randomization is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict construction, O(n2) complexity. See <http://www.ocert.org/advisories/ocert-2011-003.html> for details. [`PYTHONHASHSEED`](#envvar-PYTHONHASHSEED) allows you to set a fixed value for the hash seed secret. Changed in version 3.7: The option is no longer ignored. New in version 3.2.3. `-s` Don’t add the [`user site-packages directory`](../library/site#site.USER_SITE "site.USER_SITE") to [`sys.path`](../library/sys#sys.path "sys.path"). See also [**PEP 370**](https://www.python.org/dev/peps/pep-0370) – Per user site-packages directory `-S` Disable the import of the module [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") and the site-dependent manipulations of [`sys.path`](../library/sys#sys.path "sys.path") that it entails. Also disable these manipulations if [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") is explicitly imported later (call [`site.main()`](../library/site#site.main "site.main") if you want them to be triggered). `-u` Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream. See also [`PYTHONUNBUFFERED`](#envvar-PYTHONUNBUFFERED). Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered. `-v` Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice (`-vv`), print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. See also [`PYTHONVERBOSE`](#envvar-PYTHONVERBOSE). `-W arg` Warning control. Python’s warning machinery by default prints warning messages to [`sys.stderr`](../library/sys#sys.stderr "sys.stderr"). A typical warning message has the following form: ``` file:line: category: message ``` By default, each warning is printed once for each source line where it occurs. This option controls how often warnings are printed. Multiple [`-W`](#cmdoption-w) options may be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid [`-W`](#cmdoption-w) options are ignored (though, a warning message is printed about invalid options when the first warning is issued). Warnings can also be controlled using the [`PYTHONWARNINGS`](#envvar-PYTHONWARNINGS) environment variable and from within a Python program using the [`warnings`](../library/warnings#module-warnings "warnings: Issue warning messages and control their disposition.") module. The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default): ``` -Wdefault # Warn once per call location -Werror # Convert to exceptions -Walways # Warn every time -Wmodule # Warn once per calling module -Wonce # Warn once per Python process -Wignore # Never warn ``` The action names can be abbreviated as desired (e.g. `-Wi`, `-Wd`, `-Wa`, `-We`) and the interpreter will resolve them to the appropriate action name. See [The Warnings Filter](../library/warnings#warning-filter) and [Describing Warning Filters](../library/warnings#describing-warning-filters) for more details. `-x` Skip the first line of the source, allowing use of non-Unix forms of `#!cmd`. This is intended for a DOS specific hack only. `-X` Reserved for various implementation-specific options. CPython currently defines the following possible values: * `-X faulthandler` to enable [`faulthandler`](../library/faulthandler#module-faulthandler "faulthandler: Dump the Python traceback."); * `-X oldparser`: enable the traditional LL(1) parser. See also [`PYTHONOLDPARSER`](#envvar-PYTHONOLDPARSER) and [**PEP 617**](https://www.python.org/dev/peps/pep-0617). * `-X showrefcount` to output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds. * `-X tracemalloc` to start tracing Python memory allocations using the [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") module. By default, only the most recent frame is stored in a traceback of a trace. Use `-X tracemalloc=NFRAME` to start tracing with a traceback limit of *NFRAME* frames. See the [`tracemalloc.start()`](../library/tracemalloc#tracemalloc.start "tracemalloc.start") for more information. * `-X int_max_str_digits` configures the [integer string conversion length limitation](../library/stdtypes#int-max-str-digits). See also [`PYTHONINTMAXSTRDIGITS`](#envvar-PYTHONINTMAXSTRDIGITS). * `-X importtime` to show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is `python3 -X importtime -c 'import asyncio'`. See also [`PYTHONPROFILEIMPORTTIME`](#envvar-PYTHONPROFILEIMPORTTIME). * `-X dev`: enable [Python Development Mode](../library/devmode#devmode), introducing additional runtime checks that are too expensive to be enabled by default. * `-X utf8` enables UTF-8 mode for operating system interfaces, overriding the default locale-aware mode. `-X utf8=0` explicitly disables UTF-8 mode (even when it would otherwise activate automatically). See [`PYTHONUTF8`](#envvar-PYTHONUTF8) for more details. * `-X pycache_prefix=PATH` enables writing `.pyc` files to a parallel tree rooted at the given directory instead of to the code tree. See also [`PYTHONPYCACHEPREFIX`](#envvar-PYTHONPYCACHEPREFIX). It also allows passing arbitrary values and retrieving them through the [`sys._xoptions`](../library/sys#sys._xoptions "sys._xoptions") dictionary. Changed in version 3.2: The [`-X`](#id5) option was added. New in version 3.3: The `-X faulthandler` option. New in version 3.4: The `-X showrefcount` and `-X tracemalloc` options. New in version 3.6: The `-X showalloccount` option. New in version 3.7: The `-X importtime`, `-X dev` and `-X utf8` options. New in version 3.8: The `-X pycache_prefix` option. The `-X dev` option now logs `close()` exceptions in [`io.IOBase`](../library/io#io.IOBase "io.IOBase") destructor. Changed in version 3.9: Using `-X dev` option, check *encoding* and *errors* arguments on string encoding and decoding operations. The `-X showalloccount` option has been removed. New in version 3.9.14: The `-X int_max_str_digits` option. Deprecated since version 3.9, will be removed in version 3.10: The `-X oldparser` option. ### 1.1.4. Options you shouldn’t use `-J` Reserved for use by [Jython](http://www.jython.org/). 1.2. Environment variables --------------------------- These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I. It is customary that command-line switches override environmental variables where there is a conflict. `PYTHONHOME` Change the location of the standard Python libraries. By default, the libraries are searched in `*prefix*/lib/python*version*` and `*exec\_prefix*/lib/python*version*`, where `*prefix*` and `*exec\_prefix*` are installation-dependent directories, both defaulting to `/usr/local`. When [`PYTHONHOME`](#envvar-PYTHONHOME) is set to a single directory, its value replaces both `*prefix*` and `*exec\_prefix*`. To specify different values for these, set [`PYTHONHOME`](#envvar-PYTHONHOME) to `*prefix*:*exec\_prefix*`. `PYTHONPATH` Augment the default search path for module files. The format is the same as the shell’s `PATH`: one or more directory pathnames separated by [`os.pathsep`](../library/os#os.pathsep "os.pathsep") (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored. In addition to normal directories, individual [`PYTHONPATH`](#envvar-PYTHONPATH) entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles. The default search path is installation dependent, but generally begins with `*prefix*/lib/python*version*` (see [`PYTHONHOME`](#envvar-PYTHONHOME) above). It is *always* appended to [`PYTHONPATH`](#envvar-PYTHONPATH). An additional directory will be inserted in the search path in front of [`PYTHONPATH`](#envvar-PYTHONPATH) as described above under [Interface options](#using-on-interface-options). The search path can be manipulated from within a Python program as the variable [`sys.path`](../library/sys#sys.path "sys.path"). `PYTHONPLATLIBDIR` If this is set to a non-empty string, it overrides the [`sys.platlibdir`](../library/sys#sys.platlibdir "sys.platlibdir") value. New in version 3.9. `PYTHONSTARTUP` If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts [`sys.ps1`](../library/sys#sys.ps1 "sys.ps1") and [`sys.ps2`](../library/sys#sys.ps2 "sys.ps2") and the hook [`sys.__interactivehook__`](../library/sys#sys.__interactivehook__ "sys.__interactivehook__") in this file. Raises an [auditing event](../library/sys#auditing) `cpython.run_startup` with the filename as the argument when called on startup. `PYTHONOPTIMIZE` If this is set to a non-empty string it is equivalent to specifying the [`-O`](#cmdoption-o) option. If set to an integer, it is equivalent to specifying [`-O`](#cmdoption-o) multiple times. `PYTHONBREAKPOINT` If this is set, it names a callable using dotted-path notation. The module containing the callable will be imported and then the callable will be run by the default implementation of [`sys.breakpointhook()`](../library/sys#sys.breakpointhook "sys.breakpointhook") which itself is called by built-in [`breakpoint()`](../library/functions#breakpoint "breakpoint"). If not set, or set to the empty string, it is equivalent to the value “pdb.set\_trace”. Setting this to the string “0” causes the default implementation of [`sys.breakpointhook()`](../library/sys#sys.breakpointhook "sys.breakpointhook") to do nothing but return immediately. New in version 3.7. `PYTHONDEBUG` If this is set to a non-empty string it is equivalent to specifying the [`-d`](#cmdoption-d) option. If set to an integer, it is equivalent to specifying [`-d`](#cmdoption-d) multiple times. `PYTHONOLDPARSER` If this is set to a non-empty string, enable the traditional LL(1) parser. See also the [`-X`](#id5) `oldparser` option and [**PEP 617**](https://www.python.org/dev/peps/pep-0617). Deprecated since version 3.9, will be removed in version 3.10. `PYTHONINSPECT` If this is set to a non-empty string it is equivalent to specifying the [`-i`](#cmdoption-i) option. This variable can also be modified by Python code using [`os.environ`](../library/os#os.environ "os.environ") to force inspect mode on program termination. `PYTHONUNBUFFERED` If this is set to a non-empty string it is equivalent to specifying the [`-u`](#cmdoption-u) option. `PYTHONVERBOSE` If this is set to a non-empty string it is equivalent to specifying the [`-v`](#id4) option. If set to an integer, it is equivalent to specifying [`-v`](#id4) multiple times. `PYTHONCASEOK` If this is set, Python ignores case in [`import`](../reference/simple_stmts#import) statements. This only works on Windows and macOS. `PYTHONDONTWRITEBYTECODE` If this is set to a non-empty string, Python won’t try to write `.pyc` files on the import of source modules. This is equivalent to specifying the [`-B`](#id1) option. `PYTHONPYCACHEPREFIX` If this is set, Python will write `.pyc` files in a mirror directory tree at this path, instead of in `__pycache__` directories within the source tree. This is equivalent to specifying the [`-X`](#id5) `pycache_prefix=PATH` option. New in version 3.8. `PYTHONHASHSEED` If this variable is not set or set to `random`, a random value is used to seed the hashes of str and bytes objects. If [`PYTHONHASHSEED`](#envvar-PYTHONHASHSEED) is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization. Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values. The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash randomization. New in version 3.2.3. `PYTHONINTMAXSTRDIGITS` If this variable is set to an integer, it is used to configure the interpreter’s global [integer string conversion length limitation](../library/stdtypes#int-max-str-digits). New in version 3.9.14. `PYTHONIOENCODING` If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax `encodingname:errorhandler`. Both the `encodingname` and the `:errorhandler` parts are optional and have the same meaning as in [`str.encode()`](../library/stdtypes#str.encode "str.encode"). For stderr, the `:errorhandler` part is ignored; the handler will always be `'backslashreplace'`. Changed in version 3.4: The `encodingname` part is now optional. Changed in version 3.6: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless [`PYTHONLEGACYWINDOWSSTDIO`](#envvar-PYTHONLEGACYWINDOWSSTDIO) is also specified. Files and pipes redirected through the standard streams are not affected. `PYTHONNOUSERSITE` If this is set, Python won’t add the [`user site-packages directory`](../library/site#site.USER_SITE "site.USER_SITE") to [`sys.path`](../library/sys#sys.path "sys.path"). See also [**PEP 370**](https://www.python.org/dev/peps/pep-0370) – Per user site-packages directory `PYTHONUSERBASE` Defines the [`user base directory`](../library/site#site.USER_BASE "site.USER_BASE"), which is used to compute the path of the [`user site-packages directory`](../library/site#site.USER_SITE "site.USER_SITE") and [Distutils installation paths](../install/index#inst-alt-install-user) for `python setup.py install --user`. See also [**PEP 370**](https://www.python.org/dev/peps/pep-0370) – Per user site-packages directory `PYTHONEXECUTABLE` If this environment variable is set, `sys.argv[0]` will be set to its value instead of the value got through the C runtime. Only works on macOS. `PYTHONWARNINGS` This is equivalent to the [`-W`](#cmdoption-w) option. If set to a comma separated string, it is equivalent to specifying [`-W`](#cmdoption-w) multiple times, with filters later in the list taking precedence over those earlier in the list. The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default): ``` PYTHONWARNINGS=default # Warn once per call location PYTHONWARNINGS=error # Convert to exceptions PYTHONWARNINGS=always # Warn every time PYTHONWARNINGS=module # Warn once per calling module PYTHONWARNINGS=once # Warn once per Python process PYTHONWARNINGS=ignore # Never warn ``` See [The Warnings Filter](../library/warnings#warning-filter) and [Describing Warning Filters](../library/warnings#describing-warning-filters) for more details. `PYTHONFAULTHANDLER` If this environment variable is set to a non-empty string, [`faulthandler.enable()`](../library/faulthandler#faulthandler.enable "faulthandler.enable") is called at startup: install a handler for `SIGSEGV`, `SIGFPE`, `SIGABRT`, `SIGBUS` and `SIGILL` signals to dump the Python traceback. This is equivalent to [`-X`](#id5) `faulthandler` option. New in version 3.3. `PYTHONTRACEMALLOC` If this environment variable is set to a non-empty string, start tracing Python memory allocations using the [`tracemalloc`](../library/tracemalloc#module-tracemalloc "tracemalloc: Trace memory allocations.") module. The value of the variable is the maximum number of frames stored in a traceback of a trace. For example, `PYTHONTRACEMALLOC=1` stores only the most recent frame. See the [`tracemalloc.start()`](../library/tracemalloc#tracemalloc.start "tracemalloc.start") for more information. New in version 3.4. `PYTHONPROFILEIMPORTTIME` If this environment variable is set to a non-empty string, Python will show how long each import takes. This is exactly equivalent to setting `-X importtime` on the command line. New in version 3.7. `PYTHONASYNCIODEBUG` If this environment variable is set to a non-empty string, enable the [debug mode](../library/asyncio-dev#asyncio-debug-mode) of the [`asyncio`](../library/asyncio#module-asyncio "asyncio: Asynchronous I/O.") module. New in version 3.4. `PYTHONMALLOC` Set the Python memory allocators and/or install debug hooks. Set the family of memory allocators used by Python: * `default`: use the [default memory allocators](../c-api/memory#default-memory-allocators). * `malloc`: use the `malloc()` function of the C library for all domains ([`PYMEM_DOMAIN_RAW`](../c-api/memory#c.PYMEM_DOMAIN_RAW "PYMEM_DOMAIN_RAW"), [`PYMEM_DOMAIN_MEM`](../c-api/memory#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM"), [`PYMEM_DOMAIN_OBJ`](../c-api/memory#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ")). * `pymalloc`: use the [pymalloc allocator](../c-api/memory#pymalloc) for [`PYMEM_DOMAIN_MEM`](../c-api/memory#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") and [`PYMEM_DOMAIN_OBJ`](../c-api/memory#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") domains and use the `malloc()` function for the [`PYMEM_DOMAIN_RAW`](../c-api/memory#c.PYMEM_DOMAIN_RAW "PYMEM_DOMAIN_RAW") domain. Install debug hooks: * `debug`: install debug hooks on top of the [default memory allocators](../c-api/memory#default-memory-allocators). * `malloc_debug`: same as `malloc` but also install debug hooks. * `pymalloc_debug`: same as `pymalloc` but also install debug hooks. See the [default memory allocators](../c-api/memory#default-memory-allocators) and the [`PyMem_SetupDebugHooks()`](../c-api/memory#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") function (install debug hooks on Python memory allocators). Changed in version 3.7: Added the `"default"` allocator. New in version 3.6. `PYTHONMALLOCSTATS` If set to a non-empty string, Python will print statistics of the [pymalloc memory allocator](../c-api/memory#pymalloc) every time a new pymalloc object arena is created, and on shutdown. This variable is ignored if the [`PYTHONMALLOC`](#envvar-PYTHONMALLOC) environment variable is used to force the `malloc()` allocator of the C library, or if Python is configured without `pymalloc` support. Changed in version 3.6: This variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string. `PYTHONLEGACYWINDOWSFSENCODING` If set to a non-empty string, the default filesystem encoding and errors mode will revert to their pre-3.6 values of ‘mbcs’ and ‘replace’, respectively. Otherwise, the new defaults ‘utf-8’ and ‘surrogatepass’ are used. This may also be enabled at runtime with [`sys._enablelegacywindowsfsencoding()`](../library/sys#sys._enablelegacywindowsfsencoding "sys._enablelegacywindowsfsencoding"). [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.6: See [**PEP 529**](https://www.python.org/dev/peps/pep-0529) for more details. `PYTHONLEGACYWINDOWSSTDIO` If set to a non-empty string, does not use the new console reader and writer. This means that Unicode characters will be encoded according to the active console code page, rather than using utf-8. This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. New in version 3.6. `PYTHONCOERCECLOCALE` If set to the value `0`, causes the main Python command line application to skip coercing the legacy ASCII-based C and POSIX locales to a more capable UTF-8 based alternative. If this variable is *not* set (or is set to a value other than `0`), the `LC_ALL` locale override environment variable is also not set, and the current locale reported for the `LC_CTYPE` category is either the default `C` locale, or else the explicitly ASCII-based `POSIX` locale, then the Python CLI will attempt to configure the following locales for the `LC_CTYPE` category in the order listed before loading the interpreter runtime: * `C.UTF-8` * `C.utf8` * `UTF-8` If setting one of these locale categories succeeds, then the `LC_CTYPE` environment variable will also be set accordingly in the current process environment before the Python runtime is initialized. This ensures that in addition to being seen by both the interpreter itself and other locale-aware components running in the same process (such as the GNU `readline` library), the updated setting is also seen in subprocesses (regardless of whether or not those processes are running a Python interpreter), as well as in operations that query the environment rather than the current C locale (such as Python’s own [`locale.getdefaultlocale()`](../library/locale#locale.getdefaultlocale "locale.getdefaultlocale")). Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the `surrogateescape` [error handler](../library/codecs#error-handlers) for [`sys.stdin`](../library/sys#sys.stdin "sys.stdin") and [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") ([`sys.stderr`](../library/sys#sys.stderr "sys.stderr") continues to use `backslashreplace` as it does in any other locale). This stream handling behavior can be overridden using [`PYTHONIOENCODING`](#envvar-PYTHONIOENCODING) as usual. For debugging purposes, setting `PYTHONCOERCECLOCALE=warn` will cause Python to emit warning messages on `stderr` if either the locale coercion activates, or else if a locale that *would* have triggered coercion is still active when the Python runtime is initialized. Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale, [`PYTHONUTF8`](#envvar-PYTHONUTF8) will still activate by default in legacy ASCII-based locales. Both features must be disabled in order to force the interpreter to use `ASCII` instead of `UTF-8` for system interfaces. [Availability](https://docs.python.org/3.9/library/intro.html#availability): \*nix. New in version 3.7: See [**PEP 538**](https://www.python.org/dev/peps/pep-0538) for more details. `PYTHONDEVMODE` If this environment variable is set to a non-empty string, enable [Python Development Mode](../library/devmode#devmode), introducing additional runtime checks that are too expensive to be enabled by default. New in version 3.7. `PYTHONUTF8` If set to `1`, enables the interpreter’s UTF-8 mode, where `UTF-8` is used as the text encoding for system interfaces, regardless of the current locale setting. This means that: * [`sys.getfilesystemencoding()`](../library/sys#sys.getfilesystemencoding "sys.getfilesystemencoding") returns `'UTF-8'` (the locale encoding is ignored). * [`locale.getpreferredencoding()`](../library/locale#locale.getpreferredencoding "locale.getpreferredencoding") returns `'UTF-8'` (the locale encoding is ignored, and the function’s `do_setlocale` parameter has no effect). * [`sys.stdin`](../library/sys#sys.stdin "sys.stdin"), [`sys.stdout`](../library/sys#sys.stdout "sys.stdout"), and [`sys.stderr`](../library/sys#sys.stderr "sys.stderr") all use UTF-8 as their text encoding, with the `surrogateescape` [error handler](../library/codecs#error-handlers) being enabled for [`sys.stdin`](../library/sys#sys.stdin "sys.stdin") and [`sys.stdout`](../library/sys#sys.stdout "sys.stdout") ([`sys.stderr`](../library/sys#sys.stderr "sys.stderr") continues to use `backslashreplace` as it does in the default locale-aware mode) As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours: * Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding. * [`os.fsdecode()`](../library/os#os.fsdecode "os.fsdecode") and [`os.fsencode()`](../library/os#os.fsencode "os.fsencode") use the UTF-8 encoding. * [`open()`](../library/functions#open "open"), [`io.open()`](../library/io#io.open "io.open"), and [`codecs.open()`](../library/codecs#codecs.open "codecs.open") use the UTF-8 encoding by default. However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data. Note that the standard stream settings in UTF-8 mode can be overridden by [`PYTHONIOENCODING`](#envvar-PYTHONIOENCODING) (just as they can be in the default locale-aware mode). If set to `0`, the interpreter runs in its default locale-aware mode. Setting any other non-empty string causes an error during interpreter initialisation. If this environment variable is not set at all, then the interpreter defaults to using the current locale settings, *unless* the current locale is identified as a legacy ASCII-based locale (as described for [`PYTHONCOERCECLOCALE`](#envvar-PYTHONCOERCECLOCALE)), and locale coercion is either disabled or fails. In such legacy locales, the interpreter will default to enabling UTF-8 mode unless explicitly instructed not to do so. Also available as the [`-X`](#id5) `utf8` option. New in version 3.7: See [**PEP 540**](https://www.python.org/dev/peps/pep-0540) for more details. ### 1.2.1. Debug-mode variables Setting these variables only has an effect in a debug build of Python. `PYTHONTHREADDEBUG` If set, Python will print threading debug info. Need Python configured with the `--with-pydebug` build option. `PYTHONDUMPREFS` If set, Python will dump objects and reference counts still alive after shutting down the interpreter. Need Python configured with the `--with-trace-refs` build option.
programming_docs
python Editors and IDEs Editors and IDEs ================= There are a number of IDEs that support Python programming language. Many editors and IDEs provide syntax highlighting, debugging tools, and [**PEP 8**](https://www.python.org/dev/peps/pep-0008) checks. Please go to [Python Editors](https://wiki.python.org/moin/PythonEditors) and [Integrated Development Environments](https://wiki.python.org/moin/IntegratedDevelopmentEnvironments) for a comprehensive list. python Using Python on a Mac Using Python on a Mac ====================== Author Bob Savage <[[email protected]](mailto:bobsavage%40mac.com)> Python on a Mac running macOS is in principle very similar to Python on any other Unix platform, but there are a number of additional features such as the IDE and the Package Manager that are worth pointing out. 4.1. Getting and Installing MacPython -------------------------------------- macOS since version 10.8 comes with Python 2.7 pre-installed by Apple. If you wish, you are invited to install the most recent version of Python 3 from the Python website (<https://www.python.org>). A current “universal binary” build of Python, which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there. What you get after installing is a number of things: * A `Python 3.9` folder in your `Applications` folder. In here you find IDLE, the development environment that is a standard part of official Python distributions; and PythonLauncher, which handles double-clicking Python scripts from the Finder. * A framework `/Library/Frameworks/Python.framework`, which includes the Python executable and libraries. The installer adds this location to your shell path. To uninstall MacPython, you can simply remove these three things. A symlink to the Python executable is placed in /usr/local/bin/. The Apple-provided build of Python is installed in `/System/Library/Frameworks/Python.framework` and `/usr/bin/python`, respectively. You should never modify or delete these, as they are Apple-controlled and are used by Apple- or third-party software. Remember that if you choose to install a newer Python version from python.org, you will have two different but functional Python installations on your computer, so it will be important that your paths and usages are consistent with what you want to do. IDLE includes a help menu that allows you to access Python documentation. If you are completely new to Python you should start reading the tutorial introduction in that document. If you are familiar with Python on other Unix platforms you should read the section on running Python scripts from the Unix shell. ### 4.1.1. How to run a Python script Your best way to get started with Python on macOS is through the IDLE integrated development environment, see section [The IDE](#ide) and use the Help menu when the IDE is running. If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script. macOS comes with a number of standard Unix command line editors, **vim** and **emacs** among them. If you want a more Mac-like editor, **BBEdit** or **TextWrangler** from Bare Bones Software (see <http://www.barebones.com/products/bbedit/index.html>) are good choices, as is **TextMate** (see <https://macromates.com/>). Other editors include **Gvim** (<http://macvim-dev.github.io/macvim/>) and **Aquamacs** (<http://aquamacs.org/>). To run your script from the Terminal window you must make sure that `/usr/local/bin` is in your shell search path. To run your script from the Finder you have two options: * Drag it to **PythonLauncher** * Select **PythonLauncher** as the default application to open your script (or any .py script) through the finder Info window and double-click it. **PythonLauncher** has various preferences to control how your script is launched. Option-dragging allows you to change these for one invocation, or use its Preferences menu to change things globally. ### 4.1.2. Running scripts with a GUI With older versions of Python, there is one macOS quirk that you need to be aware of: programs that talk to the Aqua window manager (in other words, anything that has a GUI) need to be run in a special way. Use **pythonw** instead of **python** to start such scripts. With Python 3.9, you can use either **python** or **pythonw**. ### 4.1.3. Configuration Python on macOS honors all standard Unix environment variables such as [`PYTHONPATH`](cmdline#envvar-PYTHONPATH), but setting these variables for programs started from the Finder is non-standard as the Finder does not read your `.profile` or `.cshrc` at startup. You need to create a file `~/.MacOSX/environment.plist`. See Apple’s Technical Document QA1067 for details. For more information on installation Python packages in MacPython, see section [Installing Additional Python Packages](#mac-package-manager). 4.2. The IDE ------------- MacPython ships with the standard IDLE development environment. A good introduction to using IDLE can be found at <http://www.hashcollision.org/hkn/python/idle_intro/index.html>. 4.3. Installing Additional Python Packages ------------------------------------------- There are several methods to install additional Python packages: * Packages can be installed via the standard Python distutils mode (`python setup.py install`). * Many packages can also be installed via the **setuptools** extension or **pip** wrapper, see <https://pip.pypa.io/>. 4.4. GUI Programming on the Mac -------------------------------- There are several options for building GUI applications on the Mac with Python. *PyObjC* is a Python binding to Apple’s Objective-C/Cocoa framework, which is the foundation of most modern Mac development. Information on PyObjC is available from <https://pypi.org/project/pyobjc/>. The standard Python GUI toolkit is [`tkinter`](../library/tkinter#module-tkinter "tkinter: Interface to Tcl/Tk for graphical user interfaces"), based on the cross-platform Tk toolkit (<https://www.tcl.tk>). An Aqua-native version of Tk is bundled with OS X by Apple, and the latest version can be downloaded and installed from <https://www.activestate.com>; it can also be built from source. *wxPython* is another popular cross-platform GUI toolkit that runs natively on macOS. Packages and documentation are available from <https://www.wxpython.org>. *PyQt* is another popular cross-platform GUI toolkit that runs natively on macOS. More information can be found at <https://riverbankcomputing.com/software/pyqt/intro>. 4.5. Distributing Python Applications on the Mac ------------------------------------------------- The standard tool for deploying standalone Python applications on the Mac is **py2app**. More information on installing and using py2app can be found at <https://pypi.org/project/py2app/>. 4.6. Other Resources --------------------- The MacPython mailing list is an excellent support resource for Python users and developers on the Mac: <https://www.python.org/community/sigs/current/pythonmac-sig/> Another useful resource is the MacPython wiki: <https://wiki.python.org/moin/MacPython> python Using Python on Windows Using Python on Windows ======================== This document aims to give an overview of Windows-specific behaviour you should know about when using Python on Microsoft Windows. Unlike most Unix systems and services, Windows does not include a system supported installation of Python. To make Python available, the CPython team has compiled Windows installers (MSI packages) with every [release](https://www.python.org/download/releases/) for many years. These installers are primarily intended to add a per-user installation of Python, with the core interpreter and library being used by a single user. The installer is also able to install for all users of a single machine, and a separate ZIP file is available for application-local distributions. As specified in [**PEP 11**](https://www.python.org/dev/peps/pep-0011), a Python release only supports a Windows platform while Microsoft considers the platform under extended support. This means that Python 3.9 supports Windows 8.1 and newer. If you require Windows 7 support, please install Python 3.8. There are a number of different installers available for Windows, each with certain benefits and downsides. [The full installer](#windows-full) contains all components and is the best option for developers using Python for any kind of project. [The Microsoft Store package](#windows-store) is a simple installation of Python that is suitable for running scripts and packages, and using IDLE or other development environments. It requires Windows 10, but can be safely installed without corrupting other programs. It also provides many convenient commands for launching Python and its tools. [The nuget.org packages](#windows-nuget) are lightweight installations intended for continuous integration systems. It can be used to build Python packages or run scripts, but is not updateable and has no user interface tools. [The embeddable package](#windows-embeddable) is a minimal package of Python suitable for embedding into a larger application. 3.1. The full installer ------------------------ ### 3.1.1. Installation steps Four Python 3.9 installers are available for download - two each for the 32-bit and 64-bit versions of the interpreter. The *web installer* is a small initial download, and it will automatically download the required components as necessary. The *offline installer* includes the components necessary for a default installation and only requires an internet connection for optional features. See [Installing Without Downloading](#install-layout-option) for other ways to avoid downloading during installation. After starting the installer, one of two options may be selected: If you select “Install Now”: * You will *not* need to be an administrator (unless a system update for the C Runtime Library is required or you install the [Python Launcher for Windows](#launcher) for all users) * Python will be installed into your user directory * The [Python Launcher for Windows](#launcher) will be installed according to the option at the bottom of the first page * The standard library, test suite, launcher and pip will be installed * If selected, the install directory will be added to your `PATH` * Shortcuts will only be visible for the current user Selecting “Customize installation” will allow you to select the features to install, the installation location and other options or post-install actions. To install debugging symbols or binaries, you will need to use this option. To perform an all-users installation, you should select “Customize installation”. In this case: * You may be required to provide administrative credentials or approval * Python will be installed into the Program Files directory * The [Python Launcher for Windows](#launcher) will be installed into the Windows directory * Optional features may be selected during installation * The standard library can be pre-compiled to bytecode * If selected, the install directory will be added to the system `PATH` * Shortcuts are available for all users ### 3.1.2. Removing the MAX\_PATH Limitation Windows historically has limited path lengths to 260 characters. This meant that paths longer than this would not resolve and errors would result. In the latest versions of Windows, this limitation can be expanded to approximately 32,000 characters. Your administrator will need to activate the “Enable Win32 long paths” group policy, or set `LongPathsEnabled` to `1` in the registry key `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. This allows the [`open()`](../library/functions#open "open") function, the [`os`](../library/os#module-os "os: Miscellaneous operating system interfaces.") module and most other path functionality to accept and return paths longer than 260 characters. After changing the above option, no further configuration is required. Changed in version 3.6: Support for long paths was enabled in Python. ### 3.1.3. Installing Without UI All of the options available in the installer UI can also be specified from the command line, allowing scripted installers to replicate an installation on many machines without user interaction. These options may also be set without suppressing the UI in order to change some of the defaults. To completely hide the installer UI and install Python silently, pass the `/quiet` option. To skip past the user interaction but still display progress and errors, pass the `/passive` option. The `/uninstall` option may be passed to immediately begin removing Python - no confirmation prompt will be displayed. All other options are passed as `name=value`, where the value is usually `0` to disable a feature, `1` to enable a feature, or a path. The full list of available options is shown below. | Name | Description | Default | | --- | --- | --- | | InstallAllUsers | Perform a system-wide installation. | 0 | | TargetDir | The installation directory | Selected based on InstallAllUsers | | DefaultAllUsersTargetDir | The default installation directory for all-user installs | `%ProgramFiles%\Python X.Y` or `%ProgramFiles(x86)%\Python X.Y` | | DefaultJustForMeTargetDir | The default install directory for just-for-me installs | `%LocalAppData%\Programs\PythonXY` or `%LocalAppData%\Programs\PythonXY-32` or `%LocalAppData%\Programs\PythonXY-64` | | DefaultCustomTargetDir | The default custom install directory displayed in the UI | (empty) | | AssociateFiles | Create file associations if the launcher is also installed. | 1 | | CompileAll | Compile all `.py` files to `.pyc`. | 0 | | PrependPath | Add install and Scripts directories to `PATH` and `.PY` to `PATHEXT` | 0 | | Shortcuts | Create shortcuts for the interpreter, documentation and IDLE if installed. | 1 | | Include\_doc | Install Python manual | 1 | | Include\_debug | Install debug binaries | 0 | | Include\_dev | Install developer headers and libraries | 1 | | Include\_exe | Install `python.exe` and related files | 1 | | Include\_launcher | Install [Python Launcher for Windows](#launcher). | 1 | | InstallLauncherAllUsers | Installs [Python Launcher for Windows](#launcher) for all users. | 1 | | Include\_lib | Install standard library and extension modules | 1 | | Include\_pip | Install bundled pip and setuptools | 1 | | Include\_symbols | Install debugging symbols (`*`.pdb) | 0 | | Include\_tcltk | Install Tcl/Tk support and IDLE | 1 | | Include\_test | Install standard library test suite | 1 | | Include\_tools | Install utility scripts | 1 | | LauncherOnly | Only installs the launcher. This will override most other options. | 0 | | SimpleInstall | Disable most install UI | 0 | | SimpleInstallDescription | A custom message to display when the simplified install UI is used. | (empty) | For example, to silently install a default, system-wide Python installation, you could use the following command (from an elevated command prompt): ``` python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 ``` To allow users to easily install a personal copy of Python without the test suite, you could provide a shortcut with the following command. This will display a simplified initial page and disallow customization: ``` python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0 SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite." ``` (Note that omitting the launcher also omits file associations, and is only recommended for per-user installs when there is also a system-wide installation that included the launcher.) The options listed above can also be provided in a file named `unattend.xml` alongside the executable. This file specifies a list of options and values. When a value is provided as an attribute, it will be converted to a number if possible. Values provided as element text are always left as strings. This example file sets the same options as the previous example: ``` <Options> <Option Name="InstallAllUsers" Value="no" /> <Option Name="Include_launcher" Value="0" /> <Option Name="Include_test" Value="no" /> <Option Name="SimpleInstall" Value="yes" /> <Option Name="SimpleInstallDescription">Just for me, no test suite</Option> </Options> ``` ### 3.1.4. Installing Without Downloading As some features of Python are not included in the initial installer download, selecting those features may require an internet connection. To avoid this need, all possible components may be downloaded on-demand to create a complete *layout* that will no longer require an internet connection regardless of the selected features. Note that this download may be bigger than required, but where a large number of installations are going to be performed it is very useful to have a locally cached copy. Execute the following command from Command Prompt to download all possible required files. Remember to substitute `python-3.9.0.exe` for the actual name of your installer, and to create layouts in their own directories to avoid collisions between files with the same name. ``` python-3.9.0.exe /layout [optional target directory] ``` You may also specify the `/quiet` option to hide the progress display. ### 3.1.5. Modifying an install Once Python has been installed, you can add or remove features through the Programs and Features tool that is part of Windows. Select the Python entry and choose “Uninstall/Change” to open the installer in maintenance mode. “Modify” allows you to add or remove features by modifying the checkboxes - unchanged checkboxes will not install or remove anything. Some options cannot be changed in this mode, such as the install directory; to modify these, you will need to remove and then reinstall Python completely. “Repair” will verify all the files that should be installed using the current settings and replace any that have been removed or modified. “Uninstall” will remove Python entirely, with the exception of the [Python Launcher for Windows](#launcher), which has its own entry in Programs and Features. 3.2. The Microsoft Store package --------------------------------- New in version 3.7.2. The Microsoft Store package is an easily installable Python interpreter that is intended mainly for interactive use, for example, by students. To install the package, ensure you have the latest Windows 10 updates and search the Microsoft Store app for “Python 3.9”. Ensure that the app you select is published by the Python Software Foundation, and install it. Warning Python will always be available for free on the Microsoft Store. If you are asked to pay for it, you have not selected the correct package. After installation, Python may be launched by finding it in Start. Alternatively, it will be available from any Command Prompt or PowerShell session by typing `python`. Further, pip and IDLE may be used by typing `pip` or `idle`. IDLE can also be found in Start. All three commands are also available with version number suffixes, for example, as `python3.exe` and `python3.x.exe` as well as `python.exe` (where `3.x` is the specific version you want to launch, such as 3.9). Open “Manage App Execution Aliases” through Start to select which version of Python is associated with each command. It is recommended to make sure that `pip` and `idle` are consistent with whichever version of `python` is selected. Virtual environments can be created with `python -m venv` and activated and used as normal. If you have installed another version of Python and added it to your `PATH` variable, it will be available as `python.exe` rather than the one from the Microsoft Store. To access the new installation, use `python3.exe` or `python3.x.exe`. The `py.exe` launcher will detect this Python installation, but will prefer installations from the traditional installer. To remove Python, open Settings and use Apps and Features, or else find Python in Start and right-click to select Uninstall. Uninstalling will remove all packages you installed directly into this Python installation, but will not remove any virtual environments ### 3.2.1. Known Issues Because of restrictions on Microsoft Store apps, Python scripts may not have full write access to shared locations such as `TEMP` and the registry. Instead, it will write to a private copy. If your scripts must modify the shared locations, you will need to install the full installer. For more detail on the technical basis for these limitations, please consult Microsoft’s documentation on packaged full-trust apps, currently available at [docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes](https://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes) 3.3. The nuget.org packages ---------------------------- New in version 3.5.2. The nuget.org package is a reduced size Python environment intended for use on continuous integration and build systems that do not have a system-wide install of Python. While nuget is “the package manager for .NET”, it also works perfectly fine for packages containing build-time tools. Visit [nuget.org](https://www.nuget.org/) for the most up-to-date information on using nuget. What follows is a summary that is sufficient for Python developers. The `nuget.exe` command line tool may be downloaded directly from `https://aka.ms/nugetclidl`, for example, using curl or PowerShell. With the tool, the latest version of Python for 64-bit or 32-bit machines is installed using: ``` nuget.exe install python -ExcludeVersion -OutputDirectory . nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory . ``` To select a particular version, add a `-Version 3.x.y`. The output directory may be changed from `.`, and the package will be installed into a subdirectory. By default, the subdirectory is named the same as the package, and without the `-ExcludeVersion` option this name will include the specific version installed. Inside the subdirectory is a `tools` directory that contains the Python installation: ``` # Without -ExcludeVersion > .\python.3.5.2\tools\python.exe -V Python 3.5.2 # With -ExcludeVersion > .\python\tools\python.exe -V Python 3.5.2 ``` In general, nuget packages are not upgradeable, and newer versions should be installed side-by-side and referenced using the full path. Alternatively, delete the package directory manually and install it again. Many CI systems will do this automatically if they do not preserve files between builds. Alongside the `tools` directory is a `build\native` directory. This contains a MSBuild properties file `python.props` that can be used in a C++ project to reference the Python install. Including the settings will automatically use the headers and import libraries in your build. The package information pages on nuget.org are [www.nuget.org/packages/python](https://www.nuget.org/packages/python) for the 64-bit version and [www.nuget.org/packages/pythonx86](https://www.nuget.org/packages/pythonx86) for the 32-bit version. 3.4. The embeddable package ---------------------------- New in version 3.5. The embedded distribution is a ZIP file containing a minimal Python environment. It is intended for acting as part of another application, rather than being directly accessed by end-users. When extracted, the embedded distribution is (almost) fully isolated from the user’s system, including environment variables, system registry settings, and installed packages. The standard library is included as pre-compiled and optimized `.pyc` files in a ZIP, and `python3.dll`, `python37.dll`, `python.exe` and `pythonw.exe` are all provided. Tcl/tk (including all dependants, such as Idle), pip and the Python documentation are not included. Note The embedded distribution does not include the [Microsoft C Runtime](https://docs.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist#visual-studio-2015-2017-2019-and-2022) and it is the responsibility of the application installer to provide this. The runtime may have already been installed on a user’s system previously or automatically via Windows Update, and can be detected by finding `ucrtbase.dll` in the system directory. Third-party packages should be installed by the application installer alongside the embedded distribution. Using pip to manage dependencies as for a regular Python installation is not supported with this distribution, though with some care it may be possible to include and use pip for automatic updates. In general, third-party packages should be treated as part of the application (“vendoring”) so that the developer can ensure compatibility with newer versions before providing updates to users. The two recommended use cases for this distribution are described below. ### 3.4.1. Python Application An application written in Python does not necessarily require users to be aware of that fact. The embedded distribution may be used in this case to include a private version of Python in an install package. Depending on how transparent it should be (or conversely, how professional it should appear), there are two options. Using a specialized executable as a launcher requires some coding, but provides the most transparent experience for users. With a customized launcher, there are no obvious indications that the program is running on Python: icons can be customized, company and version information can be specified, and file associations behave properly. In most cases, a custom launcher should simply be able to call `Py_Main` with a hard-coded command line. The simpler approach is to provide a batch file or generated shortcut that directly calls the `python.exe` or `pythonw.exe` with the required command-line arguments. In this case, the application will appear to be Python and not its actual name, and users may have trouble distinguishing it from other running Python processes or file associations. With the latter approach, packages should be installed as directories alongside the Python executable to ensure they are available on the path. With the specialized launcher, packages can be located in other locations as there is an opportunity to specify the search path before launching the application. ### 3.4.2. Embedding Python Applications written in native code often require some form of scripting language, and the embedded Python distribution can be used for this purpose. In general, the majority of the application is in native code, and some part will either invoke `python.exe` or directly use `python3.dll`. For either case, extracting the embedded distribution to a subdirectory of the application installation is sufficient to provide a loadable Python interpreter. As with the application use, packages can be installed to any location as there is an opportunity to specify search paths before initializing the interpreter. Otherwise, there is no fundamental differences between using the embedded distribution and a regular installation. 3.5. Alternative bundles ------------------------- Besides the standard CPython distribution, there are modified packages including additional functionality. The following is a list of popular versions and their key features: [ActivePython](https://www.activestate.com/activepython/) Installer with multi-platform compatibility, documentation, PyWin32 [Anaconda](https://www.anaconda.com/download/) Popular scientific modules (such as numpy, scipy and pandas) and the `conda` package manager. [Canopy](https://www.enthought.com/product/canopy/) A “comprehensive Python analysis environment” with editors and other development tools. [WinPython](https://winpython.github.io/) Windows-specific distribution with prebuilt scientific packages and tools for building packages. Note that these packages may not include the latest versions of Python or other libraries, and are not maintained or supported by the core Python team. 3.6. Configuring Python ------------------------ To run Python conveniently from a command prompt, you might consider changing some default environment variables in Windows. While the installer provides an option to configure the PATH and PATHEXT variables for you, this is only reliable for a single, system-wide installation. If you regularly use multiple versions of Python, consider using the [Python Launcher for Windows](#launcher). ### 3.6.1. Excursus: Setting environment variables Windows allows environment variables to be configured permanently at both the User level and the System level, or temporarily in a command prompt. To temporarily set environment variables, open Command Prompt and use the **set** command: ``` C:\>set PATH=C:\Program Files\Python 3.9;%PATH% C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib C:\>python ``` These changes will apply to any further commands executed in that console, and will be inherited by any applications started from the console. Including the variable name within percent signs will expand to the existing value, allowing you to add your new value at either the start or the end. Modifying `PATH` by adding the directory containing **python.exe** to the start is a common way to ensure the correct version of Python is launched. To permanently modify the default environment variables, click Start and search for ‘edit environment variables’, or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights). Note Windows will concatenate User variables *after* System variables, which may cause unexpected results when modifying `PATH`. The [`PYTHONPATH`](cmdline#envvar-PYTHONPATH) variable is used by all versions of Python, so you should not permanently configure it unless the listed paths only include code that is compatible with all of your installed Python versions. See also <https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables> Overview of environment variables on Windows <https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/set_1> The `set` command, for temporarily modifying environment variables <https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/setx> The `setx` command, for permanently modifying environment variables ### 3.6.2. Finding the Python executable Changed in version 3.5. Besides using the automatically created start menu entry for the Python interpreter, you might want to start Python in the command prompt. The installer has an option to set that up for you. On the first page of the installer, an option labelled “Add Python to PATH” may be selected to have the installer add the install location into the `PATH`. The location of the `Scripts\` folder is also added. This allows you to type **python** to run the interpreter, and **pip** for the package installer. Thus, you can also execute your scripts with command line options, see [Command line](cmdline#using-on-cmdline) documentation. If you don’t enable this option at install time, you can always re-run the installer, select Modify, and enable it. Alternatively, you can manually modify the `PATH` using the directions in [Excursus: Setting environment variables](#setting-envvars). You need to set your `PATH` environment variable to include the directory of your Python installation, delimited by a semicolon from other entries. An example variable could look like this (assuming the first two entries already existed): ``` C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.9 ``` 3.7. UTF-8 mode ---------------- New in version 3.7. Windows still uses legacy encodings for the system encoding (the ANSI Code Page). Python uses it for the default encoding of text files (e.g. [`locale.getpreferredencoding()`](../library/locale#locale.getpreferredencoding "locale.getpreferredencoding")). This may cause issues because UTF-8 is widely used on the internet and most Unix systems, including WSL (Windows Subsystem for Linux). You can use UTF-8 mode to change the default text encoding to UTF-8. You can enable UTF-8 mode via the `-X utf8` command line option, or the `PYTHONUTF8=1` environment variable. See [`PYTHONUTF8`](cmdline#envvar-PYTHONUTF8) for enabling UTF-8 mode, and [Excursus: Setting environment variables](#setting-envvars) for how to modify environment variables. When UTF-8 mode is enabled: * [`locale.getpreferredencoding()`](../library/locale#locale.getpreferredencoding "locale.getpreferredencoding") returns `'UTF-8'` instead of the system encoding. This function is used for the default text encoding in many places, including [`open()`](../library/functions#open "open"), `Popen`, `Path.read_text()`, etc. * [`sys.stdin`](../library/sys#sys.stdin "sys.stdin"), [`sys.stdout`](../library/sys#sys.stdout "sys.stdout"), and [`sys.stderr`](../library/sys#sys.stderr "sys.stderr") all use UTF-8 as their text encoding. * You can still use the system encoding via the “mbcs” codec. Note that adding `PYTHONUTF8=1` to the default environment variables will affect all Python 3.7+ applications on your system. If you have any Python 3.7+ applications which rely on the legacy system encoding, it is recommended to set the environment variable temporarily or use the `-X utf8` command line option. Note Even when UTF-8 mode is disabled, Python uses UTF-8 by default on Windows for: * Console I/O including standard I/O (see [**PEP 528**](https://www.python.org/dev/peps/pep-0528) for details). * The filesystem encoding (see [**PEP 529**](https://www.python.org/dev/peps/pep-0529) for details). 3.8. Python Launcher for Windows --------------------------------- New in version 3.3. The Python launcher for Windows is a utility which aids in locating and executing of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version. Unlike the `PATH` variable, the launcher will correctly select the most appropriate version of Python. It will prefer per-user installations over system-wide ones, and orders by language version rather than using the most recently installed version. The launcher was originally specified in [**PEP 397**](https://www.python.org/dev/peps/pep-0397). ### 3.8.1. Getting started #### 3.8.1.1. From the command-line Changed in version 3.6. System-wide installations of Python 3.3 and later will put the launcher on your `PATH`. The launcher is compatible with all available versions of Python, so it does not matter which version is installed. To check that the launcher is available, execute the following command in Command Prompt: ``` py ``` You should find that the latest version of Python you have installed is started - it can be exited as normal, and any additional command-line arguments specified will be sent directly to Python. If you have multiple versions of Python installed (e.g., 3.7 and 3.9) you will have noticed that Python 3.9 was started - to launch Python 3.7, try the command: ``` py -3.7 ``` If you want the latest version of Python 2 you have installed, try the command: ``` py -2 ``` You should find the latest version of Python 3.x starts. If you see the following error, you do not have the launcher installed: ``` 'py' is not recognized as an internal or external command, operable program or batch file. ``` Per-user installations of Python do not add the launcher to `PATH` unless the option was selected on installation. The command: ``` py --list ``` displays the currently installed version(s) of Python. #### 3.8.1.2. Virtual environments New in version 3.5. If the launcher is run with no explicit Python version specification, and a virtual environment (created with the standard library [`venv`](../library/venv#module-venv "venv: Creation of virtual environments.") module or the external `virtualenv` tool) active, the launcher will run the virtual environment’s interpreter rather than the global one. To run the global interpreter, either deactivate the virtual environment, or explicitly specify the global Python version. #### 3.8.1.3. From a script Let’s create a test Python script - create a file called `hello.py` with the following contents ``` #! python import sys sys.stdout.write("hello from Python %s\n" % (sys.version,)) ``` From the directory in which hello.py lives, execute the command: ``` py hello.py ``` You should notice the version number of your latest Python 2.x installation is printed. Now try changing the first line to be: ``` #! python3 ``` Re-executing the command should now print the latest Python 3.x information. As with the above command-line examples, you can specify a more explicit version qualifier. Assuming you have Python 3.7 installed, try changing the first line to `#! python3.7` and you should find the 3.9 version information printed. Note that unlike interactive use, a bare “python” will use the latest version of Python 2.x that you have installed. This is for backward compatibility and for compatibility with Unix, where the command `python` typically refers to Python 2. #### 3.8.1.4. From file associations The launcher should have been associated with Python files (i.e. `.py`, `.pyw`, `.pyc` files) when it was installed. This means that when you double-click on one of these files from Windows explorer the launcher will be used, and therefore you can use the same facilities described above to have the script specify the version which should be used. The key benefit of this is that a single launcher can support multiple Python versions at the same time depending on the contents of the first line. ### 3.8.2. Shebang Lines If the first line of a script file starts with `#!`, it is known as a “shebang” line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed. This launcher allows the same facilities to be used with Python scripts on Windows and the examples above demonstrate their use. To allow shebang lines in Python scripts to be portable between Unix and Windows, this launcher supports a number of ‘virtual’ commands to specify which interpreter to use. The supported virtual commands are: * `/usr/bin/env python` * `/usr/bin/python` * `/usr/local/bin/python` * `python` For example, if the first line of your script starts with ``` #! /usr/bin/python ``` The default Python will be located and used. As many Python scripts written to work on Unix will already have this line, you should find these scripts can be used by the launcher without modification. If you are writing a new script on Windows which you hope will be useful on Unix, you should use one of the shebang lines starting with `/usr`. Any of the above virtual commands can be suffixed with an explicit version (either just the major version, or the major and minor version). Furthermore the 32-bit version can be requested by adding “-32” after the minor version. I.e. `/usr/bin/python3.7-32` will request usage of the 32-bit python 3.7. New in version 3.7: Beginning with python launcher 3.7 it is possible to request 64-bit version by the “-64” suffix. Furthermore it is possible to specify a major and architecture without minor (i.e. `/usr/bin/python3-64`). The `/usr/bin/env` form of shebang line has one further special property. Before looking for installed Python interpreters, this form will search the executable `PATH` for a Python executable. This corresponds to the behaviour of the Unix `env` program, which performs a `PATH` search. ### 3.8.3. Arguments in shebang lines The shebang lines can also specify additional options to be passed to the Python interpreter. For example, if you have a shebang line: ``` #! /usr/bin/python -v ``` Then Python will be started with the `-v` option ### 3.8.4. Customization #### 3.8.4.1. Customization via INI files Two .ini files will be searched by the launcher - `py.ini` in the current user’s “application data” directory (i.e. the directory returned by calling the Windows function `SHGetFolderPath` with `CSIDL_LOCAL_APPDATA`) and `py.ini` in the same directory as the launcher. The same .ini files are used for both the ‘console’ version of the launcher (i.e. py.exe) and for the ‘windows’ version (i.e. pyw.exe). Customization specified in the “application directory” will have precedence over the one next to the executable, so a user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini file. #### 3.8.4.2. Customizing default Python versions In some cases, a version qualifier can be included in a command to dictate which version of Python will be used by the command. A version qualifier starts with a major version number and can optionally be followed by a period (‘.’) and a minor version specifier. Furthermore it is possible to specify if a 32 or 64 bit implementation shall be requested by adding “-32” or “-64”. For example, a shebang line of `#!python` has no version qualifier, while `#!python3` has a version qualifier which specifies only a major version. If no version qualifiers are found in a command, the environment variable `PY_PYTHON` can be set to specify the default version qualifier. If it is not set, the default is “3”. The variable can specify any value that may be passed on the command line, such as “3”, “3.7”, “3.7-32” or “3.7-64”. (Note that the “-64” option is only available with the launcher included with Python 3.7 or newer.) If no minor version qualifiers are found, the environment variable `PY_PYTHON{major}` (where `{major}` is the current major version qualifier as determined above) can be set to specify the full version. If no such option is found, the launcher will enumerate the installed Python versions and use the latest minor release found for the major version, which is likely, although not guaranteed, to be the most recently installed version in that family. On 64-bit Windows with both 32-bit and 64-bit implementations of the same (major.minor) Python version installed, the 64-bit version will always be preferred. This will be true for both 32-bit and 64-bit implementations of the launcher - a 32-bit launcher will prefer to execute a 64-bit Python installation of the specified version if available. This is so the behavior of the launcher can be predicted knowing only what versions are installed on the PC and without regard to the order in which they were installed (i.e., without knowing whether a 32 or 64-bit version of Python and corresponding launcher was installed last). As noted above, an optional “-32” or “-64” suffix can be used on a version specifier to change this behaviour. Examples: * If no relevant options are set, the commands `python` and `python2` will use the latest Python 2.x version installed and the command `python3` will use the latest Python 3.x installed. * The command `python3.7` will not consult any options at all as the versions are fully specified. * If `PY_PYTHON=3`, the commands `python` and `python3` will both use the latest installed Python 3 version. * If `PY_PYTHON=3.7-32`, the command `python` will use the 32-bit implementation of 3.7 whereas the command `python3` will use the latest installed Python (PY\_PYTHON was not considered at all as a major version was specified.) * If `PY_PYTHON=3` and `PY_PYTHON3=3.7`, the commands `python` and `python3` will both use specifically 3.7 In addition to environment variables, the same settings can be configured in the .INI file used by the launcher. The section in the INI file is called `[defaults]` and the key name will be the same as the environment variables without the leading `PY_` prefix (and note that the key names in the INI file are case insensitive.) The contents of an environment variable will override things specified in the INI file. For example: * Setting `PY_PYTHON=3.7` is equivalent to the INI file containing: ``` [defaults] python=3.7 ``` * Setting `PY_PYTHON=3` and `PY_PYTHON3=3.7` is equivalent to the INI file containing: ``` [defaults] python=3 python3=3.7 ``` ### 3.8.5. Diagnostics If an environment variable `PYLAUNCH_DEBUG` is set (to any value), the launcher will print diagnostic information to stderr (i.e. to the console). While this information manages to be simultaneously verbose *and* terse, it should allow you to see what versions of Python were located, why a particular version was chosen and the exact command-line used to execute the target Python. 3.9. Finding modules --------------------- Python usually stores its library (and thereby your site-packages folder) in the installation directory. So, if you had installed Python to `C:\Python\`, the default library would reside in `C:\Python\Lib\` and third-party modules should be stored in `C:\Python\Lib\site-packages\`. To completely override [`sys.path`](../library/sys#sys.path "sys.path"), create a `._pth` file with the same name as the DLL (`python37._pth`) or the executable (`python._pth`) and specify one line for each path to add to [`sys.path`](../library/sys#sys.path "sys.path"). The file based on the DLL name overrides the one based on the executable, which allows paths to be restricted for any program loading the runtime if desired. When the file exists, all registry and environment variables are ignored, isolated mode is enabled, and [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") is not imported unless one line in the file specifies `import site`. Blank paths and lines starting with `#` are ignored. Each path may be absolute or relative to the location of the file. Import statements other than to `site` are not permitted, and arbitrary code cannot be specified. Note that `.pth` files (without leading underscore) will be processed normally by the [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") module when `import site` has been specified. When no `._pth` file is found, this is how [`sys.path`](../library/sys#sys.path "sys.path") is populated on Windows: * An empty entry is added at the start, which corresponds to the current directory. * If the environment variable [`PYTHONPATH`](cmdline#envvar-PYTHONPATH) exists, as described in [Environment variables](cmdline#using-on-envvars), its entries are added next. Note that on Windows, paths in this variable must be separated by semicolons, to distinguish them from the colon used in drive identifiers (`C:\` etc.). * Additional “application paths” can be added in the registry as subkeys of `\SOFTWARE\Python\PythonCore{version}\PythonPath` under both the `HKEY_CURRENT_USER` and `HKEY_LOCAL_MACHINE` hives. Subkeys which have semicolon-delimited path strings as their default value will cause each path to be added to [`sys.path`](../library/sys#sys.path "sys.path"). (Note that all known installers only use HKLM, so HKCU is typically empty.) * If the environment variable [`PYTHONHOME`](cmdline#envvar-PYTHONHOME) is set, it is assumed as “Python Home”. Otherwise, the path of the main Python executable is used to locate a “landmark file” (either `Lib\os.py` or `pythonXY.zip`) to deduce the “Python Home”. If a Python home is found, the relevant sub-directories added to [`sys.path`](../library/sys#sys.path "sys.path") (`Lib`, `plat-win`, etc) are based on that folder. Otherwise, the core Python path is constructed from the PythonPath stored in the registry. * If the Python Home cannot be located, no [`PYTHONPATH`](cmdline#envvar-PYTHONPATH) is specified in the environment, and no registry entries can be found, a default path with relative entries is used (e.g. `.\Lib;.\plat-win`, etc). If a `pyvenv.cfg` file is found alongside the main executable or in the directory one level above the executable, the following variations apply: * If `home` is an absolute path and [`PYTHONHOME`](cmdline#envvar-PYTHONHOME) is not set, this path is used instead of the path to the main executable when deducing the home location. The end result of all this is: * When running `python.exe`, or any other .exe in the main Python directory (either an installed version, or directly from the PCbuild directory), the core path is deduced, and the core paths in the registry are ignored. Other “application paths” in the registry are always read. * When Python is hosted in another .exe (different directory, embedded via COM, etc), the “Python Home” will not be deduced, so the core path from the registry is used. Other “application paths” in the registry are always read. * If Python can’t find its home and there are no registry value (frozen .exe, some very strange installation setup) you get a path with some default, but relative, paths. For those who want to bundle Python into their application or distribution, the following advice will prevent conflicts with other installations: * Include a `._pth` file alongside your executable containing the directories to include. This will ignore paths listed in the registry and environment variables, and also ignore [`site`](../library/site#module-site "site: Module responsible for site-specific configuration.") unless `import site` is listed. * If you are loading `python3.dll` or `python37.dll` in your own executable, explicitly call [`Py_SetPath()`](../c-api/init#c.Py_SetPath "Py_SetPath") or (at least) [`Py_SetProgramName()`](../c-api/init#c.Py_SetProgramName "Py_SetProgramName") before [`Py_Initialize()`](../c-api/init#c.Py_Initialize "Py_Initialize"). * Clear and/or overwrite [`PYTHONPATH`](cmdline#envvar-PYTHONPATH) and set [`PYTHONHOME`](cmdline#envvar-PYTHONHOME) before launching `python.exe` from your application. * If you cannot use the previous suggestions (for example, you are a distribution that allows people to run `python.exe` directly), ensure that the landmark file (`Lib\os.py`) exists in your install directory. (Note that it will not be detected inside a ZIP file, but a correctly named ZIP file will be detected instead.) These will ensure that the files in a system-wide installation will not take precedence over the copy of the standard library bundled with your application. Otherwise, your users may experience problems using your application. Note that the first suggestion is the best, as the others may still be susceptible to non-standard paths in the registry and user site-packages. Changed in version 3.6: * Adds `._pth` file support and removes `applocal` option from `pyvenv.cfg`. * Adds `pythonXX.zip` as a potential landmark when directly adjacent to the executable. Deprecated since version 3.6: Modules specified in the registry under `Modules` (not `PythonPath`) may be imported by [`importlib.machinery.WindowsRegistryFinder`](../library/importlib#importlib.machinery.WindowsRegistryFinder "importlib.machinery.WindowsRegistryFinder"). This finder is enabled on Windows in 3.6.0 and earlier, but may need to be explicitly added to [`sys.meta_path`](../library/sys#sys.meta_path "sys.meta_path") in the future. 3.10. Additional modules ------------------------- Even though Python aims to be portable among all platforms, there are features that are unique to Windows. A couple of modules, both in the standard library and external, and snippets exist to use these features. The Windows-specific standard modules are documented in [MS Windows Specific Services](../library/windows#mswin-specific-services). ### 3.10.1. PyWin32 The [PyWin32](https://pypi.org/project/pywin32) module by Mark Hammond is a collection of modules for advanced Windows-specific support. This includes utilities for: * [Component Object Model](https://docs.microsoft.com/en-us/windows/win32/com/component-object-model--com--portal) (COM) * Win32 API calls * Registry * Event log * [Microsoft Foundation Classes](https://docs.microsoft.com/en-us/cpp/mfc/mfc-desktop-applications) (MFC) user interfaces [PythonWin](https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/) is a sample MFC application shipped with PyWin32. It is an embeddable IDE with a built-in debugger. See also [Win32 How Do I…?](http://timgolden.me.uk/python/win32_how_do_i.html) by Tim Golden [Python and COM](https://www.boddie.org.uk/python/COM.html) by David and Paul Boddie ### 3.10.2. cx\_Freeze [cx\_Freeze](https://cx-freeze.readthedocs.io/en/latest/) is a [`distutils`](../library/distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") extension (see [Extending Distutils](../distutils/extending#extending-distutils)) which wraps Python scripts into executable Windows programs (`*\**.exe` files). When you have done this, you can distribute your application without requiring your users to install Python. 3.11. Compiling Python on Windows ---------------------------------- If you want to compile CPython yourself, first thing you should do is get the [source](https://www.python.org/downloads/source/). You can download either the latest release’s source or just grab a fresh [checkout](https://devguide.python.org/setup/#getting-the-source-code). The source tree contains a build solution and project files for Microsoft Visual Studio, which is the compiler used to build the official Python releases. These files are in the `PCbuild` directory. Check `PCbuild/readme.txt` for general information on the build process. For extension modules, consult [Building C and C++ Extensions on Windows](../extending/windows#building-on-windows). 3.12. Other Platforms ---------------------- With ongoing development of Python, some platforms that used to be supported earlier are no longer supported (due to the lack of users or developers). Check [**PEP 11**](https://www.python.org/dev/peps/pep-0011) for details on all unsupported platforms. * [Windows CE](http://pythonce.sourceforge.net/) is [no longer supported](https://github.com/python/cpython/issues/71542) since Python 3 (if it ever was). * The [Cygwin](https://cygwin.com/) installer offers to install the [Python interpreter](https://cygwin.com/packages/summary/python3.html) as well See [Python for Windows](https://www.python.org/downloads/windows/) for detailed information about platforms with pre-compiled installers.
programming_docs
python typing — Support for type hints typing — Support for type hints =============================== New in version 3.5. **Source code:** [Lib/typing.py](https://github.com/python/cpython/tree/3.9/Lib/typing.py) Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types [`Any`](#typing.Any "typing.Any"), [`Union`](#typing.Union "typing.Union"), [`Callable`](#typing.Callable "typing.Callable"), [`TypeVar`](#typing.TypeVar "typing.TypeVar"), and [`Generic`](#typing.Generic "typing.Generic"). For a full specification, please see [**PEP 484**](https://www.python.org/dev/peps/pep-0484). For a simplified introduction to type hints, see [**PEP 483**](https://www.python.org/dev/peps/pep-0483). The function below takes and returns a string and is annotated as follows: ``` def greeting(name: str) -> str: return 'Hello ' + name ``` In the function `greeting`, the argument `name` is expected to be of type [`str`](stdtypes#str "str") and the return type [`str`](stdtypes#str "str"). Subtypes are accepted as arguments. New features are frequently added to the `typing` module. The [typing\_extensions](https://pypi.org/project/typing-extensions/) package provides backports of these new features to older versions of Python. Relevant PEPs ------------- Since the initial introduction of type hints in [**PEP 484**](https://www.python.org/dev/peps/pep-0484) and [**PEP 483**](https://www.python.org/dev/peps/pep-0483), a number of PEPs have modified and enhanced Python’s framework for type annotations. These include: * [**PEP 526**](https://www.python.org/dev/peps/pep-0526): Syntax for Variable Annotations *Introducing* syntax for annotating variables outside of function definitions, and [`ClassVar`](#typing.ClassVar "typing.ClassVar") * [**PEP 544**](https://www.python.org/dev/peps/pep-0544): Protocols: Structural subtyping (static duck typing) *Introducing* [`Protocol`](#typing.Protocol "typing.Protocol") and the [`@runtime_checkable`](#typing.runtime_checkable "typing.runtime_checkable") decorator * [**PEP 585**](https://www.python.org/dev/peps/pep-0585): Type Hinting Generics In Standard Collections *Introducing* [`types.GenericAlias`](types#types.GenericAlias "types.GenericAlias") and the ability to use standard library classes as [generic types](stdtypes#types-genericalias) * [**PEP 586**](https://www.python.org/dev/peps/pep-0586): Literal Types *Introducing* [`Literal`](#typing.Literal "typing.Literal") * [**PEP 589**](https://www.python.org/dev/peps/pep-0589): TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys *Introducing* [`TypedDict`](#typing.TypedDict "typing.TypedDict") * [**PEP 591**](https://www.python.org/dev/peps/pep-0591): Adding a final qualifier to typing *Introducing* [`Final`](#typing.Final "typing.Final") and the [`@final`](#typing.final "typing.final") decorator * [**PEP 593**](https://www.python.org/dev/peps/pep-0593): Flexible function and variable annotations *Introducing* [`Annotated`](#typing.Annotated "typing.Annotated") Type aliases ------------ A type alias is defined by assigning the type to the alias. In this example, `Vector` and `list[float]` will be treated as interchangeable synonyms: ``` Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) ``` Type aliases are useful for simplifying complex type signatures. For example: ``` from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ... ``` Note that `None` as a type hint is a special case and is replaced by `type(None)`. NewType ------- Use the [`NewType()`](#typing.NewType "typing.NewType") helper to create distinct types: ``` from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313) ``` The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors: ``` def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1) ``` You may still perform all `int` operations on a variable of type `UserId`, but the result will always be of type `int`. This lets you pass in a `UserId` wherever an `int` might be expected, but will prevent you from accidentally creating a `UserId` in an invalid way: ``` # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341) ``` Note that these checks are enforced only by the static type checker. At runtime, the statement `Derived = NewType('Derived', Base)` will make `Derived` a callable that immediately returns whatever parameter you pass it. That means the expression `Derived(some_value)` does not create a new class or introduce any overhead beyond that of a regular function call. More precisely, the expression `some_value is Derived(some_value)` is always true at runtime. This also means that it is not possible to create a subtype of `Derived` since it is an identity function at runtime, not an actual type: ``` from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not typecheck class AdminUserId(UserId): pass ``` However, it is possible to create a [`NewType()`](#typing.NewType "typing.NewType") based on a ‘derived’ `NewType`: ``` from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) ``` and typechecking for `ProUserId` will work as expected. See [**PEP 484**](https://www.python.org/dev/peps/pep-0484) for more details. Note Recall that the use of a type alias declares two types to be *equivalent* to one another. Doing `Alias = Original` will make the static type checker treat `Alias` as being *exactly equivalent* to `Original` in all cases. This is useful when you want to simplify complex type signatures. In contrast, `NewType` declares one type to be a *subtype* of another. Doing `Derived = NewType('Derived', Original)` will make the static type checker treat `Derived` as a *subclass* of `Original`, which means a value of type `Original` cannot be used in places where a value of type `Derived` is expected. This is useful when you want to prevent logic errors with minimal runtime cost. New in version 3.5.2. Callable -------- Frameworks expecting callback functions of specific signatures might be type hinted using `Callable[[Arg1Type, Arg2Type], ReturnType]`. For example: ``` from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update ``` It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: `Callable[..., ReturnType]`. Generics -------- Since type information about objects kept in containers cannot be statically inferred in a generic way, abstract base classes have been extended to support subscription to denote expected types for container elements. ``` from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ... ``` Generics can be parameterized by using a factory available in typing called [`TypeVar`](#typing.TypeVar "typing.TypeVar"). ``` from collections.abc import Sequence from typing import TypeVar T = TypeVar('T') # Declare type variable def first(l: Sequence[T]) -> T: # Generic function return l[0] ``` User-defined generic types -------------------------- A user-defined class can be defined as a generic class. ``` from typing import TypeVar, Generic from logging import Logger T = TypeVar('T') class LoggedVar(Generic[T]): def __init__(self, value: T, name: str, logger: Logger) -> None: self.name = name self.logger = logger self.value = value def set(self, new: T) -> None: self.log('Set ' + repr(self.value)) self.value = new def get(self) -> T: self.log('Get ' + repr(self.value)) return self.value def log(self, message: str) -> None: self.logger.info('%s: %s', self.name, message) ``` `Generic[T]` as a base class defines that the class `LoggedVar` takes a single type parameter `T` . This also makes `T` valid as a type within the class body. The [`Generic`](#typing.Generic "typing.Generic") base class defines [`__class_getitem__()`](../reference/datamodel#object.__class_getitem__ "object.__class_getitem__") so that `LoggedVar[t]` is valid as a type: ``` from collections.abc import Iterable def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: for var in vars: var.set(0) ``` A generic type can have any number of type variables. All varieties of [`TypeVar`](#typing.TypeVar "typing.TypeVar") are permissible as parameters for a generic type: ``` from typing import TypeVar, Generic, Sequence T = TypeVar('T', contravariant=True) B = TypeVar('B', bound=Sequence[bytes], covariant=True) S = TypeVar('S', int, str) class WeirdTrio(Generic[T, B, S]): ... ``` Each type variable argument to [`Generic`](#typing.Generic "typing.Generic") must be distinct. This is thus invalid: ``` from typing import TypeVar, Generic ... T = TypeVar('T') class Pair(Generic[T, T]): # INVALID ... ``` You can use multiple inheritance with [`Generic`](#typing.Generic "typing.Generic"): ``` from collections.abc import Sized from typing import TypeVar, Generic T = TypeVar('T') class LinkedList(Sized, Generic[T]): ... ``` When inheriting from generic classes, some type variables could be fixed: ``` from collections.abc import Mapping from typing import TypeVar T = TypeVar('T') class MyDict(Mapping[str, T]): ... ``` In this case `MyDict` has a single parameter, `T`. Using a generic class without specifying type parameters assumes [`Any`](#typing.Any "typing.Any") for each position. In the following example, `MyIterable` is not generic but implicitly inherits from `Iterable[Any]`: ``` from collections.abc import Iterable class MyIterable(Iterable): # Same as Iterable[Any] ``` User defined generic type aliases are also supported. Examples: ``` from collections.abc import Iterable from typing import TypeVar, Union S = TypeVar('S') Response = Union[Iterable[S], int] # Return type here is same as Union[Iterable[str], int] def response(query: str) -> Response[str]: ... T = TypeVar('T', int, float, complex) Vec = Iterable[tuple[T, T]] def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]] return sum(x*y for x, y in v) ``` Changed in version 3.7: [`Generic`](#typing.Generic "typing.Generic") no longer has a custom metaclass. A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality. The Any type ------------ A special kind of type is [`Any`](#typing.Any "typing.Any"). A static type checker will treat every type as being compatible with [`Any`](#typing.Any "typing.Any") and [`Any`](#typing.Any "typing.Any") as being compatible with every type. This means that it is possible to perform any operation or method call on a value of type [`Any`](#typing.Any "typing.Any") and assign it to any variable: ``` from typing import Any a: Any = None a = [] # OK a = 2 # OK s: str = '' s = a # OK def foo(item: Any) -> int: # Typechecks; 'item' could be any type, # and that type might have a 'bar' method item.bar() ... ``` Notice that no typechecking is performed when assigning a value of type [`Any`](#typing.Any "typing.Any") to a more precise type. For example, the static type checker did not report an error when assigning `a` to `s` even though `s` was declared to be of type [`str`](stdtypes#str "str") and receives an [`int`](functions#int "int") value at runtime! Furthermore, all functions without a return type or parameter types will implicitly default to using [`Any`](#typing.Any "typing.Any"): ``` def legacy_parser(text): ... return data # A static type checker will treat the above # as having the same signature as: def legacy_parser(text: Any) -> Any: ... return data ``` This behavior allows [`Any`](#typing.Any "typing.Any") to be used as an *escape hatch* when you need to mix dynamically and statically typed code. Contrast the behavior of [`Any`](#typing.Any "typing.Any") with the behavior of [`object`](functions#object "object"). Similar to [`Any`](#typing.Any "typing.Any"), every type is a subtype of [`object`](functions#object "object"). However, unlike [`Any`](#typing.Any "typing.Any"), the reverse is not true: [`object`](functions#object "object") is *not* a subtype of every other type. That means when the type of a value is [`object`](functions#object "object"), a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example: ``` def hash_a(item: object) -> int: # Fails; an object does not have a 'magic' method. item.magic() ... def hash_b(item: Any) -> int: # Typechecks item.magic() ... # Typechecks, since ints and strs are subclasses of object hash_a(42) hash_a("foo") # Typechecks, since Any is compatible with all types hash_b(42) hash_b("foo") ``` Use [`object`](functions#object "object") to indicate that a value could be any type in a typesafe manner. Use [`Any`](#typing.Any "typing.Any") to indicate that a value is dynamically typed. Nominal vs structural subtyping ------------------------------- Initially [**PEP 484**](https://www.python.org/dev/peps/pep-0484) defined the Python static type system as using *nominal subtyping*. This means that a class `A` is allowed where a class `B` is expected if and only if `A` is a subclass of `B`. This requirement previously also applied to abstract base classes, such as [`Iterable`](collections.abc#collections.abc.Iterable "collections.abc.Iterable"). The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to [**PEP 484**](https://www.python.org/dev/peps/pep-0484): ``` from collections.abc import Sized, Iterable, Iterator class Bucket(Sized, Iterable[int]): ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... ``` [**PEP 544**](https://www.python.org/dev/peps/pep-0544) allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing `Bucket` to be implicitly considered a subtype of both `Sized` and `Iterable[int]` by static type checkers. This is known as *structural subtyping* (or static duck-typing): ``` from collections.abc import Iterator, Iterable class Bucket: # Note: no base classes ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def collect(items: Iterable[int]) -> int: ... result = collect(Bucket()) # Passes type check ``` Moreover, by subclassing a special class [`Protocol`](#typing.Protocol "typing.Protocol"), a user can define new custom protocols to fully enjoy structural subtyping (see examples below). Module contents --------------- The module defines the following classes, functions and decorators. Note This module defines several types that are subclasses of pre-existing standard library classes which also extend [`Generic`](#typing.Generic "typing.Generic") to support type variables inside `[]`. These types became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support `[]`. The redundant types are deprecated as of Python 3.9 but no deprecation warnings will be issued by the interpreter. It is expected that type checkers will flag the deprecated types when the checked program targets Python 3.9 or newer. The deprecated types will be removed from the [`typing`](#module-typing "typing: Support for type hints (see :pep:`484`).") module in the first Python version released 5 years after the release of Python 3.9.0. See details in [**PEP 585**](https://www.python.org/dev/peps/pep-0585)—*Type Hinting Generics In Standard Collections*. ### Special typing primitives #### Special types These can be used as types in annotations and do not support `[]`. `typing.Any` Special type indicating an unconstrained type. * Every type is compatible with [`Any`](#typing.Any "typing.Any"). * [`Any`](#typing.Any "typing.Any") is compatible with every type. `typing.NoReturn` Special type indicating that a function never returns. For example: ``` from typing import NoReturn def stop() -> NoReturn: raise RuntimeError('no way') ``` New in version 3.5.4. New in version 3.6.2. #### Special forms These can be used as types in annotations using `[]`, each having a unique syntax. `typing.Tuple` Tuple type; `Tuple[X, Y]` is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written as `Tuple[()]`. Example: `Tuple[T1, T2]` is a tuple of two elements corresponding to type variables T1 and T2. `Tuple[int, float, str]` is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. `Tuple[int, ...]`. A plain [`Tuple`](#typing.Tuple "typing.Tuple") is equivalent to `Tuple[Any, ...]`, and in turn to [`tuple`](stdtypes#tuple "tuple"). Deprecated since version 3.9: [`builtins.tuple`](stdtypes#tuple "tuple") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `typing.Union` Union type; `Union[X, Y]` means either X or Y. To define a union, use e.g. `Union[int, str]`. Details: * The arguments must be types and there must be at least one. * Unions of unions are flattened, e.g.: ``` Union[Union[int, str], float] == Union[int, str, float] ``` * Unions of a single argument vanish, e.g.: ``` Union[int] == int # The constructor actually returns int ``` * Redundant arguments are skipped, e.g.: ``` Union[int, str, int] == Union[int, str] ``` * When comparing unions, the argument order is ignored, e.g.: ``` Union[int, str] == Union[str, int] ``` * You cannot subclass or instantiate a union. * You cannot write `Union[X][Y]`. * You can use `Optional[X]` as a shorthand for `Union[X, None]`. Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime. `typing.Optional` Optional type. `Optional[X]` is equivalent to `Union[X, None]`. Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example: ``` def foo(arg: int = 0) -> None: ... ``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example: ``` def foo(arg: Optional[int] = None) -> None: ... ``` `typing.Callable` Callable type; `Callable[[int], str]` is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type. There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. `Callable[..., ReturnType]` (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning `ReturnType`. A plain [`Callable`](#typing.Callable "typing.Callable") is equivalent to `Callable[..., Any]`, and in turn to [`collections.abc.Callable`](collections.abc#collections.abc.Callable "collections.abc.Callable"). Deprecated since version 3.9: [`collections.abc.Callable`](collections.abc#collections.abc.Callable "collections.abc.Callable") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Type(Generic[CT_co])` A variable annotated with `C` may accept a value of type `C`. In contrast, a variable annotated with `Type[C]` may accept values that are classes themselves – specifically, it will accept the *class object* of `C`. For example: ``` a = 3 # Has type 'int' b = int # Has type 'Type[int]' c = type(a) # Also has type 'Type[int]' ``` Note that `Type[C]` is covariant: ``` class User: ... class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... # Accepts User, BasicUser, ProUser, TeamUser, ... def make_new_user(user_class: Type[User]) -> User: # ... return user_class() ``` The fact that `Type[C]` is covariant implies that all subclasses of `C` should implement the same constructor signature and class method signatures as `C`. The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of [**PEP 484**](https://www.python.org/dev/peps/pep-0484). The only legal parameters for [`Type`](#typing.Type "typing.Type") are classes, [`Any`](#typing.Any "typing.Any"), [type variables](#generics), and unions of any of these types. For example: ``` def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ... ``` `Type[Any]` is equivalent to `Type` which in turn is equivalent to `type`, which is the root of Python’s metaclass hierarchy. New in version 3.5.2. Deprecated since version 3.9: [`builtins.type`](functions#type "type") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `typing.Literal` A type that can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals). For example: ``` def validate_simple(data: Any) -> Literal[True]: # always returns True ... MODE = Literal['r', 'rb', 'w', 'wb'] def open_helper(file: str, mode: MODE) -> str: ... open_helper('/some/path', 'r') # Passes type check open_helper('/other/path', 'typo') # Error in type checker ``` `Literal[...]` cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to `Literal[...]`, but type checkers may impose restrictions. See [**PEP 586**](https://www.python.org/dev/peps/pep-0586) for more details about literal types. New in version 3.8. Changed in version 3.9.1: `Literal` now de-duplicates parameters. Equality comparisons of `Literal` objects are no longer order dependent. `Literal` objects will now raise a [`TypeError`](exceptions#TypeError "TypeError") exception during equality comparisons if one of their parameters are not [hashable](../glossary#term-hashable). `typing.ClassVar` Special type construct to mark class variables. As introduced in [**PEP 526**](https://www.python.org/dev/peps/pep-0526), a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage: ``` class Starship: stats: ClassVar[dict[str, int]] = {} # class variable damage: int = 10 # instance variable ``` [`ClassVar`](#typing.ClassVar "typing.ClassVar") accepts only types and cannot be further subscribed. [`ClassVar`](#typing.ClassVar "typing.ClassVar") is not a class itself, and should not be used with [`isinstance()`](functions#isinstance "isinstance") or [`issubclass()`](functions#issubclass "issubclass"). [`ClassVar`](#typing.ClassVar "typing.ClassVar") does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error: ``` enterprise_d = Starship(3000) enterprise_d.stats = {} # Error, setting class variable on instance Starship.stats = {} # This is OK ``` New in version 3.5.3. `typing.Final` A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass. For example: ``` MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker ``` There is no runtime checking of these properties. See [**PEP 591**](https://www.python.org/dev/peps/pep-0591) for more details. New in version 3.8. `typing.Annotated` A type, introduced in [**PEP 593**](https://www.python.org/dev/peps/pep-0593) (`Flexible function and variable annotations`), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as `Annotated` is variadic). Specifically, a type `T` can be annotated with metadata `x` via the typehint `Annotated[T, x]`. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint `Annotated[T, x]` and has no special logic for metadata `x`, it should ignore it and simply treat the type as `T`. Unlike the `no_type_check` functionality that currently exists in the `typing` module which completely disables typechecking annotations on a function or a class, the `Annotated` type allows for both static typechecking of `T` (which can safely ignore `x`) together with runtime access to `x` within a specific application. Ultimately, the responsibility of how to interpret the annotations (if at all) is the responsibility of the tool or library encountering the `Annotated` type. A tool or library encountering an `Annotated` type can scan through the annotations to determine if they are of interest (e.g., using `isinstance()`). When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type. It’s up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations. Since the `Annotated` type allows you to put several annotations of the same (or different) type(s) on any node, the tools or libraries consuming those annotations are in charge of dealing with potential duplicates. For example, if you are doing value range analysis you might allow this: ``` T1 = Annotated[int, ValueRange(-10, 5)] T2 = Annotated[T1, ValueRange(-20, 3)] ``` Passing `include_extras=True` to [`get_type_hints()`](#typing.get_type_hints "typing.get_type_hints") lets one access the extra annotations at runtime. The details of the syntax: * The first argument to `Annotated` must be a valid type * Multiple type annotations are supported (`Annotated` supports variadic arguments): ``` Annotated[int, ValueRange(3, 10), ctype("char")] ``` * `Annotated` must be called with at least two arguments ( `Annotated[int]` is not valid) * The order of the annotations is preserved and matters for equality checks: ``` Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ int, ctype("char"), ValueRange(3, 10) ] ``` * Nested `Annotated` types are flattened, with metadata ordered starting with the innermost annotation: ``` Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ int, ValueRange(3, 10), ctype("char") ] ``` * Duplicated annotations are not removed: ``` Annotated[int, ValueRange(3, 10)] != Annotated[ int, ValueRange(3, 10), ValueRange(3, 10) ] ``` * `Annotated` can be used with nested and generic aliases: ``` T = TypeVar('T') Vec = Annotated[list[tuple[T, T]], MaxLen(10)] V = Vec[int] V == Annotated[list[tuple[int, int]], MaxLen(10)] ``` New in version 3.9. #### Building generic types These are not used in annotations. They are building blocks for creating generic types. `class typing.Generic` Abstract base class for generic types. A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as: ``` class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. ``` This class can then be used as follows: ``` X = TypeVar('X') Y = TypeVar('Y') def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: try: return mapping[key] except KeyError: return default ``` `class typing.TypeVar` Type variable. Usage: ``` T = TypeVar('T') # Can be anything S = TypeVar('S', bound=str) # Can be any subtype of str A = TypeVar('A', str, bytes) # Must be exactly str or bytes ``` Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See [`Generic`](#typing.Generic "typing.Generic") for more information on generic types. Generic functions work as follows: ``` def repeat(x: T, n: int) -> Sequence[T]: """Return a list containing n references to x.""" return [x]*n def print_capitalized(x: S) -> S: """Print x capitalized, and return x.""" print(x.capitalize()) return x def concatenate(x: A, y: A) -> A: """Add two strings or bytes objects together.""" return x + y ``` Note that type variables can be *bound*, *constrained*, or neither, but cannot be both bound *and* constrained. Constrained type variables and bound type variables have different semantics in several important ways. Using a *constrained* type variable means that the `TypeVar` can only ever be solved as being exactly one of the constraints given: ``` a = concatenate('one', 'two') # Ok, variable 'a' has type 'str' b = concatenate(StringSubclass('one'), StringSubclass('two')) # Inferred type of variable 'b' is 'str', # despite 'StringSubclass' being passed in c = concatenate('one', b'two') # error: type variable 'A' can be either 'str' or 'bytes' in a function call, but not both ``` Using a *bound* type variable, however, means that the `TypeVar` will be solved using the most specific type possible: ``` print_capitalized('a string') # Ok, output has type 'str' class StringSubclass(str): pass print_capitalized(StringSubclass('another string')) # Ok, output has type 'StringSubclass' print_capitalized(45) # error: int is not a subtype of str ``` Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types: ``` U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method ``` Bound type variables are particularly useful for annotating [`classmethods`](functions#classmethod "classmethod") that serve as alternative constructors. In the following example (© [Raymond Hettinger](https://www.youtube.com/watch?v=HTLu2DFOdTg)), the type variable `C` is bound to the `Circle` class through the use of a forward reference. Using this type variable to annotate the `with_circumference` classmethod, rather than hardcoding the return type as `Circle`, means that a type checker can correctly infer the return type even if the method is called on a subclass: ``` import math C = TypeVar('C', bound='Circle') class Circle: """An abstract circle""" def __init__(self, radius: float) -> None: self.radius = radius # Use a type variable to show that the return type # will always be an instance of whatever ``cls`` is @classmethod def with_circumference(cls: type[C], circumference: float) -> C: """Create a circle with the specified circumference""" radius = circumference / (math.pi * 2) return cls(radius) class Tire(Circle): """A specialised circle (made out of rubber)""" MATERIAL = 'rubber' c = Circle.with_circumference(3) # Ok, variable 'c' has type 'Circle' t = Tire.with_circumference(4) # Ok, variable 't' has type 'Tire' (not 'Circle') ``` At runtime, `isinstance(x, T)` will raise [`TypeError`](exceptions#TypeError "TypeError"). In general, [`isinstance()`](functions#isinstance "isinstance") and [`issubclass()`](functions#issubclass "issubclass") should not be used with types. Type variables may be marked covariant or contravariant by passing `covariant=True` or `contravariant=True`. See [**PEP 484**](https://www.python.org/dev/peps/pep-0484) for more details. By default, type variables are invariant. `typing.AnyStr` `AnyStr` is a [`constrained type variable`](#typing.TypeVar "typing.TypeVar") defined as `AnyStr = TypeVar('AnyStr', str, bytes)`. It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example: ``` def concat(a: AnyStr, b: AnyStr) -> AnyStr: return a + b concat(u"foo", u"bar") # Ok, output has type 'unicode' concat(b"foo", b"bar") # Ok, output has type 'bytes' concat(u"foo", b"bar") # Error, cannot mix unicode and bytes ``` `class typing.Protocol(Generic)` Base class for protocol classes. Protocol classes are defined like this: ``` class Proto(Protocol): def meth(self) -> int: ... ``` Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example: ``` class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check ``` See [**PEP 544**](https://www.python.org/dev/peps/pep-0544) for details. Protocol classes decorated with [`runtime_checkable()`](#typing.runtime_checkable "typing.runtime_checkable") (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, for example: ``` class GenProto(Protocol[T]): def meth(self) -> T: ... ``` New in version 3.8. `@typing.runtime_checkable` Mark a protocol class as a runtime protocol. Such a protocol can be used with [`isinstance()`](functions#isinstance "isinstance") and [`issubclass()`](functions#issubclass "issubclass"). This raises [`TypeError`](exceptions#TypeError "TypeError") when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in [`collections.abc`](collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") such as [`Iterable`](collections.abc#collections.abc.Iterable "collections.abc.Iterable"). For example: ``` @runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable) ``` Note [`runtime_checkable()`](#typing.runtime_checkable "typing.runtime_checkable") will check only the presence of the required methods, not their type signatures! For example, [`builtins.complex`](functions#complex "complex") implements [`__float__()`](../reference/datamodel#object.__float__ "object.__float__"), therefore it passes an [`issubclass()`](functions#issubclass "issubclass") check against [`SupportsFloat`](#typing.SupportsFloat "typing.SupportsFloat"). However, the `complex.__float__` method exists only to raise a [`TypeError`](exceptions#TypeError "TypeError") with a more informative message. New in version 3.8. #### Other special directives These are not used in annotations. They are building blocks for declaring types. `class typing.NamedTuple` Typed version of [`collections.namedtuple()`](collections#collections.namedtuple "collections.namedtuple"). Usage: ``` class Employee(NamedTuple): name: str id: int ``` This is equivalent to: ``` Employee = collections.namedtuple('Employee', ['name', 'id']) ``` To give a field a default value, you can assign to it in the class body: ``` class Employee(NamedTuple): name: str id: int = 3 employee = Employee('Guido') assert employee.id == 3 ``` Fields with a default value must come after any fields without a default. The resulting class has an extra attribute `__annotations__` giving a dict that maps the field names to the field types. (The field names are in the `_fields` attribute and the default values are in the `_field_defaults` attribute, both of which are part of the [`namedtuple()`](collections#collections.namedtuple "collections.namedtuple") API.) `NamedTuple` subclasses can also have docstrings and methods: ``` class Employee(NamedTuple): """Represents an employee.""" name: str id: int = 3 def __repr__(self) -> str: return f'<Employee {self.name}, id={self.id}>' ``` Backward-compatible usage: ``` Employee = NamedTuple('Employee', [('name', str), ('id', int)]) ``` Changed in version 3.6: Added support for [**PEP 526**](https://www.python.org/dev/peps/pep-0526) variable annotation syntax. Changed in version 3.6.1: Added support for default values, methods, and docstrings. Changed in version 3.8: The `_field_types` and `__annotations__` attributes are now regular dictionaries instead of instances of `OrderedDict`. Changed in version 3.9: Removed the `_field_types` attribute in favor of the more standard `__annotations__` attribute which has the same information. `typing.NewType(name, tp)` A helper function to indicate a distinct type to a typechecker, see [NewType](#distinct). At runtime it returns a function that returns its argument. Usage: ``` UserId = NewType('UserId', int) first_user = UserId(1) ``` New in version 3.5.2. `class typing.TypedDict(dict)` Special construct to add type hints to a dictionary. At runtime it is a plain [`dict`](stdtypes#dict "dict"). `TypedDict` declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage: ``` class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') ``` To allow using this feature with older versions of Python that do not support [**PEP 526**](https://www.python.org/dev/peps/pep-0526), `TypedDict` supports two additional equivalent syntactic forms: * Using a literal [`dict`](stdtypes#dict "dict") as the second argument: ``` Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) ``` * Using keyword arguments: ``` Point2D = TypedDict('Point2D', x=int, y=int, label=str) ``` The functional syntax should also be used when any of the keys are not valid [identifiers](../reference/lexical_analysis#identifiers), for example because they are keywords or contain hyphens. Example: ``` # raises SyntaxError class Point2D(TypedDict): in: int # 'in' is a keyword x-y: int # name with hyphens # OK, functional syntax Point2D = TypedDict('Point2D', {'in': int, 'x-y': int}) ``` By default, all keys must be present in a `TypedDict`. It is possible to override this by specifying totality. Usage: ``` class Point2D(TypedDict, total=False): x: int y: int # Alternative syntax Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False) ``` This means that a `Point2D` `TypedDict` can have any of the keys omitted. A type checker is only expected to support a literal `False` or `True` as the value of the `total` argument. `True` is the default, and makes all items defined in the class body required. It is possible for a `TypedDict` type to inherit from one or more other `TypedDict` types using the class-based syntax. Usage: ``` class Point3D(Point2D): z: int ``` `Point3D` has three items: `x`, `y` and `z`. It is equivalent to this definition: ``` class Point3D(TypedDict): x: int y: int z: int ``` A `TypedDict` cannot inherit from a non-`TypedDict` class, notably including [`Generic`](#typing.Generic "typing.Generic"). For example: ``` class X(TypedDict): x: int class Y(TypedDict): y: int class Z(object): pass # A non-TypedDict class class XY(X, Y): pass # OK class XZ(X, Z): pass # raises TypeError T = TypeVar('T') class XT(X, Generic[T]): pass # raises TypeError ``` A `TypedDict` can be introspected via `__annotations__`, [`__total__`](#typing.TypedDict.__total__ "typing.TypedDict.__total__"), [`__required_keys__`](#typing.TypedDict.__required_keys__ "typing.TypedDict.__required_keys__"), and [`__optional_keys__`](#typing.TypedDict.__optional_keys__ "typing.TypedDict.__optional_keys__"). `__total__` `Point2D.__total__` gives the value of the `total` argument. Example: ``` >>> from typing import TypedDict >>> class Point2D(TypedDict): pass >>> Point2D.__total__ True >>> class Point2D(TypedDict, total=False): pass >>> Point2D.__total__ False >>> class Point3D(Point2D): pass >>> Point3D.__total__ True ``` `__required_keys__` `__optional_keys__` `Point2D.__required_keys__` and `Point2D.__optional_keys__` return [`frozenset`](stdtypes#frozenset "frozenset") objects containing required and non-required keys, respectively. Currently the only way to declare both required and non-required keys in the same `TypedDict` is mixed inheritance, declaring a `TypedDict` with one value for the `total` argument and then inheriting it from another `TypedDict` with a different value for `total`. Usage: ``` >>> class Point2D(TypedDict, total=False): ... x: int ... y: int ... >>> class Point3D(Point2D): ... z: int ... >>> Point3D.__required_keys__ == frozenset({'z'}) True >>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) True ``` See [**PEP 589**](https://www.python.org/dev/peps/pep-0589) for more examples and detailed rules of using `TypedDict`. New in version 3.8. ### Generic concrete collections #### Corresponding to built-in types `class typing.Dict(dict, MutableMapping[KT, VT])` A generic version of [`dict`](stdtypes#dict "dict"). Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as [`Mapping`](#typing.Mapping "typing.Mapping"). This type can be used as follows: ``` def count_words(text: str) -> Dict[str, int]: ... ``` Deprecated since version 3.9: [`builtins.dict`](stdtypes#dict "dict") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.List(list, MutableSequence[T])` Generic version of [`list`](stdtypes#list "list"). Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as [`Sequence`](#typing.Sequence "typing.Sequence") or [`Iterable`](#typing.Iterable "typing.Iterable"). This type may be used as follows: ``` T = TypeVar('T', int, float) def vec2(x: T, y: T) -> List[T]: return [x, y] def keep_positives(vector: Sequence[T]) -> List[T]: return [item for item in vector if item > 0] ``` Deprecated since version 3.9: [`builtins.list`](stdtypes#list "list") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Set(set, MutableSet[T])` A generic version of [`builtins.set`](stdtypes#set "set"). Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as [`AbstractSet`](#typing.AbstractSet "typing.AbstractSet"). Deprecated since version 3.9: [`builtins.set`](stdtypes#set "set") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.FrozenSet(frozenset, AbstractSet[T_co])` A generic version of [`builtins.frozenset`](stdtypes#frozenset "frozenset"). Deprecated since version 3.9: [`builtins.frozenset`](stdtypes#frozenset "frozenset") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). Note [`Tuple`](#typing.Tuple "typing.Tuple") is a special form. #### Corresponding to types in [`collections`](collections#module-collections "collections: Container datatypes") `class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])` A generic version of [`collections.defaultdict`](collections#collections.defaultdict "collections.defaultdict"). New in version 3.5.2. Deprecated since version 3.9: [`collections.defaultdict`](collections#collections.defaultdict "collections.defaultdict") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])` A generic version of [`collections.OrderedDict`](collections#collections.OrderedDict "collections.OrderedDict"). New in version 3.7.2. Deprecated since version 3.9: [`collections.OrderedDict`](collections#collections.OrderedDict "collections.OrderedDict") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])` A generic version of [`collections.ChainMap`](collections#collections.ChainMap "collections.ChainMap"). New in version 3.5.4. New in version 3.6.1. Deprecated since version 3.9: [`collections.ChainMap`](collections#collections.ChainMap "collections.ChainMap") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Counter(collections.Counter, Dict[T, int])` A generic version of [`collections.Counter`](collections#collections.Counter "collections.Counter"). New in version 3.5.4. New in version 3.6.1. Deprecated since version 3.9: [`collections.Counter`](collections#collections.Counter "collections.Counter") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Deque(deque, MutableSequence[T])` A generic version of [`collections.deque`](collections#collections.deque "collections.deque"). New in version 3.5.4. New in version 3.6.1. Deprecated since version 3.9: [`collections.deque`](collections#collections.deque "collections.deque") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). #### Other concrete types `class typing.IO` `class typing.TextIO` `class typing.BinaryIO` Generic type `IO[AnyStr]` and its subclasses `TextIO(IO[str])` and `BinaryIO(IO[bytes])` represent the types of I/O streams such as returned by [`open()`](functions#open "open"). Deprecated since version 3.8, will be removed in version 3.12: These types are also in the `typing.io` namespace, which was never supported by type checkers and will be removed. `class typing.Pattern` `class typing.Match` These type aliases correspond to the return types from [`re.compile()`](re#re.compile "re.compile") and [`re.match()`](re#re.match "re.match"). These types (and the corresponding functions) are generic in `AnyStr` and can be made specific by writing `Pattern[str]`, `Pattern[bytes]`, `Match[str]`, or `Match[bytes]`. Deprecated since version 3.8, will be removed in version 3.12: These types are also in the `typing.re` namespace, which was never supported by type checkers and will be removed. Deprecated since version 3.9: Classes `Pattern` and `Match` from [`re`](re#module-re "re: Regular expression operations.") now support `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Text` `Text` is an alias for `str`. It is provided to supply a forward compatible path for Python 2 code: in Python 2, `Text` is an alias for `unicode`. Use `Text` to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3: ``` def add_unicode_checkmark(text: Text) -> Text: return text + u' \u2713' ``` New in version 3.5.2. ### Abstract Base Classes #### Corresponding to collections in [`collections.abc`](collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") `class typing.AbstractSet(Sized, Collection[T_co])` A generic version of [`collections.abc.Set`](collections.abc#collections.abc.Set "collections.abc.Set"). Deprecated since version 3.9: [`collections.abc.Set`](collections.abc#collections.abc.Set "collections.abc.Set") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.ByteString(Sequence[int])` A generic version of [`collections.abc.ByteString`](collections.abc#collections.abc.ByteString "collections.abc.ByteString"). This type represents the types [`bytes`](stdtypes#bytes "bytes"), [`bytearray`](stdtypes#bytearray "bytearray"), and [`memoryview`](stdtypes#memoryview "memoryview") of byte sequences. As a shorthand for this type, [`bytes`](stdtypes#bytes "bytes") can be used to annotate arguments of any of the types mentioned above. Deprecated since version 3.9: [`collections.abc.ByteString`](collections.abc#collections.abc.ByteString "collections.abc.ByteString") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Collection(Sized, Iterable[T_co], Container[T_co])` A generic version of [`collections.abc.Collection`](collections.abc#collections.abc.Collection "collections.abc.Collection") New in version 3.6.0. Deprecated since version 3.9: [`collections.abc.Collection`](collections.abc#collections.abc.Collection "collections.abc.Collection") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Container(Generic[T_co])` A generic version of [`collections.abc.Container`](collections.abc#collections.abc.Container "collections.abc.Container"). Deprecated since version 3.9: [`collections.abc.Container`](collections.abc#collections.abc.Container "collections.abc.Container") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.ItemsView(MappingView, Generic[KT_co, VT_co])` A generic version of [`collections.abc.ItemsView`](collections.abc#collections.abc.ItemsView "collections.abc.ItemsView"). Deprecated since version 3.9: [`collections.abc.ItemsView`](collections.abc#collections.abc.ItemsView "collections.abc.ItemsView") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.KeysView(MappingView[KT_co], AbstractSet[KT_co])` A generic version of [`collections.abc.KeysView`](collections.abc#collections.abc.KeysView "collections.abc.KeysView"). Deprecated since version 3.9: [`collections.abc.KeysView`](collections.abc#collections.abc.KeysView "collections.abc.KeysView") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Mapping(Sized, Collection[KT], Generic[VT_co])` A generic version of [`collections.abc.Mapping`](collections.abc#collections.abc.Mapping "collections.abc.Mapping"). This type can be used as follows: ``` def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: return word_list[word] ``` Deprecated since version 3.9: [`collections.abc.Mapping`](collections.abc#collections.abc.Mapping "collections.abc.Mapping") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.MappingView(Sized, Iterable[T_co])` A generic version of [`collections.abc.MappingView`](collections.abc#collections.abc.MappingView "collections.abc.MappingView"). Deprecated since version 3.9: [`collections.abc.MappingView`](collections.abc#collections.abc.MappingView "collections.abc.MappingView") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.MutableMapping(Mapping[KT, VT])` A generic version of [`collections.abc.MutableMapping`](collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping"). Deprecated since version 3.9: [`collections.abc.MutableMapping`](collections.abc#collections.abc.MutableMapping "collections.abc.MutableMapping") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.MutableSequence(Sequence[T])` A generic version of [`collections.abc.MutableSequence`](collections.abc#collections.abc.MutableSequence "collections.abc.MutableSequence"). Deprecated since version 3.9: [`collections.abc.MutableSequence`](collections.abc#collections.abc.MutableSequence "collections.abc.MutableSequence") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.MutableSet(AbstractSet[T])` A generic version of [`collections.abc.MutableSet`](collections.abc#collections.abc.MutableSet "collections.abc.MutableSet"). Deprecated since version 3.9: [`collections.abc.MutableSet`](collections.abc#collections.abc.MutableSet "collections.abc.MutableSet") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Sequence(Reversible[T_co], Collection[T_co])` A generic version of [`collections.abc.Sequence`](collections.abc#collections.abc.Sequence "collections.abc.Sequence"). Deprecated since version 3.9: [`collections.abc.Sequence`](collections.abc#collections.abc.Sequence "collections.abc.Sequence") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.ValuesView(MappingView[VT_co])` A generic version of [`collections.abc.ValuesView`](collections.abc#collections.abc.ValuesView "collections.abc.ValuesView"). Deprecated since version 3.9: [`collections.abc.ValuesView`](collections.abc#collections.abc.ValuesView "collections.abc.ValuesView") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). #### Corresponding to other types in [`collections.abc`](collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") `class typing.Iterable(Generic[T_co])` A generic version of [`collections.abc.Iterable`](collections.abc#collections.abc.Iterable "collections.abc.Iterable"). Deprecated since version 3.9: [`collections.abc.Iterable`](collections.abc#collections.abc.Iterable "collections.abc.Iterable") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Iterator(Iterable[T_co])` A generic version of [`collections.abc.Iterator`](collections.abc#collections.abc.Iterator "collections.abc.Iterator"). Deprecated since version 3.9: [`collections.abc.Iterator`](collections.abc#collections.abc.Iterator "collections.abc.Iterator") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])` A generator can be annotated by the generic type `Generator[YieldType, SendType, ReturnType]`. For example: ``` def echo_round() -> Generator[int, float, str]: sent = yield 0 while sent >= 0: sent = yield round(sent) return 'Done' ``` Note that unlike many other generics in the typing module, the `SendType` of [`Generator`](#typing.Generator "typing.Generator") behaves contravariantly, not covariantly or invariantly. If your generator will only yield values, set the `SendType` and `ReturnType` to `None`: ``` def infinite_stream(start: int) -> Generator[int, None, None]: while True: yield start start += 1 ``` Alternatively, annotate your generator as having a return type of either `Iterable[YieldType]` or `Iterator[YieldType]`: ``` def infinite_stream(start: int) -> Iterator[int]: while True: yield start start += 1 ``` Deprecated since version 3.9: [`collections.abc.Generator`](collections.abc#collections.abc.Generator "collections.abc.Generator") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Hashable` An alias to [`collections.abc.Hashable`](collections.abc#collections.abc.Hashable "collections.abc.Hashable"). `class typing.Reversible(Iterable[T_co])` A generic version of [`collections.abc.Reversible`](collections.abc#collections.abc.Reversible "collections.abc.Reversible"). Deprecated since version 3.9: [`collections.abc.Reversible`](collections.abc#collections.abc.Reversible "collections.abc.Reversible") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Sized` An alias to [`collections.abc.Sized`](collections.abc#collections.abc.Sized "collections.abc.Sized"). #### Asynchronous programming `class typing.Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co])` A generic version of [`collections.abc.Coroutine`](collections.abc#collections.abc.Coroutine "collections.abc.Coroutine"). The variance and order of type variables correspond to those of [`Generator`](#typing.Generator "typing.Generator"), for example: ``` from collections.abc import Coroutine c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere x = c.send('hi') # Inferred type of 'x' is list[str] async def bar() -> None: y = await c # Inferred type of 'y' is int ``` New in version 3.5.3. Deprecated since version 3.9: [`collections.abc.Coroutine`](collections.abc#collections.abc.Coroutine "collections.abc.Coroutine") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])` An async generator can be annotated by the generic type `AsyncGenerator[YieldType, SendType]`. For example: ``` async def echo_round() -> AsyncGenerator[int, float]: sent = yield 0 while sent >= 0.0: rounded = await round(sent) sent = yield rounded ``` Unlike normal generators, async generators cannot return a value, so there is no `ReturnType` type parameter. As with [`Generator`](#typing.Generator "typing.Generator"), the `SendType` behaves contravariantly. If your generator will only yield values, set the `SendType` to `None`: ``` async def infinite_stream(start: int) -> AsyncGenerator[int, None]: while True: yield start start = await increment(start) ``` Alternatively, annotate your generator as having a return type of either `AsyncIterable[YieldType]` or `AsyncIterator[YieldType]`: ``` async def infinite_stream(start: int) -> AsyncIterator[int]: while True: yield start start = await increment(start) ``` New in version 3.6.1. Deprecated since version 3.9: [`collections.abc.AsyncGenerator`](collections.abc#collections.abc.AsyncGenerator "collections.abc.AsyncGenerator") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.AsyncIterable(Generic[T_co])` A generic version of [`collections.abc.AsyncIterable`](collections.abc#collections.abc.AsyncIterable "collections.abc.AsyncIterable"). New in version 3.5.2. Deprecated since version 3.9: [`collections.abc.AsyncIterable`](collections.abc#collections.abc.AsyncIterable "collections.abc.AsyncIterable") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.AsyncIterator(AsyncIterable[T_co])` A generic version of [`collections.abc.AsyncIterator`](collections.abc#collections.abc.AsyncIterator "collections.abc.AsyncIterator"). New in version 3.5.2. Deprecated since version 3.9: [`collections.abc.AsyncIterator`](collections.abc#collections.abc.AsyncIterator "collections.abc.AsyncIterator") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.Awaitable(Generic[T_co])` A generic version of [`collections.abc.Awaitable`](collections.abc#collections.abc.Awaitable "collections.abc.Awaitable"). New in version 3.5.2. Deprecated since version 3.9: [`collections.abc.Awaitable`](collections.abc#collections.abc.Awaitable "collections.abc.Awaitable") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). #### Context manager types `class typing.ContextManager(Generic[T_co])` A generic version of [`contextlib.AbstractContextManager`](contextlib#contextlib.AbstractContextManager "contextlib.AbstractContextManager"). New in version 3.5.4. New in version 3.6.0. Deprecated since version 3.9: [`contextlib.AbstractContextManager`](contextlib#contextlib.AbstractContextManager "contextlib.AbstractContextManager") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). `class typing.AsyncContextManager(Generic[T_co])` A generic version of [`contextlib.AbstractAsyncContextManager`](contextlib#contextlib.AbstractAsyncContextManager "contextlib.AbstractAsyncContextManager"). New in version 3.5.4. New in version 3.6.2. Deprecated since version 3.9: [`contextlib.AbstractAsyncContextManager`](contextlib#contextlib.AbstractAsyncContextManager "contextlib.AbstractAsyncContextManager") now supports `[]`. See [**PEP 585**](https://www.python.org/dev/peps/pep-0585) and [Generic Alias Type](stdtypes#types-genericalias). ### Protocols These protocols are decorated with [`runtime_checkable()`](#typing.runtime_checkable "typing.runtime_checkable"). `class typing.SupportsAbs` An ABC with one abstract method `__abs__` that is covariant in its return type. `class typing.SupportsBytes` An ABC with one abstract method `__bytes__`. `class typing.SupportsComplex` An ABC with one abstract method `__complex__`. `class typing.SupportsFloat` An ABC with one abstract method `__float__`. `class typing.SupportsIndex` An ABC with one abstract method `__index__`. New in version 3.8. `class typing.SupportsInt` An ABC with one abstract method `__int__`. `class typing.SupportsRound` An ABC with one abstract method `__round__` that is covariant in its return type. ### Functions and decorators `typing.cast(typ, val)` Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible). `@typing.overload` The `@overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of `@overload`-decorated definitions must be followed by exactly one non-`@overload`-decorated definition (for the same function/method). The `@overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-`@overload`-decorated definition, while the latter is used at runtime but should be ignored by a type checker. At runtime, calling a `@overload`-decorated function directly will raise [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). An example of overload that gives a more precise type than can be expressed using a union or a type variable: ``` @overload def process(response: None) -> None: ... @overload def process(response: int) -> tuple[int, str]: ... @overload def process(response: bytes) -> str: ... def process(response): <actual implementation> ``` See [**PEP 484**](https://www.python.org/dev/peps/pep-0484) for details and comparison with other typing semantics. `@typing.final` A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example: ``` class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ... ``` There is no runtime checking of these properties. See [**PEP 591**](https://www.python.org/dev/peps/pep-0591) for more details. New in version 3.8. `@typing.no_type_check` Decorator to indicate that annotations are not type hints. This works as class or function [decorator](../glossary#term-decorator). With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the function(s) in place. `@typing.no_type_check_decorator` Decorator to give another decorator the [`no_type_check()`](#typing.no_type_check "typing.no_type_check") effect. This wraps the decorator with something that wraps the decorated function in [`no_type_check()`](#typing.no_type_check "typing.no_type_check"). `@typing.type_check_only` Decorator to mark a class or function to be unavailable at runtime. This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class: ``` @type_check_only class Response: # private or not available at runtime code: int def get_header(self, name: str) -> str: ... def fetch_response() -> Response: ... ``` Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public. ### Introspection helpers `typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)` Return a dictionary containing type hints for a function, method, module or class object. This is often the same as `obj.__annotations__`. In addition, forward references encoded as string literals are handled by evaluating them in `globals` and `locals` namespaces. If necessary, `Optional[t]` is added for function and method annotations if a default value equal to `None` is set. For a class `C`, return a dictionary constructed by merging all the `__annotations__` along `C.__mro__` in reverse order. The function recursively replaces all `Annotated[T, ...]` with `T`, unless `include_extras` is set to `True` (see [`Annotated`](#typing.Annotated "typing.Annotated") for more information). For example: ``` class Student(NamedTuple): name: Annotated[str, 'some marker'] get_type_hints(Student) == {'name': str} get_type_hints(Student, include_extras=False) == {'name': str} get_type_hints(Student, include_extras=True) == { 'name': Annotated[str, 'some marker'] } ``` Changed in version 3.9: Added `include_extras` parameter as part of [**PEP 593**](https://www.python.org/dev/peps/pep-0593). `typing.get_args(tp)` `typing.get_origin(tp)` Provide basic introspection for generic types and special typing forms. For a typing object of the form `X[Y, Z, ...]` these functions return `X` and `(Y, Z, ...)`. If `X` is a generic alias for a builtin or [`collections`](collections#module-collections "collections: Container datatypes") class, it gets normalized to the original class. If `X` is a [`Union`](#typing.Union "typing.Union") or [`Literal`](#typing.Literal "typing.Literal") contained in another generic type, the order of `(Y, Z, ...)` may be different from the order of the original arguments `[Y, Z, ...]` due to type caching. For unsupported objects return `None` and `()` correspondingly. Examples: ``` assert get_origin(Dict[str, int]) is dict assert get_args(Dict[int, str]) == (int, str) assert get_origin(Union[int, str]) is Union assert get_args(Union[int, str]) == (int, str) ``` New in version 3.8. `class typing.ForwardRef` A class used for internal typing representation of string forward references. For example, `List["SomeClass"]` is implicitly transformed into `List[ForwardRef("SomeClass")]`. This class should not be instantiated by a user, but may be used by introspection tools. Note [**PEP 585**](https://www.python.org/dev/peps/pep-0585) generic types such as `list["SomeClass"]` will not be implicitly transformed into `list[ForwardRef("SomeClass")]` and thus will not automatically resolve to `list[SomeClass]`. New in version 3.7.4. ### Constant `typing.TYPE_CHECKING` A special constant that is assumed to be `True` by 3rd party static type checkers. It is `False` at runtime. Usage: ``` if TYPE_CHECKING: import expensive_mod def fun(arg: 'expensive_mod.SomeType') -> None: local_var: expensive_mod.AnotherType = other_fun() ``` The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the `expensive_mod` reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes. Note If `from __future__ import annotations` is used, annotations are not evaluated at function definition time. Instead, they are stored as strings in `__annotations__`. This makes it unnecessary to use quotes around the annotation (see [**PEP 563**](https://www.python.org/dev/peps/pep-0563)). New in version 3.5.2.
programming_docs
python curses.panel — A panel stack extension for curses curses.panel — A panel stack extension for curses ================================================= Panels are windows with the added feature of depth, so they can be stacked on top of each other, and only the visible portions of each window will be displayed. Panels can be added, moved up or down in the stack, and removed. Functions --------- The module [`curses.panel`](#module-curses.panel "curses.panel: A panel stack extension that adds depth to curses windows.") defines the following functions: `curses.panel.bottom_panel()` Returns the bottom panel in the panel stack. `curses.panel.new_panel(win)` Returns a panel object, associating it with the given window *win*. Be aware that you need to keep the returned panel object referenced explicitly. If you don’t, the panel object is garbage collected and removed from the panel stack. `curses.panel.top_panel()` Returns the top panel in the panel stack. `curses.panel.update_panels()` Updates the virtual screen after changes in the panel stack. This does not call [`curses.doupdate()`](curses#curses.doupdate "curses.doupdate"), so you’ll have to do this yourself. Panel Objects ------------- Panel objects, as returned by [`new_panel()`](#curses.panel.new_panel "curses.panel.new_panel") above, are windows with a stacking order. There’s always a window associated with a panel which determines the content, while the panel methods are responsible for the window’s depth in the panel stack. Panel objects have the following methods: `Panel.above()` Returns the panel above the current panel. `Panel.below()` Returns the panel below the current panel. `Panel.bottom()` Push the panel to the bottom of the stack. `Panel.hidden()` Returns `True` if the panel is hidden (not visible), `False` otherwise. `Panel.hide()` Hide the panel. This does not delete the object, it just makes the window on screen invisible. `Panel.move(y, x)` Move the panel to the screen coordinates `(y, x)`. `Panel.replace(win)` Change the window associated with the panel to the window *win*. `Panel.set_userptr(obj)` Set the panel’s user pointer to *obj*. This is used to associate an arbitrary piece of data with the panel, and can be any Python object. `Panel.show()` Display the panel (which might have been hidden). `Panel.top()` Push panel to the top of the stack. `Panel.userptr()` Returns the user pointer for the panel. This might be any Python object. `Panel.window()` Returns the window object associated with the panel. python email.headerregistry: Custom Header Objects email.headerregistry: Custom Header Objects =========================================== **Source code:** [Lib/email/headerregistry.py](https://github.com/python/cpython/tree/3.9/Lib/email/headerregistry.py) New in version 3.6: [1](#id2) Headers are represented by customized subclasses of [`str`](stdtypes#str "str"). The particular class used to represent a given header is determined by the [`header_factory`](email.policy#email.policy.EmailPolicy.header_factory "email.policy.EmailPolicy.header_factory") of the [`policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") in effect when the headers are created. This section documents the particular `header_factory` implemented by the email package for handling [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) compliant email messages, which not only provides customized header objects for various header types, but also provides an extension mechanism for applications to add their own custom header types. When using any of the policy objects derived from [`EmailPolicy`](email.policy#email.policy.EmailPolicy "email.policy.EmailPolicy"), all headers are produced by [`HeaderRegistry`](#email.headerregistry.HeaderRegistry "email.headerregistry.HeaderRegistry") and have [`BaseHeader`](#email.headerregistry.BaseHeader "email.headerregistry.BaseHeader") as their last base class. Each header class has an additional base class that is determined by the type of the header. For example, many headers have the class [`UnstructuredHeader`](#email.headerregistry.UnstructuredHeader "email.headerregistry.UnstructuredHeader") as their other base class. The specialized second class for a header is determined by the name of the header, using a lookup table stored in the [`HeaderRegistry`](#email.headerregistry.HeaderRegistry "email.headerregistry.HeaderRegistry"). All of this is managed transparently for the typical application program, but interfaces are provided for modifying the default behavior for use by more complex applications. The sections below first document the header base classes and their attributes, followed by the API for modifying the behavior of [`HeaderRegistry`](#email.headerregistry.HeaderRegistry "email.headerregistry.HeaderRegistry"), and finally the support classes used to represent the data parsed from structured headers. `class email.headerregistry.BaseHeader(name, value)` *name* and *value* are passed to `BaseHeader` from the [`header_factory`](email.policy#email.policy.EmailPolicy.header_factory "email.policy.EmailPolicy.header_factory") call. The string value of any header object is the *value* fully decoded to unicode. This base class defines the following read-only properties: `name` The name of the header (the portion of the field before the ‘:’). This is exactly the value passed in the [`header_factory`](email.policy#email.policy.EmailPolicy.header_factory "email.policy.EmailPolicy.header_factory") call for *name*; that is, case is preserved. `defects` A tuple of `HeaderDefect` instances reporting any RFC compliance problems found during parsing. The email package tries to be complete about detecting compliance issues. See the [`errors`](email.errors#module-email.errors "email.errors: The exception classes used by the email package.") module for a discussion of the types of defects that may be reported. `max_count` The maximum number of headers of this type that can have the same `name`. A value of `None` means unlimited. The `BaseHeader` value for this attribute is `None`; it is expected that specialized header classes will override this value as needed. `BaseHeader` also provides the following method, which is called by the email library code and should not in general be called by application programs: `fold(*, policy)` Return a string containing [`linesep`](email.policy#email.policy.Policy.linesep "email.policy.Policy.linesep") characters as required to correctly fold the header according to *policy*. A [`cte_type`](email.policy#email.policy.Policy.cte_type "email.policy.Policy.cte_type") of `8bit` will be treated as if it were `7bit`, since headers may not contain arbitrary binary data. If [`utf8`](email.policy#email.policy.EmailPolicy.utf8 "email.policy.EmailPolicy.utf8") is `False`, non-ASCII data will be [**RFC 2047**](https://tools.ietf.org/html/rfc2047.html) encoded. `BaseHeader` by itself cannot be used to create a header object. It defines a protocol that each specialized header cooperates with in order to produce the header object. Specifically, `BaseHeader` requires that the specialized class provide a [`classmethod()`](functions#classmethod "classmethod") named `parse`. This method is called as follows: ``` parse(string, kwds) ``` `kwds` is a dictionary containing one pre-initialized key, `defects`. `defects` is an empty list. The parse method should append any detected defects to this list. On return, the `kwds` dictionary *must* contain values for at least the keys `decoded` and `defects`. `decoded` should be the string value for the header (that is, the header value fully decoded to unicode). The parse method should assume that *string* may contain content-transfer-encoded parts, but should correctly handle all valid unicode characters as well so that it can parse un-encoded header values. `BaseHeader`’s `__new__` then creates the header instance, and calls its `init` method. The specialized class only needs to provide an `init` method if it wishes to set additional attributes beyond those provided by `BaseHeader` itself. Such an `init` method should look like this: ``` def init(self, /, *args, **kw): self._myattr = kw.pop('myattr') super().init(*args, **kw) ``` That is, anything extra that the specialized class puts in to the `kwds` dictionary should be removed and handled, and the remaining contents of `kw` (and `args`) passed to the `BaseHeader` `init` method. `class email.headerregistry.UnstructuredHeader` An “unstructured” header is the default type of header in [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html). Any header that does not have a specified syntax is treated as unstructured. The classic example of an unstructured header is the *Subject* header. In [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html), an unstructured header is a run of arbitrary text in the ASCII character set. [**RFC 2047**](https://tools.ietf.org/html/rfc2047.html), however, has an [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) compatible mechanism for encoding non-ASCII text as ASCII characters within a header value. When a *value* containing encoded words is passed to the constructor, the `UnstructuredHeader` parser converts such encoded words into unicode, following the [**RFC 2047**](https://tools.ietf.org/html/rfc2047.html) rules for unstructured text. The parser uses heuristics to attempt to decode certain non-compliant encoded words. Defects are registered in such cases, as well as defects for issues such as invalid characters within the encoded words or the non-encoded text. This header type provides no additional attributes. `class email.headerregistry.DateHeader` [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) specifies a very specific format for dates within email headers. The `DateHeader` parser recognizes that date format, as well as recognizing a number of variant forms that are sometimes found “in the wild”. This header type provides the following additional attributes: `datetime` If the header value can be recognized as a valid date of one form or another, this attribute will contain a [`datetime`](datetime#datetime.datetime "datetime.datetime") instance representing that date. If the timezone of the input date is specified as `-0000` (indicating it is in UTC but contains no information about the source timezone), then [`datetime`](#email.headerregistry.DateHeader.datetime "email.headerregistry.DateHeader.datetime") will be a naive [`datetime`](datetime#datetime.datetime "datetime.datetime"). If a specific timezone offset is found (including `+0000`), then [`datetime`](#email.headerregistry.DateHeader.datetime "email.headerregistry.DateHeader.datetime") will contain an aware `datetime` that uses [`datetime.timezone`](datetime#datetime.timezone "datetime.timezone") to record the timezone offset. The `decoded` value of the header is determined by formatting the `datetime` according to the [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) rules; that is, it is set to: ``` email.utils.format_datetime(self.datetime) ``` When creating a `DateHeader`, *value* may be [`datetime`](datetime#datetime.datetime "datetime.datetime") instance. This means, for example, that the following code is valid and does what one would expect: ``` msg['Date'] = datetime(2011, 7, 15, 21) ``` Because this is a naive `datetime` it will be interpreted as a UTC timestamp, and the resulting value will have a timezone of `-0000`. Much more useful is to use the [`localtime()`](email.utils#email.utils.localtime "email.utils.localtime") function from the [`utils`](email.utils#module-email.utils "email.utils: Miscellaneous email package utilities.") module: ``` msg['Date'] = utils.localtime() ``` This example sets the date header to the current time and date using the current timezone offset. `class email.headerregistry.AddressHeader` Address headers are one of the most complex structured header types. The `AddressHeader` class provides a generic interface to any address header. This header type provides the following additional attributes: `groups` A tuple of [`Group`](#email.headerregistry.Group "email.headerregistry.Group") objects encoding the addresses and groups found in the header value. Addresses that are not part of a group are represented in this list as single-address `Groups` whose [`display_name`](#email.headerregistry.Group.display_name "email.headerregistry.Group.display_name") is `None`. `addresses` A tuple of [`Address`](#email.headerregistry.Address "email.headerregistry.Address") objects encoding all of the individual addresses from the header value. If the header value contains any groups, the individual addresses from the group are included in the list at the point where the group occurs in the value (that is, the list of addresses is “flattened” into a one dimensional list). The `decoded` value of the header will have all encoded words decoded to unicode. [`idna`](codecs#module-encodings.idna "encodings.idna: Internationalized Domain Names implementation") encoded domain names are also decoded to unicode. The `decoded` value is set by [`join`](stdtypes#str.join "str.join")ing the [`str`](stdtypes#str "str") value of the elements of the `groups` attribute with `', '`. A list of [`Address`](#email.headerregistry.Address "email.headerregistry.Address") and [`Group`](#email.headerregistry.Group "email.headerregistry.Group") objects in any combination may be used to set the value of an address header. `Group` objects whose `display_name` is `None` will be interpreted as single addresses, which allows an address list to be copied with groups intact by using the list obtained from the `groups` attribute of the source header. `class email.headerregistry.SingleAddressHeader` A subclass of [`AddressHeader`](#email.headerregistry.AddressHeader "email.headerregistry.AddressHeader") that adds one additional attribute: `address` The single address encoded by the header value. If the header value actually contains more than one address (which would be a violation of the RFC under the default [`policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages")), accessing this attribute will result in a [`ValueError`](exceptions#ValueError "ValueError"). Many of the above classes also have a `Unique` variant (for example, `UniqueUnstructuredHeader`). The only difference is that in the `Unique` variant, [`max_count`](#email.headerregistry.BaseHeader.max_count "email.headerregistry.BaseHeader.max_count") is set to 1. `class email.headerregistry.MIMEVersionHeader` There is really only one valid value for the *MIME-Version* header, and that is `1.0`. For future proofing, this header class supports other valid version numbers. If a version number has a valid value per [**RFC 2045**](https://tools.ietf.org/html/rfc2045.html), then the header object will have non-`None` values for the following attributes: `version` The version number as a string, with any whitespace and/or comments removed. `major` The major version number as an integer `minor` The minor version number as an integer `class email.headerregistry.ParameterizedMIMEHeader` MIME headers all start with the prefix ‘Content-’. Each specific header has a certain value, described under the class for that header. Some can also take a list of supplemental parameters, which have a common format. This class serves as a base for all the MIME headers that take parameters. `params` A dictionary mapping parameter names to parameter values. `class email.headerregistry.ContentTypeHeader` A [`ParameterizedMIMEHeader`](#email.headerregistry.ParameterizedMIMEHeader "email.headerregistry.ParameterizedMIMEHeader") class that handles the *Content-Type* header. `content_type` The content type string, in the form `maintype/subtype`. `maintype` `subtype` `class email.headerregistry.ContentDispositionHeader` A [`ParameterizedMIMEHeader`](#email.headerregistry.ParameterizedMIMEHeader "email.headerregistry.ParameterizedMIMEHeader") class that handles the *Content-Disposition* header. `content_disposition` `inline` and `attachment` are the only valid values in common use. `class email.headerregistry.ContentTransferEncoding` Handles the *Content-Transfer-Encoding* header. `cte` Valid values are `7bit`, `8bit`, `base64`, and `quoted-printable`. See [**RFC 2045**](https://tools.ietf.org/html/rfc2045.html) for more information. `class email.headerregistry.HeaderRegistry(base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)` This is the factory used by [`EmailPolicy`](email.policy#email.policy.EmailPolicy "email.policy.EmailPolicy") by default. `HeaderRegistry` builds the class used to create a header instance dynamically, using *base\_class* and a specialized class retrieved from a registry that it holds. When a given header name does not appear in the registry, the class specified by *default\_class* is used as the specialized class. When *use\_default\_map* is `True` (the default), the standard mapping of header names to classes is copied in to the registry during initialization. *base\_class* is always the last class in the generated class’s `__bases__` list. The default mappings are: subject UniqueUnstructuredHeader date UniqueDateHeader resent-date DateHeader orig-date UniqueDateHeader sender UniqueSingleAddressHeader resent-sender SingleAddressHeader to UniqueAddressHeader resent-to AddressHeader cc UniqueAddressHeader resent-cc AddressHeader bcc UniqueAddressHeader resent-bcc AddressHeader from UniqueAddressHeader resent-from AddressHeader reply-to UniqueAddressHeader mime-version MIMEVersionHeader content-type ContentTypeHeader content-disposition ContentDispositionHeader content-transfer-encoding ContentTransferEncodingHeader message-id MessageIDHeader `HeaderRegistry` has the following methods: `map_to_type(self, name, cls)` *name* is the name of the header to be mapped. It will be converted to lower case in the registry. *cls* is the specialized class to be used, along with *base\_class*, to create the class used to instantiate headers that match *name*. `__getitem__(name)` Construct and return a class to handle creating a *name* header. `__call__(name, value)` Retrieves the specialized header associated with *name* from the registry (using *default\_class* if *name* does not appear in the registry) and composes it with *base\_class* to produce a class, calls the constructed class’s constructor, passing it the same argument list, and finally returns the class instance created thereby. The following classes are the classes used to represent data parsed from structured headers and can, in general, be used by an application program to construct structured values to assign to specific headers. `class email.headerregistry.Address(display_name='', username='', domain='', addr_spec=None)` The class used to represent an email address. The general form of an address is: ``` [display_name] <username@domain> ``` or: ``` username@domain ``` where each part must conform to specific syntax rules spelled out in [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html). As a convenience *addr\_spec* can be specified instead of *username* and *domain*, in which case *username* and *domain* will be parsed from the *addr\_spec*. An *addr\_spec* must be a properly RFC quoted string; if it is not `Address` will raise an error. Unicode characters are allowed and will be property encoded when serialized. However, per the RFCs, unicode is *not* allowed in the username portion of the address. `display_name` The display name portion of the address, if any, with all quoting removed. If the address does not have a display name, this attribute will be an empty string. `username` The `username` portion of the address, with all quoting removed. `domain` The `domain` portion of the address. `addr_spec` The `username@domain` portion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable. `__str__()` The `str` value of the object is the address quoted according to [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) rules, but with no Content Transfer Encoding of any non-ASCII characters. To support SMTP ([**RFC 5321**](https://tools.ietf.org/html/rfc5321.html)), `Address` handles one special case: if `username` and `domain` are both the empty string (or `None`), then the string value of the `Address` is `<>`. `class email.headerregistry.Group(display_name=None, addresses=None)` The class used to represent an address group. The general form of an address group is: ``` display_name: [address-list]; ``` As a convenience for processing lists of addresses that consist of a mixture of groups and single addresses, a `Group` may also be used to represent single addresses that are not part of a group by setting *display\_name* to `None` and providing a list of the single address as *addresses*. `display_name` The `display_name` of the group. If it is `None` and there is exactly one `Address` in `addresses`, then the `Group` represents a single address that is not in a group. `addresses` A possibly empty tuple of [`Address`](#email.headerregistry.Address "email.headerregistry.Address") objects representing the addresses in the group. `__str__()` The `str` value of a `Group` is formatted according to [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html), but with no Content Transfer Encoding of any non-ASCII characters. If `display_name` is none and there is a single `Address` in the `addresses` list, the `str` value will be the same as the `str` of that single `Address`. #### Footnotes `1` Originally added in 3.3 as a [provisional module](../glossary#term-provisional-package)
programming_docs
python Data Persistence Data Persistence ================ The modules described in this chapter support storing Python data in a persistent form on disk. The [`pickle`](pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") and [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") modules can turn many Python data types into a stream of bytes and then recreate the objects from the bytes. The various DBM-related modules support a family of hash-based file formats that store a mapping of strings to other strings. The list of modules described in this chapter is: * [`pickle` — Python object serialization](pickle) + [Relationship to other Python modules](pickle#relationship-to-other-python-modules) - [Comparison with `marshal`](pickle#comparison-with-marshal) - [Comparison with `json`](pickle#comparison-with-json) + [Data stream format](pickle#data-stream-format) + [Module Interface](pickle#module-interface) + [What can be pickled and unpickled?](pickle#what-can-be-pickled-and-unpickled) + [Pickling Class Instances](pickle#pickling-class-instances) - [Persistence of External Objects](pickle#persistence-of-external-objects) - [Dispatch Tables](pickle#dispatch-tables) - [Handling Stateful Objects](pickle#handling-stateful-objects) + [Custom Reduction for Types, Functions, and Other Objects](pickle#custom-reduction-for-types-functions-and-other-objects) + [Out-of-band Buffers](pickle#out-of-band-buffers) - [Provider API](pickle#provider-api) - [Consumer API](pickle#consumer-api) - [Example](pickle#example) + [Restricting Globals](pickle#restricting-globals) + [Performance](pickle#performance) + [Examples](pickle#examples) * [`copyreg` — Register `pickle` support functions](copyreg) + [Example](copyreg#example) * [`shelve` — Python object persistence](shelve) + [Restrictions](shelve#restrictions) + [Example](shelve#example) * [`marshal` — Internal Python object serialization](marshal) * [`dbm` — Interfaces to Unix “databases”](dbm) + [`dbm.gnu` — GNU’s reinterpretation of dbm](dbm#module-dbm.gnu) + [`dbm.ndbm` — Interface based on ndbm](dbm#module-dbm.ndbm) + [`dbm.dumb` — Portable DBM implementation](dbm#module-dbm.dumb) * [`sqlite3` — DB-API 2.0 interface for SQLite databases](sqlite3) + [Module functions and constants](sqlite3#module-functions-and-constants) + [Connection Objects](sqlite3#connection-objects) + [Cursor Objects](sqlite3#cursor-objects) + [Row Objects](sqlite3#row-objects) + [Exceptions](sqlite3#exceptions) + [SQLite and Python types](sqlite3#sqlite-and-python-types) - [Introduction](sqlite3#introduction) - [Using adapters to store additional Python types in SQLite databases](sqlite3#using-adapters-to-store-additional-python-types-in-sqlite-databases) * [Letting your object adapt itself](sqlite3#letting-your-object-adapt-itself) * [Registering an adapter callable](sqlite3#registering-an-adapter-callable) - [Converting SQLite values to custom Python types](sqlite3#converting-sqlite-values-to-custom-python-types) - [Default adapters and converters](sqlite3#default-adapters-and-converters) + [Controlling Transactions](sqlite3#controlling-transactions) + [Using `sqlite3` efficiently](sqlite3#using-sqlite3-efficiently) - [Using shortcut methods](sqlite3#using-shortcut-methods) - [Accessing columns by name instead of by index](sqlite3#accessing-columns-by-name-instead-of-by-index) - [Using the connection as a context manager](sqlite3#using-the-connection-as-a-context-manager) python abc — Abstract Base Classes abc — Abstract Base Classes =========================== **Source code:** [Lib/abc.py](https://github.com/python/cpython/tree/3.9/Lib/abc.py) This module provides the infrastructure for defining [abstract base classes](../glossary#term-abstract-base-class) (ABCs) in Python, as outlined in [**PEP 3119**](https://www.python.org/dev/peps/pep-3119); see the PEP for why this was added to Python. (See also [**PEP 3141**](https://www.python.org/dev/peps/pep-3141) and the [`numbers`](numbers#module-numbers "numbers: Numeric abstract base classes (Complex, Real, Integral, etc.).") module regarding a type hierarchy for numbers based on ABCs.) The [`collections`](collections#module-collections "collections: Container datatypes") module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the [`collections.abc`](collections.abc#module-collections.abc "collections.abc: Abstract base classes for containers") submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping. This module provides the metaclass [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") for defining ABCs and a helper class [`ABC`](#abc.ABC "abc.ABC") to alternatively define ABCs through inheritance: `class abc.ABC` A helper class that has [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") as its metaclass. With this class, an abstract base class can be created by simply deriving from [`ABC`](#abc.ABC "abc.ABC") avoiding sometimes confusing metaclass usage, for example: ``` from abc import ABC class MyABC(ABC): pass ``` Note that the type of [`ABC`](#abc.ABC "abc.ABC") is still [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta"), therefore inheriting from [`ABC`](#abc.ABC "abc.ABC") requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. One may also define an abstract base class by passing the metaclass keyword and using [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") directly, for example: ``` from abc import ABCMeta class MyABC(metaclass=ABCMeta): pass ``` New in version 3.4. `class abc.ABCMeta` Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as “virtual subclasses” – these and their descendants will be considered subclasses of the registering ABC by the built-in [`issubclass()`](functions#issubclass "issubclass") function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via [`super()`](functions#super "super")). [1](#id2) Classes created with a metaclass of [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") have the following method: `register(subclass)` Register *subclass* as a “virtual subclass” of this ABC. For example: ``` from abc import ABC class MyABC(ABC): pass MyABC.register(tuple) assert issubclass(tuple, MyABC) assert isinstance((), MyABC) ``` Changed in version 3.3: Returns the registered subclass, to allow usage as a class decorator. Changed in version 3.4: To detect calls to [`register()`](#abc.ABCMeta.register "abc.ABCMeta.register"), you can use the [`get_cache_token()`](#abc.get_cache_token "abc.get_cache_token") function. You can also override this method in an abstract base class: `__subclasshook__(subclass)` (Must be defined as a class method.) Check whether *subclass* is considered a subclass of this ABC. This means that you can customize the behavior of `issubclass` further without the need to call [`register()`](#abc.ABCMeta.register "abc.ABCMeta.register") on every class you want to consider a subclass of the ABC. (This class method is called from the `__subclasscheck__()` method of the ABC.) This method should return `True`, `False` or `NotImplemented`. If it returns `True`, the *subclass* is considered a subclass of this ABC. If it returns `False`, the *subclass* is not considered a subclass of this ABC, even if it would normally be one. If it returns `NotImplemented`, the subclass check is continued with the usual mechanism. For a demonstration of these concepts, look at this example ABC definition: ``` class Foo: def __getitem__(self, index): ... def __len__(self): ... def get_iterator(self): return iter(self) class MyIterable(ABC): @abstractmethod def __iter__(self): while False: yield None def get_iterator(self): return self.__iter__() @classmethod def __subclasshook__(cls, C): if cls is MyIterable: if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented MyIterable.register(Foo) ``` The ABC `MyIterable` defines the standard iterable method, [`__iter__()`](stdtypes#iterator.__iter__ "iterator.__iter__"), as an abstract method. The implementation given here can still be called from subclasses. The `get_iterator()` method is also part of the `MyIterable` abstract base class, but it does not have to be overridden in non-abstract derived classes. The [`__subclasshook__()`](#abc.ABCMeta.__subclasshook__ "abc.ABCMeta.__subclasshook__") class method defined here says that any class that has an [`__iter__()`](stdtypes#iterator.__iter__ "iterator.__iter__") method in its [`__dict__`](stdtypes#object.__dict__ "object.__dict__") (or in that of one of its base classes, accessed via the [`__mro__`](stdtypes#class.__mro__ "class.__mro__") list) is considered a `MyIterable` too. Finally, the last line makes `Foo` a virtual subclass of `MyIterable`, even though it does not define an [`__iter__()`](stdtypes#iterator.__iter__ "iterator.__iter__") method (it uses the old-style iterable protocol, defined in terms of [`__len__()`](../reference/datamodel#object.__len__ "object.__len__") and [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__")). Note that this will not make `get_iterator` available as a method of `Foo`, so it is provided separately. The [`abc`](#module-abc "abc: Abstract base classes according to :pep:`3119`.") module also provides the following decorator: `@abc.abstractmethod` A decorator indicating abstract methods. Using this decorator requires that the class’s metaclass is [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") or is derived from it. A class that has a metaclass derived from [`ABCMeta`](#abc.ABCMeta "abc.ABCMeta") cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms. [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod") may be used to declare abstract methods for properties and descriptors. Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported. The [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod") only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s `register()` method are not affected. When [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod") is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples: ``` class C(ABC): @abstractmethod def my_abstract_method(self, arg1): ... @classmethod @abstractmethod def my_abstract_classmethod(cls, arg2): ... @staticmethod @abstractmethod def my_abstract_staticmethod(arg3): ... @property @abstractmethod def my_abstract_property(self): ... @my_abstract_property.setter @abstractmethod def my_abstract_property(self, val): ... @abstractmethod def _get_x(self): ... @abstractmethod def _set_x(self, val): ... x = property(_get_x, _set_x) ``` In order to correctly interoperate with the abstract base class machinery, the descriptor must identify itself as abstract using `__isabstractmethod__`. In general, this attribute should be `True` if any of the methods used to compose the descriptor are abstract. For example, Python’s built-in [`property`](functions#property "property") does the equivalent of: ``` class Descriptor: ... @property def __isabstractmethod__(self): return any(getattr(f, '__isabstractmethod__', False) for f in (self._fget, self._fset, self._fdel)) ``` Note Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the [`super()`](functions#super "super") mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance. The [`abc`](#module-abc "abc: Abstract base classes according to :pep:`3119`.") module also supports the following legacy decorators: `@abc.abstractclassmethod` New in version 3.2. Deprecated since version 3.3: It is now possible to use [`classmethod`](functions#classmethod "classmethod") with [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod"), making this decorator redundant. A subclass of the built-in [`classmethod()`](functions#classmethod "classmethod"), indicating an abstract classmethod. Otherwise it is similar to [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod"). This special case is deprecated, as the [`classmethod()`](functions#classmethod "classmethod") decorator is now correctly identified as abstract when applied to an abstract method: ``` class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, arg): ... ``` `@abc.abstractstaticmethod` New in version 3.2. Deprecated since version 3.3: It is now possible to use [`staticmethod`](functions#staticmethod "staticmethod") with [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod"), making this decorator redundant. A subclass of the built-in [`staticmethod()`](functions#staticmethod "staticmethod"), indicating an abstract staticmethod. Otherwise it is similar to [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod"). This special case is deprecated, as the [`staticmethod()`](functions#staticmethod "staticmethod") decorator is now correctly identified as abstract when applied to an abstract method: ``` class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(arg): ... ``` `@abc.abstractproperty` Deprecated since version 3.3: It is now possible to use [`property`](functions#property "property"), `property.getter()`, `property.setter()` and `property.deleter()` with [`abstractmethod()`](#abc.abstractmethod "abc.abstractmethod"), making this decorator redundant. A subclass of the built-in [`property()`](functions#property "property"), indicating an abstract property. This special case is deprecated, as the [`property()`](functions#property "property") decorator is now correctly identified as abstract when applied to an abstract method: ``` class C(ABC): @property @abstractmethod def my_abstract_property(self): ... ``` The above example defines a read-only property; you can also define a read-write abstract property by appropriately marking one or more of the underlying methods as abstract: ``` class C(ABC): @property def x(self): ... @x.setter @abstractmethod def x(self, val): ... ``` If only some components are abstract, only those components need to be updated to create a concrete property in a subclass: ``` class D(C): @C.x.setter def x(self, val): ... ``` The [`abc`](#module-abc "abc: Abstract base classes according to :pep:`3119`.") module also provides the following functions: `abc.get_cache_token()` Returns the current abstract base class cache token. The token is an opaque object (that supports equality testing) identifying the current version of the abstract base class cache for virtual subclasses. The token changes with every call to [`ABCMeta.register()`](#abc.ABCMeta.register "abc.ABCMeta.register") on any ABC. New in version 3.4. #### Footnotes `1` C++ programmers should note that Python’s virtual base class concept is not the same as C++’s. python contextlib — Utilities for with-statement contexts contextlib — Utilities for with-statement contexts ================================================== **Source code:** [Lib/contextlib.py](https://github.com/python/cpython/tree/3.9/Lib/contextlib.py) This module provides utilities for common tasks involving the [`with`](../reference/compound_stmts#with) statement. For more information see also [Context Manager Types](stdtypes#typecontextmanager) and [With Statement Context Managers](../reference/datamodel#context-managers). Utilities --------- Functions and classes provided: `class contextlib.AbstractContextManager` An [abstract base class](../glossary#term-abstract-base-class) for classes that implement [`object.__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") and [`object.__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__"). A default implementation for [`object.__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") is provided which returns `self` while [`object.__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") is an abstract method which by default returns `None`. See also the definition of [Context Manager Types](stdtypes#typecontextmanager). New in version 3.6. `class contextlib.AbstractAsyncContextManager` An [abstract base class](../glossary#term-abstract-base-class) for classes that implement [`object.__aenter__()`](../reference/datamodel#object.__aenter__ "object.__aenter__") and [`object.__aexit__()`](../reference/datamodel#object.__aexit__ "object.__aexit__"). A default implementation for [`object.__aenter__()`](../reference/datamodel#object.__aenter__ "object.__aenter__") is provided which returns `self` while [`object.__aexit__()`](../reference/datamodel#object.__aexit__ "object.__aexit__") is an abstract method which by default returns `None`. See also the definition of [Asynchronous Context Managers](../reference/datamodel#async-context-managers). New in version 3.7. `@contextlib.contextmanager` This function is a [decorator](../glossary#term-decorator) that can be used to define a factory function for [`with`](../reference/compound_stmts#with) statement context managers, without needing to create a class or separate [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") and [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") methods. While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a `close()` method for use with `contextlib.closing` An abstract example would be the following to ensure correct resource management: ``` from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): # Code to acquire resource, e.g.: resource = acquire_resource(*args, **kwds) try: yield resource finally: # Code to release resource, e.g.: release_resource(resource) >>> with managed_resource(timeout=3600) as resource: ... # Resource is released at the end of this block, ... # even if code in the block raises an exception ``` The function being decorated must return a [generator](../glossary#term-generator)-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the [`with`](../reference/compound_stmts#with) statement’s `as` clause, if any. At the point where the generator yields, the block nested in the [`with`](../reference/compound_stmts#with) statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a [`try`](../reference/compound_stmts#try)…[`except`](../reference/compound_stmts#except)…[`finally`](../reference/compound_stmts#finally) statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the `with` statement that the exception has been handled, and execution will resume with the statement immediately following the `with` statement. [`contextmanager()`](#contextlib.contextmanager "contextlib.contextmanager") uses [`ContextDecorator`](#contextlib.ContextDecorator "contextlib.ContextDecorator") so the context managers it creates can be used as decorators as well as in [`with`](../reference/compound_stmts#with) statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise “one-shot” context managers created by [`contextmanager()`](#contextlib.contextmanager "contextlib.contextmanager") to meet the requirement that context managers support multiple invocations in order to be used as decorators). Changed in version 3.2: Use of [`ContextDecorator`](#contextlib.ContextDecorator "contextlib.ContextDecorator"). `@contextlib.asynccontextmanager` Similar to [`contextmanager()`](#contextlib.contextmanager "contextlib.contextmanager"), but creates an [asynchronous context manager](../reference/datamodel#async-context-managers). This function is a [decorator](../glossary#term-decorator) that can be used to define a factory function for [`async with`](../reference/compound_stmts#async-with) statement asynchronous context managers, without needing to create a class or separate [`__aenter__()`](../reference/datamodel#object.__aenter__ "object.__aenter__") and [`__aexit__()`](../reference/datamodel#object.__aexit__ "object.__aexit__") methods. It must be applied to an [asynchronous generator](../glossary#term-asynchronous-generator) function. A simple example: ``` from contextlib import asynccontextmanager @asynccontextmanager async def get_connection(): conn = await acquire_db_connection() try: yield conn finally: await release_db_connection(conn) async def get_all_users(): async with get_connection() as conn: return conn.query('SELECT ...') ``` New in version 3.7. `contextlib.closing(thing)` Return a context manager that closes *thing* upon completion of the block. This is basically equivalent to: ``` from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close() ``` And lets you write code like this: ``` from contextlib import closing from urllib.request import urlopen with closing(urlopen('https://www.python.org')) as page: for line in page: print(line) ``` without needing to explicitly close `page`. Even if an error occurs, `page.close()` will be called when the [`with`](../reference/compound_stmts#with) block is exited. `contextlib.nullcontext(enter_result=None)` Return a context manager that returns *enter\_result* from `__enter__`, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example: ``` def myfunction(arg, ignore_exceptions=False): if ignore_exceptions: # Use suppress to ignore all exceptions. cm = contextlib.suppress(Exception) else: # Do not ignore any exceptions, cm has no effect. cm = contextlib.nullcontext() with cm: # Do something ``` An example using *enter\_result*: ``` def process_file(file_or_path): if isinstance(file_or_path, str): # If string, open file cm = open(file_or_path) else: # Caller is responsible for closing file cm = nullcontext(file_or_path) with cm as file: # Perform processing on the file ``` New in version 3.7. `contextlib.suppress(*exceptions)` Return a context manager that suppresses any of the specified exceptions if they occur in the body of a `with` statement and then resumes execution with the first statement following the end of the `with` statement. As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do. For example: ``` from contextlib import suppress with suppress(FileNotFoundError): os.remove('somefile.tmp') with suppress(FileNotFoundError): os.remove('someotherfile.tmp') ``` This code is equivalent to: ``` try: os.remove('somefile.tmp') except FileNotFoundError: pass try: os.remove('someotherfile.tmp') except FileNotFoundError: pass ``` This context manager is [reentrant](#reentrant-cms). New in version 3.4. `contextlib.redirect_stdout(new_target)` Context manager for temporarily redirecting [`sys.stdout`](sys#sys.stdout "sys.stdout") to another file or file-like object. This tool adds flexibility to existing functions or classes whose output is hardwired to stdout. For example, the output of [`help()`](functions#help "help") normally is sent to *sys.stdout*. You can capture that output in a string by redirecting the output to an [`io.StringIO`](io#io.StringIO "io.StringIO") object. The replacement stream is returned from the `__enter__` method and so is available as the target of the [`with`](../reference/compound_stmts#with) statement: ``` with redirect_stdout(io.StringIO()) as f: help(pow) s = f.getvalue() ``` To send the output of [`help()`](functions#help "help") to a file on disk, redirect the output to a regular file: ``` with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) ``` To send the output of [`help()`](functions#help "help") to *sys.stderr*: ``` with redirect_stdout(sys.stderr): help(pow) ``` Note that the global side effect on [`sys.stdout`](sys#sys.stdout "sys.stdout") means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts. This context manager is [reentrant](#reentrant-cms). New in version 3.4. `contextlib.redirect_stderr(new_target)` Similar to [`redirect_stdout()`](#contextlib.redirect_stdout "contextlib.redirect_stdout") but redirecting [`sys.stderr`](sys#sys.stderr "sys.stderr") to another file or file-like object. This context manager is [reentrant](#reentrant-cms). New in version 3.5. `class contextlib.ContextDecorator` A base class that enables a context manager to also be used as a decorator. Context managers inheriting from `ContextDecorator` have to implement `__enter__` and `__exit__` as normal. `__exit__` retains its optional exception handling even when used as a decorator. `ContextDecorator` is used by [`contextmanager()`](#contextlib.contextmanager "contextlib.contextmanager"), so you get this functionality automatically. Example of `ContextDecorator`: ``` from contextlib import ContextDecorator class mycontext(ContextDecorator): def __enter__(self): print('Starting') return self def __exit__(self, *exc): print('Finishing') return False >>> @mycontext() ... def function(): ... print('The bit in the middle') ... >>> function() Starting The bit in the middle Finishing >>> with mycontext(): ... print('The bit in the middle') ... Starting The bit in the middle Finishing ``` This change is just syntactic sugar for any construct of the following form: ``` def f(): with cm(): # Do stuff ``` `ContextDecorator` lets you instead write: ``` @cm() def f(): # Do stuff ``` It makes it clear that the `cm` applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). Existing context managers that already have a base class can be extended by using `ContextDecorator` as a mixin class: ``` from contextlib import ContextDecorator class mycontext(ContextBaseClass, ContextDecorator): def __enter__(self): return self def __exit__(self, *exc): return False ``` Note As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple [`with`](../reference/compound_stmts#with) statements. If this is not the case, then the original construct with the explicit `with` statement inside the function should be used. New in version 3.2. `class contextlib.ExitStack` A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data. For example, a set of files may easily be handled in a single with statement as follows: ``` with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception ``` The [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") method returns the [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") instance, and performs no additional operations. Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a [`with`](../reference/compound_stmts#with) statement). Note that callbacks are *not* invoked implicitly when the context stack instance is garbage collected. This stack model is used so that context managers that acquire their resources in their `__init__` method (such as file objects) can be handled correctly. Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested [`with`](../reference/compound_stmts#with) statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state. This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways. New in version 3.3. `enter_context(cm)` Enters a new context manager and adds its [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") method to the callback stack. The return value is the result of the context manager’s own [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") method. These context managers may suppress exceptions just as they normally would if used directly as part of a [`with`](../reference/compound_stmts#with) statement. `push(exit)` Adds a context manager’s [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") method to the callback stack. As `__enter__` is *not* invoked, this method can be used to cover part of an [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") implementation with a context manager’s own [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") method. If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") method and adds it directly to the callback stack. By returning true values, these callbacks can suppress exceptions the same way context manager [`__exit__()`](../reference/datamodel#object.__exit__ "object.__exit__") methods can. The passed in object is returned from the function, allowing this method to be used as a function decorator. `callback(callback, /, *args, **kwds)` Accepts an arbitrary callback function and arguments and adds it to the callback stack. Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). The passed in callback is returned from the function, allowing this method to be used as a function decorator. `pop_all()` Transfers the callback stack to a fresh [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a [`with`](../reference/compound_stmts#with) statement). For example, a group of files can be opened as an “all or nothing” operation as follows: ``` with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # Hold onto the close method, but don't call it yet. close_files = stack.pop_all().close # If opening any file fails, all previously opened files will be # closed automatically. If all files are opened successfully, # they will remain open even after the with statement ends. # close_files() can then be invoked explicitly to close them all. ``` `close()` Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred. `class contextlib.AsyncExitStack` An [asynchronous context manager](../reference/datamodel#async-context-managers), similar to [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack"), that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic. The `close()` method is not implemented, [`aclose()`](#contextlib.AsyncExitStack.aclose "contextlib.AsyncExitStack.aclose") must be used instead. `coroutine enter_async_context(cm)` Similar to `enter_context()` but expects an asynchronous context manager. `push_async_exit(exit)` Similar to `push()` but expects either an asynchronous context manager or a coroutine function. `push_async_callback(callback, /, *args, **kwds)` Similar to `callback()` but expects a coroutine function. `coroutine aclose()` Similar to `close()` but properly handles awaitables. Continuing the example for [`asynccontextmanager()`](#contextlib.asynccontextmanager "contextlib.asynccontextmanager"): ``` async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the end of # the async with statement, even if attempts to open a connection # later in the list raise an exception. ``` New in version 3.7. Examples and Recipes -------------------- This section describes some examples and recipes for making effective use of the tools provided by [`contextlib`](#module-contextlib "contextlib: Utilities for with-statement contexts."). ### Supporting a variable number of context managers The primary use case for [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single [`with`](../reference/compound_stmts#with) statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional: ``` with ExitStack() as stack: for resource in resources: stack.enter_context(resource) if need_special_resource(): special = acquire_special_resource() stack.callback(release_special_resource, special) # Perform operations that use the acquired resources ``` As shown, [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") also makes it quite easy to use [`with`](../reference/compound_stmts#with) statements to manage arbitrary resources that don’t natively support the context management protocol. ### Catching exceptions from `__enter__` methods It is occasionally desirable to catch exceptions from an `__enter__` method implementation, *without* inadvertently catching exceptions from the [`with`](../reference/compound_stmts#with) statement body or the context manager’s `__exit__` method. By using [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") the steps in the context management protocol can be separated slightly in order to allow this: ``` stack = ExitStack() try: x = stack.enter_context(cm) except Exception: # handle __enter__ exception else: with stack: # Handle normal case ``` Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with [`try`](../reference/compound_stmts#try)/[`except`](../reference/compound_stmts#except)/[`finally`](../reference/compound_stmts#finally) statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") can make it easier to handle various situations that can’t be handled directly in a [`with`](../reference/compound_stmts#with) statement. ### Cleaning up in an `__enter__` implementation As noted in the documentation of [`ExitStack.push()`](#contextlib.ExitStack.push "contextlib.ExitStack.push"), this method can be useful in cleaning up an already allocated resource if later steps in the [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__") implementation fail. Here’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol: ``` from contextlib import contextmanager, AbstractContextManager, ExitStack class ResourceManager(AbstractContextManager): def __init__(self, acquire_resource, release_resource, check_resource_ok=None): self.acquire_resource = acquire_resource self.release_resource = release_resource if check_resource_ok is None: def check_resource_ok(resource): return True self.check_resource_ok = check_resource_ok @contextmanager def _cleanup_on_error(self): with ExitStack() as stack: stack.push(self) yield # The validation check passed and didn't raise an exception # Accordingly, we want to keep the resource, and pass it # back to our caller stack.pop_all() def __enter__(self): resource = self.acquire_resource() with self._cleanup_on_error(): if not self.check_resource_ok(resource): msg = "Failed validation for {!r}" raise RuntimeError(msg.format(resource)) return resource def __exit__(self, *exc_details): # We don't need to duplicate any of our resource release logic self.release_resource() ``` ### Replacing any use of `try-finally` and flag variables A pattern you will sometimes see is a `try-finally` statement with a flag variable to indicate whether or not the body of the `finally` clause should be executed. In its simplest form (that can’t already be handled just by using an `except` clause instead), it looks something like this: ``` cleanup_needed = True try: result = perform_operation() if result: cleanup_needed = False finally: if cleanup_needed: cleanup_resources() ``` As with any `try` statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code. [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") makes it possible to instead register a callback for execution at the end of a `with` statement, and then later decide to skip executing that callback: ``` from contextlib import ExitStack with ExitStack() as stack: stack.callback(cleanup_resources) result = perform_operation() if result: stack.pop_all() ``` This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable. If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class: ``` from contextlib import ExitStack class Callback(ExitStack): def __init__(self, callback, /, *args, **kwds): super().__init__() self.callback(callback, *args, **kwds) def cancel(self): self.pop_all() with Callback(cleanup_resources) as cb: result = perform_operation() if result: cb.cancel() ``` If the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of [`ExitStack.callback()`](#contextlib.ExitStack.callback "contextlib.ExitStack.callback") to declare the resource cleanup in advance: ``` from contextlib import ExitStack with ExitStack() as stack: @stack.callback def cleanup_resources(): ... result = perform_operation() if result: stack.pop_all() ``` Due to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables. ### Using a context manager as a function decorator [`ContextDecorator`](#contextlib.ContextDecorator "contextlib.ContextDecorator") makes it possible to use a context manager in both an ordinary `with` statement and also as a function decorator. For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from [`ContextDecorator`](#contextlib.ContextDecorator "contextlib.ContextDecorator") provides both capabilities in a single definition: ``` from contextlib import ContextDecorator import logging logging.basicConfig(level=logging.INFO) class track_entry_and_exit(ContextDecorator): def __init__(self, name): self.name = name def __enter__(self): logging.info('Entering: %s', self.name) def __exit__(self, exc_type, exc, exc_tb): logging.info('Exiting: %s', self.name) ``` Instances of this class can be used as both a context manager: ``` with track_entry_and_exit('widget loader'): print('Some time consuming activity goes here') load_widget() ``` And also as a function decorator: ``` @track_entry_and_exit('widget loader') def activity(): print('Some time consuming activity goes here') load_widget() ``` Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of [`__enter__()`](../reference/datamodel#object.__enter__ "object.__enter__"). If that value is needed, then it is still necessary to use an explicit `with` statement. See also [**PEP 343**](https://www.python.org/dev/peps/pep-0343) - The “with” statement The specification, background, and examples for the Python [`with`](../reference/compound_stmts#with) statement. Single use, reusable and reentrant context managers --------------------------------------------------- Most context managers are written in a way that means they can only be used effectively in a [`with`](../reference/compound_stmts#with) statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly. This common limitation means that it is generally advisable to create context managers directly in the header of the [`with`](../reference/compound_stmts#with) statement where they are used (as shown in all of the usage examples above). Files are an example of effectively single use context managers, since the first [`with`](../reference/compound_stmts#with) statement will close the file, preventing any further IO operations using that file object. Context managers created using [`contextmanager()`](#contextlib.contextmanager "contextlib.contextmanager") are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time: ``` >>> from contextlib import contextmanager >>> @contextmanager ... def singleuse(): ... print("Before") ... yield ... print("After") ... >>> cm = singleuse() >>> with cm: ... pass ... Before After >>> with cm: ... pass ... Traceback (most recent call last): ... RuntimeError: generator didn't yield ``` ### Reentrant context managers More sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple [`with`](../reference/compound_stmts#with) statements, but may also be used *inside* a `with` statement that is already using the same context manager. [`threading.RLock`](threading#threading.RLock "threading.RLock") is an example of a reentrant context manager, as are [`suppress()`](#contextlib.suppress "contextlib.suppress") and [`redirect_stdout()`](#contextlib.redirect_stdout "contextlib.redirect_stdout"). Here’s a very simple example of reentrant use: ``` >>> from contextlib import redirect_stdout >>> from io import StringIO >>> stream = StringIO() >>> write_to_stream = redirect_stdout(stream) >>> with write_to_stream: ... print("This is written to the stream rather than stdout") ... with write_to_stream: ... print("This is also written to the stream") ... >>> print("This is written directly to stdout") This is written directly to stdout >>> print(stream.getvalue()) This is written to the stream rather than stdout This is also written to the stream ``` Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example. Note also that being reentrant is *not* the same thing as being thread safe. [`redirect_stdout()`](#contextlib.redirect_stdout "contextlib.redirect_stdout"), for example, is definitely not thread safe, as it makes a global modification to the system state by binding [`sys.stdout`](sys#sys.stdout "sys.stdout") to a different stream. ### Reusable context managers Distinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement. [`threading.Lock`](threading#threading.Lock "threading.Lock") is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use [`threading.RLock`](threading#threading.RLock "threading.RLock") instead). Another example of a reusable, but not reentrant, context manager is [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack"), as it invokes *all* currently registered callbacks when leaving any with statement, regardless of where those callbacks were added: ``` >>> from contextlib import ExitStack >>> stack = ExitStack() >>> with stack: ... stack.callback(print, "Callback: from first context") ... print("Leaving first context") ... Leaving first context Callback: from first context >>> with stack: ... stack.callback(print, "Callback: from second context") ... print("Leaving second context") ... Leaving second context Callback: from second context >>> with stack: ... stack.callback(print, "Callback: from outer context") ... with stack: ... stack.callback(print, "Callback: from inner context") ... print("Leaving inner context") ... print("Leaving outer context") ... Leaving inner context Callback: from inner context Callback: from outer context Leaving outer context ``` As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour. Using separate [`ExitStack`](#contextlib.ExitStack "contextlib.ExitStack") instances instead of reusing a single instance avoids that problem: ``` >>> from contextlib import ExitStack >>> with ExitStack() as outer_stack: ... outer_stack.callback(print, "Callback: from outer context") ... with ExitStack() as inner_stack: ... inner_stack.callback(print, "Callback: from inner context") ... print("Leaving inner context") ... print("Leaving outer context") ... Leaving inner context Callback: from inner context Leaving outer context Callback: from outer context ```
programming_docs
python xml.etree.ElementTree — The ElementTree XML API xml.etree.ElementTree — The ElementTree XML API =============================================== **Source code:** [Lib/xml/etree/ElementTree.py](https://github.com/python/cpython/tree/3.9/Lib/xml/etree/ElementTree.py) The [`xml.etree.ElementTree`](#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API.") module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available. Deprecated since version 3.3: The `xml.etree.cElementTree` module is deprecated. Warning The [`xml.etree.ElementTree`](#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API.") module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see [XML vulnerabilities](xml#xml-vulnerabilities). Tutorial -------- This is a short tutorial for using [`xml.etree.ElementTree`](#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API.") (`ET` in short). The goal is to demonstrate some of the building blocks and basic concepts of the module. ### XML tree and elements XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. `ET` has two classes for this purpose - [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") represents the whole XML document as a tree, and [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") level. Interactions with a single XML element and its sub-elements are done on the [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") level. ### Parsing XML We’ll be using the following XML document as the sample data for this section: ``` <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data> ``` We can import this data by reading from a file: ``` import xml.etree.ElementTree as ET tree = ET.parse('country_data.xml') root = tree.getroot() ``` Or directly from a string: ``` root = ET.fromstring(country_data_as_string) ``` [`fromstring()`](#xml.etree.ElementTree.fromstring "xml.etree.ElementTree.fromstring") parses XML from a string directly into an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element"), which is the root element of the parsed tree. Other parsing functions may create an [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree"). Check the documentation to be sure. As an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element"), `root` has a tag and a dictionary of attributes: ``` >>> root.tag 'data' >>> root.attrib {} ``` It also has children nodes over which we can iterate: ``` >>> for child in root: ... print(child.tag, child.attrib) ... country {'name': 'Liechtenstein'} country {'name': 'Singapore'} country {'name': 'Panama'} ``` Children are nested, and we can access specific child nodes by index: ``` >>> root[0][1].text '2008' ``` Note Not all elements of the XML input will end up as elements of the parsed tree. Currently, this module skips over any XML comments, processing instructions, and document type declarations in the input. Nevertheless, trees built using this module’s API rather than parsing from XML text can have comments and processing instructions in them; they will be included when generating XML output. A document type declaration may be accessed by passing a custom [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") instance to the [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") constructor. ### Pull API for non-blocking parsing Most parsing functions provided by this module require the whole document to be read at once before returning any result. It is possible to use an [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") and feed data into it incrementally, but it is a push API that calls methods on a callback target, which is too low-level and inconvenient for most needs. Sometimes what the user really wants is to be able to parse XML incrementally, without blocking operations, while enjoying the convenience of fully constructed [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") objects. The most powerful tool for doing this is [`XMLPullParser`](#xml.etree.ElementTree.XMLPullParser "xml.etree.ElementTree.XMLPullParser"). It does not require a blocking read to obtain the XML data, and is instead fed with data incrementally with [`XMLPullParser.feed()`](#xml.etree.ElementTree.XMLPullParser.feed "xml.etree.ElementTree.XMLPullParser.feed") calls. To get the parsed XML elements, call [`XMLPullParser.read_events()`](#xml.etree.ElementTree.XMLPullParser.read_events "xml.etree.ElementTree.XMLPullParser.read_events"). Here is an example: ``` >>> parser = ET.XMLPullParser(['start', 'end']) >>> parser.feed('<mytag>sometext') >>> list(parser.read_events()) [('start', <Element 'mytag' at 0x7fa66db2be58>)] >>> parser.feed(' more text</mytag>') >>> for event, elem in parser.read_events(): ... print(event) ... print(elem.tag, 'text=', elem.text) ... end ``` The obvious use case is applications that operate in a non-blocking fashion where the XML data is being received from a socket or read incrementally from some storage device. In such cases, blocking reads are unacceptable. Because it’s so flexible, [`XMLPullParser`](#xml.etree.ElementTree.XMLPullParser "xml.etree.ElementTree.XMLPullParser") can be inconvenient to use for simpler use-cases. If you don’t mind your application blocking on reading XML data but would still like to have incremental parsing capabilities, take a look at [`iterparse()`](#xml.etree.ElementTree.iterparse "xml.etree.ElementTree.iterparse"). It can be useful when you’re reading a large XML document and don’t want to hold it wholly in memory. ### Finding interesting elements [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on). For example, [`Element.iter()`](#xml.etree.ElementTree.Element.iter "xml.etree.ElementTree.Element.iter"): ``` >>> for neighbor in root.iter('neighbor'): ... print(neighbor.attrib) ... {'name': 'Austria', 'direction': 'E'} {'name': 'Switzerland', 'direction': 'W'} {'name': 'Malaysia', 'direction': 'N'} {'name': 'Costa Rica', 'direction': 'W'} {'name': 'Colombia', 'direction': 'E'} ``` [`Element.findall()`](#xml.etree.ElementTree.Element.findall "xml.etree.ElementTree.Element.findall") finds only elements with a tag which are direct children of the current element. [`Element.find()`](#xml.etree.ElementTree.Element.find "xml.etree.ElementTree.Element.find") finds the *first* child with a particular tag, and [`Element.text`](#xml.etree.ElementTree.Element.text "xml.etree.ElementTree.Element.text") accesses the element’s text content. [`Element.get()`](#xml.etree.ElementTree.Element.get "xml.etree.ElementTree.Element.get") accesses the element’s attributes: ``` >>> for country in root.findall('country'): ... rank = country.find('rank').text ... name = country.get('name') ... print(name, rank) ... Liechtenstein 1 Singapore 4 Panama 68 ``` More sophisticated specification of which elements to look for is possible by using [XPath](#elementtree-xpath). ### Modifying an XML File [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") provides a simple way to build XML documents and write them to files. The [`ElementTree.write()`](#xml.etree.ElementTree.ElementTree.write "xml.etree.ElementTree.ElementTree.write") method serves this purpose. Once created, an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") object may be manipulated by directly changing its fields (such as [`Element.text`](#xml.etree.ElementTree.Element.text "xml.etree.ElementTree.Element.text")), adding and modifying attributes ([`Element.set()`](#xml.etree.ElementTree.Element.set "xml.etree.ElementTree.Element.set") method), as well as adding new children (for example with [`Element.append()`](#xml.etree.ElementTree.Element.append "xml.etree.ElementTree.Element.append")). Let’s say we want to add one to each country’s rank, and add an `updated` attribute to the rank element: ``` >>> for rank in root.iter('rank'): ... new_rank = int(rank.text) + 1 ... rank.text = str(new_rank) ... rank.set('updated', 'yes') ... >>> tree.write('output.xml') ``` Our XML now looks like this: ``` <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data> ``` We can remove elements using [`Element.remove()`](#xml.etree.ElementTree.Element.remove "xml.etree.ElementTree.Element.remove"). Let’s say we want to remove all countries with a rank higher than 50: ``` >>> for country in root.findall('country'): ... # using root.findall() to avoid removal during traversal ... rank = int(country.find('rank').text) ... if rank > 50: ... root.remove(country) ... >>> tree.write('output.xml') ``` Note that concurrent modification while iterating can lead to problems, just like when iterating and modifying Python lists or dicts. Therefore, the example first collects all matching elements with `root.findall()`, and only then iterates over the list of matches. Our XML now looks like this: ``` <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> </data> ``` ### Building XML documents The [`SubElement()`](#xml.etree.ElementTree.SubElement "xml.etree.ElementTree.SubElement") function also provides a convenient way to create new sub-elements for a given element: ``` >>> a = ET.Element('a') >>> b = ET.SubElement(a, 'b') >>> c = ET.SubElement(a, 'c') >>> d = ET.SubElement(c, 'd') >>> ET.dump(a) <a><b /><c><d /></c></a> ``` ### Parsing XML with Namespaces If the XML input has [namespaces](https://en.wikipedia.org/wiki/XML_namespace), tags and attributes with prefixes in the form `prefix:sometag` get expanded to `{uri}sometag` where the *prefix* is replaced by the full *URI*. Also, if there is a [default namespace](https://www.w3.org/TR/xml-names/#defaulting), that full URI gets prepended to all of the non-prefixed tags. Here is an XML example that incorporates two namespaces, one with the prefix “fictional” and the other serving as the default namespace: ``` <?xml version="1.0"?> <actors xmlns:fictional="http://characters.example.com" xmlns="http://people.example.com"> <actor> <name>John Cleese</name> <fictional:character>Lancelot</fictional:character> <fictional:character>Archie Leach</fictional:character> </actor> <actor> <name>Eric Idle</name> <fictional:character>Sir Robin</fictional:character> <fictional:character>Gunther</fictional:character> <fictional:character>Commander Clement</fictional:character> </actor> </actors> ``` One way to search and explore this XML example is to manually add the URI to every tag or attribute in the xpath of a [`find()`](#xml.etree.ElementTree.Element.find "xml.etree.ElementTree.Element.find") or [`findall()`](#xml.etree.ElementTree.Element.findall "xml.etree.ElementTree.Element.findall"): ``` root = fromstring(xml_text) for actor in root.findall('{http://people.example.com}actor'): name = actor.find('{http://people.example.com}name') print(name.text) for char in actor.findall('{http://characters.example.com}character'): print(' |-->', char.text) ``` A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions: ``` ns = {'real_person': 'http://people.example.com', 'role': 'http://characters.example.com'} for actor in root.findall('real_person:actor', ns): name = actor.find('real_person:name', ns) print(name.text) for char in actor.findall('role:character', ns): print(' |-->', char.text) ``` These two approaches both output: ``` John Cleese |--> Lancelot |--> Archie Leach Eric Idle |--> Sir Robin |--> Gunther |--> Commander Clement ``` XPath support ------------- This module provides limited support for [XPath expressions](https://www.w3.org/TR/xpath) for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module. ### Example Here’s an example that demonstrates some of the XPath capabilities of the module. We’ll be using the `countrydata` XML document from the [Parsing XML](#elementtree-parsing-xml) section: ``` import xml.etree.ElementTree as ET root = ET.fromstring(countrydata) # Top-level elements root.findall(".") # All 'neighbor' grand-children of 'country' children of the top-level # elements root.findall("./country/neighbor") # Nodes with name='Singapore' that have a 'year' child root.findall(".//year/..[@name='Singapore']") # 'year' nodes that are children of nodes with name='Singapore' root.findall(".//*[@name='Singapore']/year") # All 'neighbor' nodes that are the second child of their parent root.findall(".//neighbor[2]") ``` For XML with namespaces, use the usual qualified `{namespace}tag` notation: ``` # All dublin-core "title" tags in the document root.findall(".//{http://purl.org/dc/elements/1.1/}title") ``` ### Supported XPath syntax | Syntax | Meaning | | --- | --- | | `tag` | Selects all child elements with the given tag. For example, `spam` selects all child elements named `spam`, and `spam/egg` selects all grandchildren named `egg` in all children named `spam`. `{namespace}*` selects all tags in the given namespace, `{*}spam` selects tags named `spam` in any (or no) namespace, and `{}*` only selects tags that are not in a namespace. Changed in version 3.8: Support for star-wildcards was added. | | `*` | Selects all child elements, including comments and processing instructions. For example, `*/egg` selects all grandchildren named `egg`. | | `.` | Selects the current node. This is mostly useful at the beginning of the path, to indicate that it’s a relative path. | | `//` | Selects all subelements, on all levels beneath the current element. For example, `.//egg` selects all `egg` elements in the entire tree. | | `..` | Selects the parent element. Returns `None` if the path attempts to reach the ancestors of the start element (the element `find` was called on). | | `[@attrib]` | Selects all elements that have the given attribute. | | `[@attrib='value']` | Selects all elements for which the given attribute has the given value. The value cannot contain quotes. | | `[tag]` | Selects all elements that have a child named `tag`. Only immediate children are supported. | | `[.='text']` | Selects all elements whose complete text content, including descendants, equals the given `text`. New in version 3.7. | | `[tag='text']` | Selects all elements that have a child named `tag` whose complete text content, including descendants, equals the given `text`. | | `[position]` | Selects all elements that are located at the given position. The position can be either an integer (1 is the first position), the expression `last()` (for the last position), or a position relative to the last position (e.g. `last()-1`). | Predicates (expressions within square brackets) must be preceded by a tag name, an asterisk, or another predicate. `position` predicates must be preceded by a tag name. Reference --------- ### Functions `xml.etree.ElementTree.canonicalize(xml_data=None, *, out=None, from_file=None, **options)` [C14N 2.0](https://www.w3.org/TR/xml-c14n2/) transformation function. Canonicalization is a way to normalise XML output in a way that allows byte-by-byte comparisons and digital signatures. It reduced the freedom that XML serializers have and instead generates a more constrained XML representation. The main restrictions regard the placement of namespace declarations, the ordering of attributes, and ignorable whitespace. This function takes an XML data string (*xml\_data*) or a file path or file-like object (*from\_file*) as input, converts it to the canonical form, and writes it out using the *out* file(-like) object, if provided, or returns it as a text string if not. The output file receives text, not bytes. It should therefore be opened in text mode with `utf-8` encoding. Typical uses: ``` xml_data = "<root>...</root>" print(canonicalize(xml_data)) with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: canonicalize(xml_data, out=out_file) with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: canonicalize(from_file="inputfile.xml", out=out_file) ``` The configuration *options* are as follows: * *with\_comments*: set to true to include comments (default: false) * *strip\_text*: set to true to strip whitespace before and after text content (default: false) * *rewrite\_prefixes*: set to true to replace namespace prefixes by “n{number}” (default: false) * *qname\_aware\_tags*: a set of qname aware tag names in which prefixes should be replaced in text content (default: empty) * *qname\_aware\_attrs*: a set of qname aware attribute names in which prefixes should be replaced in text content (default: empty) * *exclude\_attrs*: a set of attribute names that should not be serialised * *exclude\_tags*: a set of tag names that should not be serialised In the option list above, “a set” refers to any collection or iterable of strings, no ordering is expected. New in version 3.8. `xml.etree.ElementTree.Comment(text=None)` Comment element factory. This factory function creates a special element that will be serialized as an XML comment by the standard serializer. The comment string can be either a bytestring or a Unicode string. *text* is a string containing the comment string. Returns an element instance representing a comment. Note that [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") skips over comments in the input instead of creating comment objects for them. An [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") will only contain comment nodes if they have been inserted into to the tree using one of the [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") methods. `xml.etree.ElementTree.dump(elem)` Writes an element tree or element structure to sys.stdout. This function should be used for debugging only. The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file. *elem* is an element tree or an individual element. Changed in version 3.8: The [`dump()`](#xml.etree.ElementTree.dump "xml.etree.ElementTree.dump") function now preserves the attribute order specified by the user. `xml.etree.ElementTree.fromstring(text, parser=None)` Parses an XML section from a string constant. Same as [`XML()`](#xml.etree.ElementTree.XML "xml.etree.ElementTree.XML"). *text* is a string containing XML data. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. `xml.etree.ElementTree.fromstringlist(sequence, parser=None)` Parses an XML document from a sequence of string fragments. *sequence* is a list or other sequence containing XML data fragments. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. New in version 3.2. `xml.etree.ElementTree.indent(tree, space=" ", level=0)` Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. *tree* can be an Element or ElementTree. *space* is the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level as *level*. New in version 3.9. `xml.etree.ElementTree.iselement(element)` Check if an object appears to be a valid element object. *element* is an element instance. Return `True` if this is an element object. `xml.etree.ElementTree.iterparse(source, events=None, parser=None)` Parses an XML section into an element tree incrementally, and reports what’s going on to the user. *source* is a filename or [file object](../glossary#term-file-object) containing XML data. *events* is a sequence of events to report back. The supported events are the strings `"start"`, `"end"`, `"comment"`, `"pi"`, `"start-ns"` and `"end-ns"` (the “ns” events are used to get detailed namespace information). If *events* is omitted, only `"end"` events are reported. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. *parser* must be a subclass of [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") and can only use the default [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") as a target. Returns an [iterator](../glossary#term-iterator) providing `(event, elem)` pairs. Note that while [`iterparse()`](#xml.etree.ElementTree.iterparse "xml.etree.ElementTree.iterparse") builds the tree incrementally, it issues blocking reads on *source* (or the file it names). As such, it’s unsuitable for applications where blocking reads can’t be made. For fully non-blocking parsing, see [`XMLPullParser`](#xml.etree.ElementTree.XMLPullParser "xml.etree.ElementTree.XMLPullParser"). Note [`iterparse()`](#xml.etree.ElementTree.iterparse "xml.etree.ElementTree.iterparse") only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present. If you need a fully populated element, look for “end” events instead. Deprecated since version 3.4: The *parser* argument. Changed in version 3.8: The `comment` and `pi` events were added. `xml.etree.ElementTree.parse(source, parser=None)` Parses an XML section into an element tree. *source* is a filename or file object containing XML data. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns an [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") instance. `xml.etree.ElementTree.ProcessingInstruction(target, text=None)` PI element factory. This factory function creates a special element that will be serialized as an XML processing instruction. *target* is a string containing the PI target. *text* is a string containing the PI contents, if given. Returns an element instance, representing a processing instruction. Note that [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") skips over processing instructions in the input instead of creating comment objects for them. An [`ElementTree`](#xml.etree.ElementTree.ElementTree "xml.etree.ElementTree.ElementTree") will only contain processing instruction nodes if they have been inserted into to the tree using one of the [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") methods. `xml.etree.ElementTree.register_namespace(prefix, uri)` Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. *prefix* is a namespace prefix. *uri* is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible. New in version 3.2. `xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)` Subelement factory. This function creates an element instance, and appends it to an existing element. The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. *parent* is the parent element. *tag* is the subelement name. *attrib* is an optional dictionary, containing element attributes. *extra* contains additional attributes, given as keyword arguments. Returns an element instance. `xml.etree.ElementTree.tostring(element, encoding="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True)` Generates a string representation of an XML element, including all subelements. *element* is an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. *encoding* [1](#id9) is the output encoding (default is US-ASCII). Use `encoding="unicode"` to generate a Unicode string (otherwise, a bytestring is generated). *method* is either `"xml"`, `"html"` or `"text"` (default is `"xml"`). *xml\_declaration*, *default\_namespace* and *short\_empty\_elements* has the same meaning as in [`ElementTree.write()`](#xml.etree.ElementTree.ElementTree.write "xml.etree.ElementTree.ElementTree.write"). Returns an (optionally) encoded string containing the XML data. New in version 3.4: The *short\_empty\_elements* parameter. New in version 3.8: The *xml\_declaration* and *default\_namespace* parameters. Changed in version 3.8: The [`tostring()`](#xml.etree.ElementTree.tostring "xml.etree.ElementTree.tostring") function now preserves the attribute order specified by the user. `xml.etree.ElementTree.tostringlist(element, encoding="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True)` Generates a string representation of an XML element, including all subelements. *element* is an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. *encoding* [1](#id9) is the output encoding (default is US-ASCII). Use `encoding="unicode"` to generate a Unicode string (otherwise, a bytestring is generated). *method* is either `"xml"`, `"html"` or `"text"` (default is `"xml"`). *xml\_declaration*, *default\_namespace* and *short\_empty\_elements* has the same meaning as in [`ElementTree.write()`](#xml.etree.ElementTree.ElementTree.write "xml.etree.ElementTree.ElementTree.write"). Returns a list of (optionally) encoded strings containing the XML data. It does not guarantee any specific sequence, except that `b"".join(tostringlist(element)) == tostring(element)`. New in version 3.2. New in version 3.4: The *short\_empty\_elements* parameter. New in version 3.8: The *xml\_declaration* and *default\_namespace* parameters. Changed in version 3.8: The [`tostringlist()`](#xml.etree.ElementTree.tostringlist "xml.etree.ElementTree.tostringlist") function now preserves the attribute order specified by the user. `xml.etree.ElementTree.XML(text, parser=None)` Parses an XML section from a string constant. This function can be used to embed “XML literals” in Python code. *text* is a string containing XML data. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. `xml.etree.ElementTree.XMLID(text, parser=None)` Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. *text* is a string containing XML data. *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns a tuple containing an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance and a dictionary. XInclude support ---------------- This module provides limited support for [XInclude directives](https://www.w3.org/TR/xinclude/), via the `xml.etree.ElementInclude` helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree. ### Example Here’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the `{http://www.w3.org/2001/XInclude}include` element and set the **parse** attribute to `"xml"`, and use the **href** attribute to specify the document to include. ``` <?xml version="1.0"?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="source.xml" parse="xml" /> </document> ``` By default, the **href** attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax. To process this file, load it as usual, and pass the root element to the [`xml.etree.ElementTree`](#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API.") module: ``` from xml.etree import ElementTree, ElementInclude tree = ElementTree.parse("document.xml") root = tree.getroot() ElementInclude.include(root) ``` The ElementInclude module replaces the `{http://www.w3.org/2001/XInclude}include` element with the root element from the **source.xml** document. The result might look something like this: ``` <document xmlns:xi="http://www.w3.org/2001/XInclude"> <para>This is a paragraph.</para> </document> ``` If the **parse** attribute is omitted, it defaults to “xml”. The href attribute is required. To include a text document, use the `{http://www.w3.org/2001/XInclude}include` element, and set the **parse** attribute to “text”: ``` <?xml version="1.0"?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> Copyright (c) <xi:include href="year.txt" parse="text" />. </document> ``` The result might look something like: ``` <document xmlns:xi="http://www.w3.org/2001/XInclude"> Copyright (c) 2003. </document> ``` Reference --------- ### Functions `xml.etree.ElementInclude.default_loader(href, parse, encoding=None)` Default loader. This default loader reads an included resource from disk. *href* is a URL. *parse* is for parse mode either “xml” or “text”. *encoding* is an optional text encoding. If not given, encoding is `utf-8`. Returns the expanded resource. If the parse mode is `"xml"`, this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception. `xml.etree.ElementInclude.include(elem, loader=None, base_url=None, max_depth=6)` This function expands XInclude directives. *elem* is the root element. *loader* is an optional resource loader. If omitted, it defaults to [`default_loader()`](#xml.etree.ElementInclude.default_loader "xml.etree.ElementInclude.default_loader"). If given, it should be a callable that implements the same interface as [`default_loader()`](#xml.etree.ElementInclude.default_loader "xml.etree.ElementInclude.default_loader"). *base\_url* is base URL of the original file, to resolve relative include file references. *max\_depth* is the maximum number of recursive inclusions. Limited to reduce the risk of malicious content explosion. Pass a negative value to disable the limitation. Returns the expanded resource. If the parse mode is `"xml"`, this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception. New in version 3.9: The *base\_url* and *max\_depth* parameters. ### Element Objects `class xml.etree.ElementTree.Element(tag, attrib={}, **extra)` Element class. This class defines the Element interface, and provides a reference implementation of this interface. The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. *tag* is the element name. *attrib* is an optional dictionary, containing element attributes. *extra* contains additional attributes, given as keyword arguments. `tag` A string identifying what kind of data this element represents (the element type, in other words). `text` `tail` These attributes can be used to hold additional data associated with the element. Their values are usually strings but may be any application-specific object. If the element is created from an XML file, the *text* attribute holds either the text between the element’s start tag and its first child or end tag, or `None`, and the *tail* attribute holds either the text between the element’s end tag and the next tag, or `None`. For the XML data ``` <a><b>1<c>2<d/>3</c></b>4</a> ``` the *a* element has `None` for both *text* and *tail* attributes, the *b* element has *text* `"1"` and *tail* `"4"`, the *c* element has *text* `"2"` and *tail* `None`, and the *d* element has *text* `None` and *tail* `"3"`. To collect the inner text of an element, see [`itertext()`](#xml.etree.ElementTree.Element.itertext "xml.etree.ElementTree.Element.itertext"), for example `"".join(element.itertext())`. Applications may store arbitrary objects in these attributes. `attrib` A dictionary containing the element’s attributes. Note that while the *attrib* value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible. The following dictionary-like methods work on the element attributes. `clear()` Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to `None`. `get(key, default=None)` Gets the element attribute named *key*. Returns the attribute value, or *default* if the attribute was not found. `items()` Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order. `keys()` Returns the elements attribute names as a list. The names are returned in an arbitrary order. `set(key, value)` Set the attribute *key* on the element to *value*. The following methods work on the element’s children (subelements). `append(subelement)` Adds the element *subelement* to the end of this element’s internal list of subelements. Raises [`TypeError`](exceptions#TypeError "TypeError") if *subelement* is not an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element"). `extend(subelements)` Appends *subelements* from a sequence object with zero or more elements. Raises [`TypeError`](exceptions#TypeError "TypeError") if a subelement is not an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element"). New in version 3.2. `find(match, namespaces=None)` Finds the first subelement matching *match*. *match* may be a tag name or a [path](#elementtree-xpath). Returns an element instance or `None`. *namespaces* is an optional mapping from namespace prefix to full name. Pass `''` as prefix to move all unprefixed tag names in the expression into the given namespace. `findall(match, namespaces=None)` Finds all matching subelements, by tag name or [path](#elementtree-xpath). Returns a list containing all matching elements in document order. *namespaces* is an optional mapping from namespace prefix to full name. Pass `''` as prefix to move all unprefixed tag names in the expression into the given namespace. `findtext(match, default=None, namespaces=None)` Finds text for the first subelement matching *match*. *match* may be a tag name or a [path](#elementtree-xpath). Returns the text content of the first matching element, or *default* if no element was found. Note that if the matching element has no text content an empty string is returned. *namespaces* is an optional mapping from namespace prefix to full name. Pass `''` as prefix to move all unprefixed tag names in the expression into the given namespace. `insert(index, subelement)` Inserts *subelement* at the given position in this element. Raises [`TypeError`](exceptions#TypeError "TypeError") if *subelement* is not an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element"). `iter(tag=None)` Creates a tree [iterator](../glossary#term-iterator) with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If *tag* is not `None` or `'*'`, only elements whose tag equals *tag* are returned from the iterator. If the tree structure is modified during iteration, the result is undefined. New in version 3.2. `iterfind(match, namespaces=None)` Finds all matching subelements, by tag name or [path](#elementtree-xpath). Returns an iterable yielding all matching elements in document order. *namespaces* is an optional mapping from namespace prefix to full name. New in version 3.2. `itertext()` Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text. New in version 3.2. `makeelement(tag, attrib)` Creates a new element object of the same type as this element. Do not call this method, use the [`SubElement()`](#xml.etree.ElementTree.SubElement "xml.etree.ElementTree.SubElement") factory function instead. `remove(subelement)` Removes *subelement* from the element. Unlike the find\* methods this method compares elements based on the instance identity, not on tag value or contents. [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") objects also support the following sequence type methods for working with subelements: [`__delitem__()`](../reference/datamodel#object.__delitem__ "object.__delitem__"), [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__"), [`__setitem__()`](../reference/datamodel#object.__setitem__ "object.__setitem__"), [`__len__()`](../reference/datamodel#object.__len__ "object.__len__"). Caution: Elements with no subelements will test as `False`. This behavior will change in future versions. Use specific `len(elem)` or `elem is None` test instead. ``` element = root.find('foo') if not element: # careful! print("element not found, or element has no subelements") if element is None: print("element not found") ``` Prior to Python 3.8, the serialisation order of the XML attributes of elements was artificially made predictable by sorting the attributes by their name. Based on the now guaranteed ordering of dicts, this arbitrary reordering was removed in Python 3.8 to preserve the order in which attributes were originally parsed or created by user code. In general, user code should try not to depend on a specific ordering of attributes, given that the [XML Information Set](https://www.w3.org/TR/xml-infoset/) explicitly excludes the attribute order from conveying information. Code should be prepared to deal with any ordering on input. In cases where deterministic XML output is required, e.g. for cryptographic signing or test data sets, canonical serialisation is available with the [`canonicalize()`](#xml.etree.ElementTree.canonicalize "xml.etree.ElementTree.canonicalize") function. In cases where canonical output is not applicable but a specific attribute order is still desirable on output, code should aim for creating the attributes directly in the desired order, to avoid perceptual mismatches for readers of the code. In cases where this is difficult to achieve, a recipe like the following can be applied prior to serialisation to enforce an order independently from the Element creation: ``` def reorder_attributes(root): for el in root.iter(): attrib = el.attrib if len(attrib) > 1: # adjust attribute order, e.g. by sorting attribs = sorted(attrib.items()) attrib.clear() attrib.update(attribs) ``` ### ElementTree Objects `class xml.etree.ElementTree.ElementTree(element=None, file=None)` ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML. *element* is the root element. The tree is initialized with the contents of the XML *file* if given. `_setroot(element)` Replaces the root element for this tree. This discards the current contents of the tree, and replaces it with the given element. Use with care. *element* is an element instance. `find(match, namespaces=None)` Same as [`Element.find()`](#xml.etree.ElementTree.Element.find "xml.etree.ElementTree.Element.find"), starting at the root of the tree. `findall(match, namespaces=None)` Same as [`Element.findall()`](#xml.etree.ElementTree.Element.findall "xml.etree.ElementTree.Element.findall"), starting at the root of the tree. `findtext(match, default=None, namespaces=None)` Same as [`Element.findtext()`](#xml.etree.ElementTree.Element.findtext "xml.etree.ElementTree.Element.findtext"), starting at the root of the tree. `getroot()` Returns the root element for this tree. `iter(tag=None)` Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. *tag* is the tag to look for (default is to return all elements). `iterfind(match, namespaces=None)` Same as [`Element.iterfind()`](#xml.etree.ElementTree.Element.iterfind "xml.etree.ElementTree.Element.iterfind"), starting at the root of the tree. New in version 3.2. `parse(source, parser=None)` Loads an external XML section into this element tree. *source* is a file name or [file object](../glossary#term-file-object). *parser* is an optional parser instance. If not given, the standard [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") parser is used. Returns the section root element. `write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml", *, short_empty_elements=True)` Writes the element tree to a file, as XML. *file* is a file name, or a [file object](../glossary#term-file-object) opened for writing. *encoding* [1](#id9) is the output encoding (default is US-ASCII). *xml\_declaration* controls if an XML declaration should be added to the file. Use `False` for never, `True` for always, `None` for only if not US-ASCII or UTF-8 or Unicode (default is `None`). *default\_namespace* sets the default XML namespace (for “xmlns”). *method* is either `"xml"`, `"html"` or `"text"` (default is `"xml"`). The keyword-only *short\_empty\_elements* parameter controls the formatting of elements that contain no content. If `True` (the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags. The output is either a string ([`str`](stdtypes#str "str")) or binary ([`bytes`](stdtypes#bytes "bytes")). This is controlled by the *encoding* argument. If *encoding* is `"unicode"`, the output is a string; otherwise, it’s binary. Note that this may conflict with the type of *file* if it’s an open [file object](../glossary#term-file-object); make sure you do not try to write a string to a binary stream and vice versa. New in version 3.4: The *short\_empty\_elements* parameter. Changed in version 3.8: The [`write()`](#xml.etree.ElementTree.ElementTree.write "xml.etree.ElementTree.ElementTree.write") method now preserves the attribute order specified by the user. This is the XML file that is going to be manipulated: ``` <html> <head> <title>Example page</title> </head> <body> <p>Moved to <a href="http://example.org/">example.org</a> or <a href="http://example.com/">example.com</a>.</p> </body> </html> ``` Example of changing the attribute “target” of every link in first paragraph: ``` >>> from xml.etree.ElementTree import ElementTree >>> tree = ElementTree() >>> tree.parse("index.xhtml") <Element 'html' at 0xb77e6fac> >>> p = tree.find("body/p") # Finds first occurrence of tag p in body >>> p <Element 'p' at 0xb77ec26c> >>> links = list(p.iter("a")) # Returns list of all links >>> links [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>] >>> for i in links: # Iterates through all found links ... i.attrib["target"] = "blank" >>> tree.write("output.xhtml") ``` ### QName Objects `class xml.etree.ElementTree.QName(text_or_uri, tag=None)` QName wrapper. This can be used to wrap a QName attribute value, in order to get proper namespace handling on output. *text\_or\_uri* is a string containing the QName value, in the form {uri}local, or, if the tag argument is given, the URI part of a QName. If *tag* is given, the first argument is interpreted as a URI, and this argument is interpreted as a local name. [`QName`](#xml.etree.ElementTree.QName "xml.etree.ElementTree.QName") instances are opaque. ### TreeBuilder Objects `class xml.etree.ElementTree.TreeBuilder(element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)` Generic element structure builder. This builder converts a sequence of start, data, end, comment and pi method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format. *element\_factory*, when given, must be a callable accepting two positional arguments: a tag and a dict of attributes. It is expected to return a new element instance. The *comment\_factory* and *pi\_factory* functions, when given, should behave like the [`Comment()`](#xml.etree.ElementTree.Comment "xml.etree.ElementTree.Comment") and [`ProcessingInstruction()`](#xml.etree.ElementTree.ProcessingInstruction "xml.etree.ElementTree.ProcessingInstruction") functions to create comments and processing instructions. When not given, the default factories will be used. When *insert\_comments* and/or *insert\_pis* is true, comments/pis will be inserted into the tree if they appear within the root element (but not outside of it). `close()` Flushes the builder buffers, and returns the toplevel document element. Returns an [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") instance. `data(data)` Adds text to the current element. *data* is a string. This should be either a bytestring, or a Unicode string. `end(tag)` Closes the current element. *tag* is the element name. Returns the closed element. `start(tag, attrs)` Opens a new element. *tag* is the element name. *attrs* is a dictionary containing element attributes. Returns the opened element. `comment(text)` Creates a comment with the given *text*. If `insert_comments` is true, this will also add it to the tree. New in version 3.8. `pi(target, text)` Creates a comment with the given *target* name and *text*. If `insert_pis` is true, this will also add it to the tree. New in version 3.8. In addition, a custom [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") object can provide the following methods: `doctype(name, pubid, system)` Handles a doctype declaration. *name* is the doctype name. *pubid* is the public identifier. *system* is the system identifier. This method does not exist on the default [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") class. New in version 3.2. `start_ns(prefix, uri)` Is called whenever the parser encounters a new namespace declaration, before the `start()` callback for the opening element that defines it. *prefix* is `''` for the default namespace and the declared namespace prefix name otherwise. *uri* is the namespace URI. New in version 3.8. `end_ns(prefix)` Is called after the `end()` callback of an element that declared a namespace prefix mapping, with the name of the *prefix* that went out of scope. New in version 3.8. `class xml.etree.ElementTree.C14NWriterTarget(write, *, with_comments=False, strip_text=False, rewrite_prefixes=False, qname_aware_tags=None, qname_aware_attrs=None, exclude_attrs=None, exclude_tags=None)` A [C14N 2.0](https://www.w3.org/TR/xml-c14n2/) writer. Arguments are the same as for the [`canonicalize()`](#xml.etree.ElementTree.canonicalize "xml.etree.ElementTree.canonicalize") function. This class does not build a tree but translates the callback events directly into a serialised form using the *write* function. New in version 3.8. ### XMLParser Objects `class xml.etree.ElementTree.XMLParser(*, target=None, encoding=None)` This class is the low-level building block of the module. It uses [`xml.parsers.expat`](pyexpat#module-xml.parsers.expat "xml.parsers.expat: An interface to the Expat non-validating XML parser.") for efficient, event-based parsing of XML. It can be fed XML data incrementally with the [`feed()`](#xml.etree.ElementTree.XMLParser.feed "xml.etree.ElementTree.XMLParser.feed") method, and parsing events are translated to a push API - by invoking callbacks on the *target* object. If *target* is omitted, the standard [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") is used. If *encoding* [1](#id9) is given, the value overrides the encoding specified in the XML file. Changed in version 3.8: Parameters are now [keyword-only](../glossary#keyword-only-parameter). The *html* argument no longer supported. `close()` Finishes feeding data to the parser. Returns the result of calling the `close()` method of the *target* passed during construction; by default, this is the toplevel document element. `feed(data)` Feeds data to the parser. *data* is encoded data. [`XMLParser.feed()`](#xml.etree.ElementTree.XMLParser.feed "xml.etree.ElementTree.XMLParser.feed") calls *target*’s `start(tag, attrs_dict)` method for each opening tag, its `end(tag)` method for each closing tag, and data is processed by method `data(data)`. For further supported callback methods, see the [`TreeBuilder`](#xml.etree.ElementTree.TreeBuilder "xml.etree.ElementTree.TreeBuilder") class. [`XMLParser.close()`](#xml.etree.ElementTree.XMLParser.close "xml.etree.ElementTree.XMLParser.close") calls *target*’s method `close()`. [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser") can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file: ``` >>> from xml.etree.ElementTree import XMLParser >>> class MaxDepth: # The target object of the parser ... maxDepth = 0 ... depth = 0 ... def start(self, tag, attrib): # Called for each opening tag. ... self.depth += 1 ... if self.depth > self.maxDepth: ... self.maxDepth = self.depth ... def end(self, tag): # Called for each closing tag. ... self.depth -= 1 ... def data(self, data): ... pass # We do not need to do anything with data. ... def close(self): # Called when all data has been parsed. ... return self.maxDepth ... >>> target = MaxDepth() >>> parser = XMLParser(target=target) >>> exampleXml = """ ... <a> ... <b> ... </b> ... <b> ... <c> ... <d> ... </d> ... </c> ... </b> ... </a>""" >>> parser.feed(exampleXml) >>> parser.close() 4 ``` ### XMLPullParser Objects `class xml.etree.ElementTree.XMLPullParser(events=None)` A pull parser suitable for non-blocking applications. Its input-side API is similar to that of [`XMLParser`](#xml.etree.ElementTree.XMLParser "xml.etree.ElementTree.XMLParser"), but instead of pushing calls to a callback target, [`XMLPullParser`](#xml.etree.ElementTree.XMLPullParser "xml.etree.ElementTree.XMLPullParser") collects an internal list of parsing events and lets the user read from it. *events* is a sequence of events to report back. The supported events are the strings `"start"`, `"end"`, `"comment"`, `"pi"`, `"start-ns"` and `"end-ns"` (the “ns” events are used to get detailed namespace information). If *events* is omitted, only `"end"` events are reported. `feed(data)` Feed the given bytes data to the parser. `close()` Signal the parser that the data stream is terminated. Unlike [`XMLParser.close()`](#xml.etree.ElementTree.XMLParser.close "xml.etree.ElementTree.XMLParser.close"), this method always returns [`None`](constants#None "None"). Any events not yet retrieved when the parser is closed can still be read with [`read_events()`](#xml.etree.ElementTree.XMLPullParser.read_events "xml.etree.ElementTree.XMLPullParser.read_events"). `read_events()` Return an iterator over the events which have been encountered in the data fed to the parser. The iterator yields `(event, elem)` pairs, where *event* is a string representing the type of event (e.g. `"end"`) and *elem* is the encountered [`Element`](#xml.etree.ElementTree.Element "xml.etree.ElementTree.Element") object, or other context value as follows. * `start`, `end`: the current Element. * `comment`, `pi`: the current comment / processing instruction * `start-ns`: a tuple `(prefix, uri)` naming the declared namespace mapping. * `end-ns`: [`None`](constants#None "None") (this may change in a future version) Events provided in a previous call to [`read_events()`](#xml.etree.ElementTree.XMLPullParser.read_events "xml.etree.ElementTree.XMLPullParser.read_events") will not be yielded again. Events are consumed from the internal queue only when they are retrieved from the iterator, so multiple readers iterating in parallel over iterators obtained from [`read_events()`](#xml.etree.ElementTree.XMLPullParser.read_events "xml.etree.ElementTree.XMLPullParser.read_events") will have unpredictable results. Note [`XMLPullParser`](#xml.etree.ElementTree.XMLPullParser "xml.etree.ElementTree.XMLPullParser") only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present. If you need a fully populated element, look for “end” events instead. New in version 3.4. Changed in version 3.8: The `comment` and `pi` events were added. ### Exceptions `class xml.etree.ElementTree.ParseError` XML parse error, raised by the various parsing methods in this module when parsing fails. The string representation of an instance of this exception will contain a user-friendly error message. In addition, it will have the following attributes available: `code` A numeric error code from the expat parser. See the documentation of [`xml.parsers.expat`](pyexpat#module-xml.parsers.expat "xml.parsers.expat: An interface to the Expat non-validating XML parser.") for the list of error codes and their meanings. `position` A tuple of *line*, *column* numbers, specifying where the error occurred. #### Footnotes `1(1,2,3,4)` The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See <https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl> and <https://www.iana.org/assignments/character-sets/character-sets.xhtml>.
programming_docs
python dataclasses — Data Classes dataclasses — Data Classes ========================== **Source code:** [Lib/dataclasses.py](https://github.com/python/cpython/tree/3.9/Lib/dataclasses.py) This module provides a decorator and functions for automatically adding generated [special method](../glossary#term-special-method)s such as [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") and [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__") to user-defined classes. It was originally described in [**PEP 557**](https://www.python.org/dev/peps/pep-0557). The member variables to use in these generated methods are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations. For example, this code: ``` from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost(self) -> float: return self.unit_price * self.quantity_on_hand ``` will add, among other things, a [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") that looks like: ``` def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0): self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand ``` Note that this method is automatically added to the class: it is not directly specified in the `InventoryItem` definition shown above. New in version 3.7. Module-level decorators, classes, and functions ----------------------------------------------- `@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)` This function is a [decorator](../glossary#term-decorator) that is used to add generated [special method](../glossary#term-special-method)s to classes, as described below. The [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator examines the class to find `field`s. A `field` is defined as a class variable that has a [type annotation](../glossary#term-variable-annotation). With two exceptions described below, nothing in [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") examines the type specified in the variable annotation. The order of the fields in all of the generated methods is the order in which they appear in the class definition. The [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created. If [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") are equivalent: ``` @dataclass class C: ... @dataclass() class C: ... @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) class C: ... ``` The parameters to [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") are: * `init`: If true (the default), a [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method will be generated. If the class already defines [`__init__()`](../reference/datamodel#object.__init__ "object.__init__"), this parameter is ignored. * `repr`: If true (the default), a [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__") method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: `InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)`. If the class already defines [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__"), this parameter is ignored. * `eq`: If true (the default), an [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__") method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If the class already defines [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__"), this parameter is ignored. * `order`: If true (the default is `False`), [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__"), [`__le__()`](../reference/datamodel#object.__le__ "object.__le__"), [`__gt__()`](../reference/datamodel#object.__gt__ "object.__gt__"), and [`__ge__()`](../reference/datamodel#object.__ge__ "object.__ge__") methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If `order` is true and `eq` is false, a [`ValueError`](exceptions#ValueError "ValueError") is raised. If the class already defines any of [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__"), [`__le__()`](../reference/datamodel#object.__le__ "object.__le__"), [`__gt__()`](../reference/datamodel#object.__gt__ "object.__gt__"), or [`__ge__()`](../reference/datamodel#object.__ge__ "object.__ge__"), then [`TypeError`](exceptions#TypeError "TypeError") is raised. * `unsafe_hash`: If `False` (the default), a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method is generated according to how `eq` and `frozen` are set. [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") is used by built-in [`hash()`](functions#hash "hash"), and when objects are added to hashed collections such as dictionaries and sets. Having a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of [`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__"), and the values of the `eq` and `frozen` flags in the [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator. By default, [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") will not implicitly add a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method unless it is safe to do so. Neither will it add or change an existing explicitly defined [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method. Setting the class attribute `__hash__ = None` has a specific meaning to Python, as described in the [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") documentation. If [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") is not explicitly defined, or if it is set to `None`, then [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") *may* add an implicit [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method. Although not recommended, you can force [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") to create a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method with `unsafe_hash=True`. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully. Here are the rules governing implicit creation of a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method. Note that you cannot both have an explicit [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method in your dataclass and set `unsafe_hash=True`; this will result in a [`TypeError`](exceptions#TypeError "TypeError"). If `eq` and `frozen` are both true, by default [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") will generate a [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method for you. If `eq` is true and `frozen` is false, [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") will be set to `None`, marking it unhashable (which it is, since it is mutable). If `eq` is false, [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") will be left untouched meaning the [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method of the superclass will be used (if the superclass is [`object`](functions#object "object"), this means it will fall back to id-based hashing). * `frozen`: If true (the default is `False`), assigning to fields will generate an exception. This emulates read-only frozen instances. If [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") or [`__delattr__()`](../reference/datamodel#object.__delattr__ "object.__delattr__") is defined in the class, then [`TypeError`](exceptions#TypeError "TypeError") is raised. See the discussion below. `field`s may optionally specify a default value, using normal Python syntax: ``` @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b' ``` In this example, both `a` and `b` will be included in the added [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method, which will be defined as: ``` def __init__(self, a: int, b: int = 0): ``` [`TypeError`](exceptions#TypeError "TypeError") will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance. `dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)` For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided [`field()`](#dataclasses.field "dataclasses.field") function. For example: ``` @dataclass class C: mylist: list[int] = field(default_factory=list) c = C() c.mylist += [1, 2, 3] ``` As shown above, the `MISSING` value is a sentinel object used to detect if the `default` and `default_factory` parameters are provided. This sentinel is used because `None` is a valid value for `default`. No code should directly use the `MISSING` value. The parameters to [`field()`](#dataclasses.field "dataclasses.field") are: * `default`: If provided, this will be the default value for this field. This is needed because the [`field()`](#dataclasses.field "dataclasses.field") call itself replaces the normal position of the default value. * `default_factory`: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both `default` and `default_factory`. * `init`: If true (the default), this field is included as a parameter to the generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method. * `repr`: If true (the default), this field is included in the string returned by the generated [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__") method. * `compare`: If true (the default), this field is included in the generated equality and comparison methods ([`__eq__()`](../reference/datamodel#object.__eq__ "object.__eq__"), [`__gt__()`](../reference/datamodel#object.__gt__ "object.__gt__"), et al.). * `hash`: This can be a bool or `None`. If true, this field is included in the generated [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") method. If `None` (the default), use the value of `compare`: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than `None` is discouraged. One possible reason to set `hash=False` but `compare=True` would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons. * `metadata`: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in [`MappingProxyType()`](types#types.MappingProxyType "types.MappingProxyType") to make it read-only, and exposed on the [`Field`](#dataclasses.Field "dataclasses.Field") object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata. If the default value of a field is specified by a call to [`field()`](#dataclasses.field "dataclasses.field"), then the class attribute for this field will be replaced by the specified `default` value. If no `default` is provided, then the class attribute will be deleted. The intent is that after the [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after: ``` @dataclass class C: x: int y: int = field(repr=False) z: int = field(repr=False, default=10) t: int = 20 ``` The class attribute `C.z` will be `10`, the class attribute `C.t` will be `20`, and the class attributes `C.x` and `C.y` will not be set. `class dataclasses.Field` [`Field`](#dataclasses.Field "dataclasses.Field") objects describe each defined field. These objects are created internally, and are returned by the [`fields()`](#dataclasses.fields "dataclasses.fields") module-level method (see below). Users should never instantiate a [`Field`](#dataclasses.Field "dataclasses.Field") object directly. Its documented attributes are: * `name`: The name of the field. * `type`: The type of the field. * `default`, `default_factory`, `init`, `repr`, `hash`, `compare`, and `metadata` have the identical meaning and values as they do in the [`field()`](#dataclasses.field "dataclasses.field") declaration. Other attributes may exist, but they are private and must not be inspected or relied on. `dataclasses.fields(class_or_instance)` Returns a tuple of [`Field`](#dataclasses.Field "dataclasses.Field") objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises [`TypeError`](exceptions#TypeError "TypeError") if not passed a dataclass or instance of one. Does not return pseudo-fields which are `ClassVar` or `InitVar`. `dataclasses.asdict(obj, *, dict_factory=dict)` Converts the dataclass `obj` to a dict (by using the factory function `dict_factory`). Each dataclass is converted to a dict of its fields, as `name: value` pairs. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with [`copy.deepcopy()`](copy#copy.deepcopy "copy.deepcopy"). Example of using [`asdict()`](#dataclasses.asdict "dataclasses.asdict") on nested dataclasses: ``` @dataclass class Point: x: int y: int @dataclass class C: mylist: list[Point] p = Point(10, 20) assert asdict(p) == {'x': 10, 'y': 20} c = C([Point(0, 0), Point(10, 4)]) assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} ``` To create a shallow copy, the following workaround may be used: ``` dict((field.name, getattr(obj, field.name)) for field in fields(obj)) ``` [`asdict()`](#dataclasses.asdict "dataclasses.asdict") raises [`TypeError`](exceptions#TypeError "TypeError") if `obj` is not a dataclass instance. `dataclasses.astuple(obj, *, tuple_factory=tuple)` Converts the dataclass `obj` to a tuple (by using the factory function `tuple_factory`). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with [`copy.deepcopy()`](copy#copy.deepcopy "copy.deepcopy"). Continuing from the previous example: ``` assert astuple(p) == (10, 20) assert astuple(c) == ([(0, 0), (10, 4)],) ``` To create a shallow copy, the following workaround may be used: ``` tuple(getattr(obj, field.name) for field in dataclasses.fields(obj)) ``` [`astuple()`](#dataclasses.astuple "dataclasses.astuple") raises [`TypeError`](exceptions#TypeError "TypeError") if `obj` is not a dataclass instance. `dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)` Creates a new dataclass with name `cls_name`, fields as defined in `fields`, base classes as given in `bases`, and initialized with a namespace as given in `namespace`. `fields` is an iterable whose elements are each either `name`, `(name, type)`, or `(name, type, Field)`. If just `name` is supplied, `typing.Any` is used for `type`. The values of `init`, `repr`, `eq`, `order`, `unsafe_hash`, and `frozen` have the same meaning as they do in [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass"). This function is not strictly required, because any Python mechanism for creating a new class with `__annotations__` can then apply the [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") function to convert that class to a dataclass. This function is provided as a convenience. For example: ``` C = make_dataclass('C', [('x', int), 'y', ('z', int, field(default=5))], namespace={'add_one': lambda self: self.x + 1}) ``` Is equivalent to: ``` @dataclass class C: x: int y: 'typing.Any' z: int = 5 def add_one(self): return self.x + 1 ``` `dataclasses.replace(obj, /, **changes)` Creates a new object of the same type as `obj`, replacing fields with values from `changes`. If `obj` is not a Data Class, raises [`TypeError`](exceptions#TypeError "TypeError"). If values in `changes` do not specify fields, raises [`TypeError`](exceptions#TypeError "TypeError"). The newly returned object is created by calling the [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method of the dataclass. This ensures that `__post_init__()`, if present, is also called. Init-only variables without default values, if any exist, must be specified on the call to [`replace()`](#dataclasses.replace "dataclasses.replace") so that they can be passed to [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") and `__post_init__()`. It is an error for `changes` to contain any fields that are defined as having `init=False`. A [`ValueError`](exceptions#ValueError "ValueError") will be raised in this case. Be forewarned about how `init=False` fields work during a call to [`replace()`](#dataclasses.replace "dataclasses.replace"). They are not copied from the source object, but rather are initialized in `__post_init__()`, if they’re initialized at all. It is expected that `init=False` fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom `replace()` (or similarly named) method which handles instance copying. `dataclasses.is_dataclass(obj)` Return `True` if its parameter is a dataclass or an instance of one, otherwise return `False`. If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for `not isinstance(obj, type)`: ``` def is_dataclass_instance(obj): return is_dataclass(obj) and not isinstance(obj, type) ``` Post-init processing -------------------- The generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") code will call a method named `__post_init__()`, if `__post_init__()` is defined on the class. It will normally be called as `self.__post_init__()`. However, if any `InitVar` fields are defined, they will also be passed to `__post_init__()` in the order they were defined in the class. If no [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method is generated, then `__post_init__()` will not automatically be called. Among other uses, this allows for initializing field values that depend on one or more other fields. For example: ``` @dataclass class C: a: float b: float c: float = field(init=False) def __post_init__(self): self.c = self.a + self.b ``` The [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method generated by [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") does not call base class [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") methods. If the base class has an [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method that has to be called, it is common to call this method in a `__post_init__()` method: ``` @dataclass class Rectangle: height: float width: float @dataclass class Square(Rectangle): side: float def __post_init__(self): super().__init__(self.side, self.side) ``` Note, however, that in general the dataclass-generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself. See the section below on init-only variables for ways to pass parameters to `__post_init__()`. Also see the warning about how [`replace()`](#dataclasses.replace "dataclasses.replace") handles `init=False` fields. Class variables --------------- One of two places where [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") actually inspects the type of a field is to determine if a field is a class variable as defined in [**PEP 526**](https://www.python.org/dev/peps/pep-0526). It does this by checking if the type of the field is `typing.ClassVar`. If a field is a `ClassVar`, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such `ClassVar` pseudo-fields are not returned by the module-level [`fields()`](#dataclasses.fields "dataclasses.fields") function. Init-only variables ------------------- The other place where [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type `dataclasses.InitVar`. If a field is an `InitVar`, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level [`fields()`](#dataclasses.fields "dataclasses.fields") function. Init-only fields are added as parameters to the generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method, and are passed to the optional `__post_init__()` method. They are not otherwise used by dataclasses. For example, suppose a field will be initialized from a database, if a value is not provided when creating the class: ``` @dataclass class C: i: int j: int = None database: InitVar[DatabaseType] = None def __post_init__(self, database): if self.j is None and database is not None: self.j = database.lookup('j') c = C(10, database=my_database) ``` In this case, [`fields()`](#dataclasses.fields "dataclasses.fields") will return [`Field`](#dataclasses.Field "dataclasses.Field") objects for `i` and `j`, but not for `database`. Frozen instances ---------------- It is not possible to create truly immutable Python objects. However, by passing `frozen=True` to the [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator you can emulate immutability. In that case, dataclasses will add [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") and [`__delattr__()`](../reference/datamodel#object.__delattr__ "object.__delattr__") methods to the class. These methods will raise a [`FrozenInstanceError`](#dataclasses.FrozenInstanceError "dataclasses.FrozenInstanceError") when invoked. There is a tiny performance penalty when using `frozen=True`: [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") cannot use simple assignment to initialize fields, and must use [`object.__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__"). Inheritance ----------- When the dataclass is being created by the [`dataclass()`](#dataclasses.dataclass "dataclasses.dataclass") decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at [`object`](functions#object "object")) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example: ``` @dataclass class Base: x: Any = 15.0 y: int = 0 @dataclass class C(Base): z: int = 10 x: int = 15 ``` The final list of fields is, in order, `x`, `y`, `z`. The final type of `x` is `int`, as specified in class `C`. The generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method for `C` will look like: ``` def __init__(self, x: int = 15, y: int = 0, z: int = 10): ``` Default factory functions ------------------------- If a [`field()`](#dataclasses.field "dataclasses.field") specifies a `default_factory`, it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use: ``` mylist: list = field(default_factory=list) ``` If a field is excluded from [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") (using `init=False`) and the field also specifies `default_factory`, then the default factory function will always be called from the generated [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") function. This happens because there is no other way to give the field an initial value. Mutable default values ---------------------- Python stores default member variable values in class attributes. Consider this example, not using dataclasses: ``` class C: x = [] def add(self, element): self.x.append(element) o1 = C() o2 = C() o1.add(1) o2.add(2) assert o1.x == [1, 2] assert o1.x is o2.x ``` Note that the two instances of class `C` share the same class variable `x`, as expected. Using dataclasses, *if* this code was valid: ``` @dataclass class D: x: List = [] def add(self, element): self.x += element ``` it would generate code similar to: ``` class D: x = [] def __init__(self, x=x): self.x = x def add(self, element): self.x += element assert D().x is D().x ``` This has the same issue as the original example using class `C`. That is, two instances of class `D` that do not specify a value for `x` when creating a class instance will share the same copy of `x`. Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, dataclasses will raise a [`TypeError`](exceptions#TypeError "TypeError") if it detects a default parameter of type `list`, `dict`, or `set`. This is a partial solution, but it does protect against many common errors. Using default factory functions is a way to create new instances of mutable types as default values for fields: ``` @dataclass class D: x: list = field(default_factory=list) assert D().x is not D().x ``` Exceptions ---------- `exception dataclasses.FrozenInstanceError` Raised when an implicitly defined [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") or [`__delattr__()`](../reference/datamodel#object.__delattr__ "object.__delattr__") is called on a dataclass which was defined with `frozen=True`. It is a subclass of [`AttributeError`](exceptions#AttributeError "AttributeError").
programming_docs
python File Formats File Formats ============ The modules described in this chapter parse various miscellaneous file formats that aren’t markup languages and are not related to e-mail. * [`csv` — CSV File Reading and Writing](csv) + [Module Contents](csv#module-contents) + [Dialects and Formatting Parameters](csv#dialects-and-formatting-parameters) + [Reader Objects](csv#reader-objects) + [Writer Objects](csv#writer-objects) + [Examples](csv#examples) * [`configparser` — Configuration file parser](configparser) + [Quick Start](configparser#quick-start) + [Supported Datatypes](configparser#supported-datatypes) + [Fallback Values](configparser#fallback-values) + [Supported INI File Structure](configparser#supported-ini-file-structure) + [Interpolation of values](configparser#interpolation-of-values) + [Mapping Protocol Access](configparser#mapping-protocol-access) + [Customizing Parser Behaviour](configparser#customizing-parser-behaviour) + [Legacy API Examples](configparser#legacy-api-examples) + [ConfigParser Objects](configparser#configparser-objects) + [RawConfigParser Objects](configparser#rawconfigparser-objects) + [Exceptions](configparser#exceptions) * [`netrc` — netrc file processing](netrc) + [netrc Objects](netrc#netrc-objects) * [`plistlib` — Generate and parse Apple `.plist` files](plistlib) + [Examples](plistlib#examples) python urllib.request — Extensible library for opening URLs urllib.request — Extensible library for opening URLs ==================================================== **Source code:** [Lib/urllib/request.py](https://github.com/python/cpython/tree/3.9/Lib/urllib/request.py) The [`urllib.request`](#module-urllib.request "urllib.request: Extensible library for opening URLs.") module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. See also The [Requests package](https://requests.readthedocs.io/en/master/) is recommended for a higher-level HTTP client interface. The [`urllib.request`](#module-urllib.request "urllib.request: Extensible library for opening URLs.") module defines the following functions: `urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)` Open the URL *url*, which can be either a string or a [`Request`](#urllib.request.Request "urllib.request.Request") object. *data* must be an object specifying additional data to be sent to the server, or `None` if no such data is needed. See [`Request`](#urllib.request.Request "urllib.request.Request") for details. urllib.request module uses HTTP/1.1 and includes `Connection:close` header in its HTTP requests. The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If *context* is specified, it must be a [`ssl.SSLContext`](ssl#ssl.SSLContext "ssl.SSLContext") instance describing the various SSL options. See [`HTTPSConnection`](http.client#http.client.HTTPSConnection "http.client.HTTPSConnection") for more details. The optional *cafile* and *capath* parameters specify a set of trusted CA certificates for HTTPS requests. *cafile* should point to a single file containing a bundle of CA certificates, whereas *capath* should point to a directory of hashed certificate files. More information can be found in [`ssl.SSLContext.load_verify_locations()`](ssl#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations"). The *cadefault* parameter is ignored. This function always returns an object which can work as a [context manager](../glossary#term-context-manager) and has the properties *url*, *headers*, and *status*. See [`urllib.response.addinfourl`](#urllib.response.addinfourl "urllib.response.addinfourl") for more detail on these properties. For HTTP and HTTPS URLs, this function returns a [`http.client.HTTPResponse`](http.client#http.client.HTTPResponse "http.client.HTTPResponse") object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the [`reason`](http.client#http.client.HTTPResponse.reason "http.client.HTTPResponse.reason") attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for [`HTTPResponse`](http.client#http.client.HTTPResponse "http.client.HTTPResponse"). For FTP, file, and data URLs and requests explicitly handled by legacy [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener") and [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener") classes, this function returns a [`urllib.response.addinfourl`](#urllib.response.addinfourl "urllib.response.addinfourl") object. Raises [`URLError`](urllib.error#urllib.error.URLError "urllib.error.URLError") on protocol errors. Note that `None` may be returned if no handler handles the request (though the default installed global [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") uses [`UnknownHandler`](#urllib.request.UnknownHandler "urllib.request.UnknownHandler") to ensure this never happens). In addition, if proxy settings are detected (for example, when a `*_proxy` environment variable like `http_proxy` is set), [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") is default installed and makes sure the requests are handled through the proxy. The legacy `urllib.urlopen` function from Python 2.6 and earlier has been discontinued; [`urllib.request.urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") corresponds to the old `urllib2.urlopen`. Proxy handling, which was done by passing a dictionary parameter to `urllib.urlopen`, can be obtained by using [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") objects. The default opener raises an [auditing event](sys#auditing) `urllib.Request` with arguments `fullurl`, `data`, `headers`, `method` taken from the request object. Changed in version 3.2: *cafile* and *capath* were added. Changed in version 3.2: HTTPS virtual hosts are now supported if possible (that is, if [`ssl.HAS_SNI`](ssl#ssl.HAS_SNI "ssl.HAS_SNI") is true). New in version 3.2: *data* can be an iterable object. Changed in version 3.3: *cadefault* was added. Changed in version 3.4.3: *context* was added. Deprecated since version 3.6: *cafile*, *capath* and *cadefault* are deprecated in favor of *context*. Please use [`ssl.SSLContext.load_cert_chain()`](ssl#ssl.SSLContext.load_cert_chain "ssl.SSLContext.load_cert_chain") instead, or let [`ssl.create_default_context()`](ssl#ssl.create_default_context "ssl.create_default_context") select the system’s trusted CA certificates for you. `urllib.request.install_opener(opener)` Install an [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") instance as the default global opener. Installing an opener is only necessary if you want urlopen to use that opener; otherwise, simply call [`OpenerDirector.open()`](#urllib.request.OpenerDirector.open "urllib.request.OpenerDirector.open") instead of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). The code does not check for a real [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"), and any class with the appropriate interface will work. `urllib.request.build_opener([handler, ...])` Return an [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") instance, which chains the handlers in the order given. *handler*s can be either instances of [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), or subclasses of [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler") (in which case it must be possible to call the constructor without any parameters). Instances of the following classes will be in front of the *handler*s, unless the *handler*s contain them, instances of them or subclasses of them: [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") (if proxy settings are detected), [`UnknownHandler`](#urllib.request.UnknownHandler "urllib.request.UnknownHandler"), [`HTTPHandler`](#urllib.request.HTTPHandler "urllib.request.HTTPHandler"), [`HTTPDefaultErrorHandler`](#urllib.request.HTTPDefaultErrorHandler "urllib.request.HTTPDefaultErrorHandler"), [`HTTPRedirectHandler`](#urllib.request.HTTPRedirectHandler "urllib.request.HTTPRedirectHandler"), [`FTPHandler`](#urllib.request.FTPHandler "urllib.request.FTPHandler"), [`FileHandler`](#urllib.request.FileHandler "urllib.request.FileHandler"), [`HTTPErrorProcessor`](#urllib.request.HTTPErrorProcessor "urllib.request.HTTPErrorProcessor"). If the Python installation has SSL support (i.e., if the [`ssl`](ssl#module-ssl "ssl: TLS/SSL wrapper for socket objects") module can be imported), [`HTTPSHandler`](#urllib.request.HTTPSHandler "urllib.request.HTTPSHandler") will also be added. A [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler") subclass may also change its `handler_order` attribute to modify its position in the handlers list. `urllib.request.pathname2url(path)` Convert the pathname *path* from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the [`quote()`](urllib.parse#urllib.parse.quote "urllib.parse.quote") function. `urllib.request.url2pathname(path)` Convert the path component *path* from a percent-encoded URL to the local syntax for a path. This does not accept a complete URL. This function uses [`unquote()`](urllib.parse#urllib.parse.unquote "urllib.parse.unquote") to decode *path*. `urllib.request.getproxies()` This helper function returns a dictionary of scheme to proxy server URL mappings. It scans the environment for variables named `<scheme>_proxy`, in a case insensitive approach, for all operating systems first, and when it cannot find it, looks for proxy information from System Configuration for macOS and Windows Systems Registry for Windows. If both lowercase and uppercase environment variables exist (and disagree), lowercase is preferred. Note If the environment variable `REQUEST_METHOD` is set, which usually indicates your script is running in a CGI environment, the environment variable `HTTP_PROXY` (uppercase `_PROXY`) will be ignored. This is because that variable can be injected by a client using the “Proxy:” HTTP header. If you need to use an HTTP proxy in a CGI environment, either use `ProxyHandler` explicitly, or make sure the variable name is in lowercase (or at least the `_proxy` suffix). The following classes are provided: `class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)` This class is an abstraction of a URL request. *url* should be a string containing a valid URL. *data* must be an object specifying additional data to send to the server, or `None` if no such data is needed. Currently HTTP requests are the only ones that use *data*. The supported object types include bytes, file-like objects, and iterables of bytes-like objects. If no `Content-Length` nor `Transfer-Encoding` header field has been provided, [`HTTPHandler`](#urllib.request.HTTPHandler "urllib.request.HTTPHandler") will set these headers according to the type of *data*. `Content-Length` will be used to send bytes objects, while `Transfer-Encoding: chunked` as specified in [**RFC 7230**](https://tools.ietf.org/html/rfc7230.html), Section 3.3.1 will be used to send files and other iterables. For an HTTP POST request method, *data* should be a buffer in the standard *application/x-www-form-urlencoded* format. The [`urllib.parse.urlencode()`](urllib.parse#urllib.parse.urlencode "urllib.parse.urlencode") function takes a mapping or sequence of 2-tuples and returns an ASCII string in this format. It should be encoded to bytes before being used as the *data* parameter. *headers* should be a dictionary, and will be treated as if [`add_header()`](#urllib.request.Request.add_header "urllib.request.Request.add_header") was called with each key and value as arguments. This is often used to “spoof” the `User-Agent` header value, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as `"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"`, while [`urllib`](urllib#module-urllib "urllib")’s default user agent string is `"Python-urllib/2.6"` (on Python 2.6). All header keys are sent in camel case. An appropriate `Content-Type` header should be included if the *data* argument is present. If this header has not been provided and *data* is not None, `Content-Type: application/x-www-form-urlencoded` will be added as a default. The next two arguments are only of interest for correct handling of third-party HTTP cookies: *origin\_req\_host* should be the request-host of the origin transaction, as defined by [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html). It defaults to `http.cookiejar.request_host(self)`. This is the host name or IP address of the original request that was initiated by the user. For example, if the request is for an image in an HTML document, this should be the request-host of the request for the page containing the image. *unverifiable* should indicate whether the request is unverifiable, as defined by [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html). It defaults to `False`. An unverifiable request is one whose URL the user did not have the option to approve. For example, if the request is for an image in an HTML document, and the user had no option to approve the automatic fetching of the image, this should be true. *method* should be a string that indicates the HTTP request method that will be used (e.g. `'HEAD'`). If provided, its value is stored in the [`method`](#urllib.request.Request.method "urllib.request.Request.method") attribute and is used by [`get_method()`](#urllib.request.Request.get_method "urllib.request.Request.get_method"). The default is `'GET'` if *data* is `None` or `'POST'` otherwise. Subclasses may indicate a different default method by setting the [`method`](#urllib.request.Request.method "urllib.request.Request.method") attribute in the class itself. Note The request will not work as expected if the data object is unable to deliver its content more than once (e.g. a file or an iterable that can produce the content only once) and the request is retried for HTTP redirects or authentication. The *data* is sent to the HTTP server right away after the headers. There is no support for a 100-continue expectation in the library. Changed in version 3.3: [`Request.method`](#urllib.request.Request.method "urllib.request.Request.method") argument is added to the Request class. Changed in version 3.4: Default [`Request.method`](#urllib.request.Request.method "urllib.request.Request.method") may be indicated at the class level. Changed in version 3.6: Do not raise an error if the `Content-Length` has not been provided and *data* is neither `None` nor a bytes object. Fall back to use chunked transfer encoding instead. `class urllib.request.OpenerDirector` The [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") class opens URLs via [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler")s chained together. It manages the chaining of handlers, and recovery from errors. `class urllib.request.BaseHandler` This is the base class for all registered handlers — and handles only the simple mechanics of registration. `class urllib.request.HTTPDefaultErrorHandler` A class which defines a default handler for HTTP error responses; all responses are turned into [`HTTPError`](urllib.error#urllib.error.HTTPError "urllib.error.HTTPError") exceptions. `class urllib.request.HTTPRedirectHandler` A class to handle redirections. `class urllib.request.HTTPCookieProcessor(cookiejar=None)` A class to handle HTTP Cookies. `class urllib.request.ProxyHandler(proxies=None)` Cause requests to go through a proxy. If *proxies* is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables `<protocol>_proxy`. If no proxy environment variables are set, then in a Windows environment proxy settings are obtained from the registry’s Internet Settings section, and in a macOS environment proxy information is retrieved from the System Configuration Framework. To disable autodetected proxy pass an empty dictionary. The `no_proxy` environment variable can be used to specify hosts which shouldn’t be reached via proxy; if set, it should be a comma-separated list of hostname suffixes, optionally with `:port` appended, for example `cern.ch,ncsa.uiuc.edu,some.host:8080`. Note `HTTP_PROXY` will be ignored if a variable `REQUEST_METHOD` is set; see the documentation on [`getproxies()`](#urllib.request.getproxies "urllib.request.getproxies"). `class urllib.request.HTTPPasswordMgr` Keep a database of `(realm, uri) -> (user, password)` mappings. `class urllib.request.HTTPPasswordMgrWithDefaultRealm` Keep a database of `(realm, uri) -> (user, password)` mappings. A realm of `None` is considered a catch-all realm, which is searched if no other realm fits. `class urllib.request.HTTPPasswordMgrWithPriorAuth` A variant of [`HTTPPasswordMgrWithDefaultRealm`](#urllib.request.HTTPPasswordMgrWithDefaultRealm "urllib.request.HTTPPasswordMgrWithDefaultRealm") that also has a database of `uri -> is_authenticated` mappings. Can be used by a BasicAuth handler to determine when to send authentication credentials immediately instead of waiting for a `401` response first. New in version 3.5. `class urllib.request.AbstractBasicAuthHandler(password_mgr=None)` This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. If *passwd\_mgr* also provides `is_authenticated` and `update_authenticated` methods (see [HTTPPasswordMgrWithPriorAuth Objects](#http-password-mgr-with-prior-auth)), then the handler will use the `is_authenticated` result for a given URI to determine whether or not to send authentication credentials with the request. If `is_authenticated` returns `True` for the URI, credentials are sent. If `is_authenticated` is `False`, credentials are not sent, and then if a `401` response is received the request is re-sent with the authentication credentials. If authentication succeeds, `update_authenticated` is called to set `is_authenticated` `True` for the URI, so that subsequent requests to the URI or any of its super-URIs will automatically include the authentication credentials. New in version 3.5: Added `is_authenticated` support. `class urllib.request.HTTPBasicAuthHandler(password_mgr=None)` Handle authentication with the remote host. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. HTTPBasicAuthHandler will raise a [`ValueError`](exceptions#ValueError "ValueError") when presented with a wrong Authentication scheme. `class urllib.request.ProxyBasicAuthHandler(password_mgr=None)` Handle authentication with the proxy. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. `class urllib.request.AbstractDigestAuthHandler(password_mgr=None)` This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. `class urllib.request.HTTPDigestAuthHandler(password_mgr=None)` Handle authentication with the remote host. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. When both Digest Authentication Handler and Basic Authentication Handler are both added, Digest Authentication is always tried first. If the Digest Authentication returns a 40x response again, it is sent to Basic Authentication handler to Handle. This Handler method will raise a [`ValueError`](exceptions#ValueError "ValueError") when presented with an authentication scheme other than Digest or Basic. Changed in version 3.3: Raise [`ValueError`](exceptions#ValueError "ValueError") on unsupported Authentication Scheme. `class urllib.request.ProxyDigestAuthHandler(password_mgr=None)` Handle authentication with the proxy. *password\_mgr*, if given, should be something that is compatible with [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr"); refer to section [HTTPPasswordMgr Objects](#http-password-mgr) for information on the interface that must be supported. `class urllib.request.HTTPHandler` A class to handle opening of HTTP URLs. `class urllib.request.HTTPSHandler(debuglevel=0, context=None, check_hostname=None)` A class to handle opening of HTTPS URLs. *context* and *check\_hostname* have the same meaning as in [`http.client.HTTPSConnection`](http.client#http.client.HTTPSConnection "http.client.HTTPSConnection"). Changed in version 3.2: *context* and *check\_hostname* were added. `class urllib.request.FileHandler` Open local files. `class urllib.request.DataHandler` Open data URLs. New in version 3.4. `class urllib.request.FTPHandler` Open FTP URLs. `class urllib.request.CacheFTPHandler` Open FTP URLs, keeping a cache of open FTP connections to minimize delays. `class urllib.request.UnknownHandler` A catch-all class to handle unknown URLs. `class urllib.request.HTTPErrorProcessor` Process HTTP error responses. Request Objects --------------- The following methods describe [`Request`](#urllib.request.Request "urllib.request.Request")’s public interface, and so all may be overridden in subclasses. It also defines several public attributes that can be used by clients to inspect the parsed request. `Request.full_url` The original URL passed to the constructor. Changed in version 3.4. Request.full\_url is a property with setter, getter and a deleter. Getting [`full_url`](#urllib.request.Request.full_url "urllib.request.Request.full_url") returns the original request URL with the fragment, if it was present. `Request.type` The URI scheme. `Request.host` The URI authority, typically a host, but may also contain a port separated by a colon. `Request.origin_req_host` The original host for the request, without port. `Request.selector` The URI path. If the [`Request`](#urllib.request.Request "urllib.request.Request") uses a proxy, then selector will be the full URL that is passed to the proxy. `Request.data` The entity body for the request, or `None` if not specified. Changed in version 3.4: Changing value of [`Request.data`](#urllib.request.Request.data "urllib.request.Request.data") now deletes “Content-Length” header if it was previously set or calculated. `Request.unverifiable` boolean, indicates whether the request is unverifiable as defined by [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html). `Request.method` The HTTP request method to use. By default its value is [`None`](constants#None "None"), which means that [`get_method()`](#urllib.request.Request.get_method "urllib.request.Request.get_method") will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation in [`get_method()`](#urllib.request.Request.get_method "urllib.request.Request.get_method")) either by providing a default value by setting it at the class level in a [`Request`](#urllib.request.Request "urllib.request.Request") subclass, or by passing a value in to the [`Request`](#urllib.request.Request "urllib.request.Request") constructor via the *method* argument. New in version 3.3. Changed in version 3.4: A default value can now be set in subclasses; previously it could only be set via the constructor argument. `Request.get_method()` Return a string indicating the HTTP request method. If [`Request.method`](#urllib.request.Request.method "urllib.request.Request.method") is not `None`, return its value, otherwise return `'GET'` if [`Request.data`](#urllib.request.Request.data "urllib.request.Request.data") is `None`, or `'POST'` if it’s not. This is only meaningful for HTTP requests. Changed in version 3.3: get\_method now looks at the value of [`Request.method`](#urllib.request.Request.method "urllib.request.Request.method"). `Request.add_header(key, val)` Add another header to the request. Headers are currently ignored by all handlers except HTTP handlers, where they are added to the list of headers sent to the server. Note that there cannot be more than one header with the same name, and later calls will overwrite previous calls in case the *key* collides. Currently, this is no loss of HTTP functionality, since all headers which have meaning when used more than once have a (header-specific) way of gaining the same functionality using only one header. Note that headers added using this method are also added to redirected requests. `Request.add_unredirected_header(key, header)` Add a header that will not be added to a redirected request. `Request.has_header(header)` Return whether the instance has the named header (checks both regular and unredirected). `Request.remove_header(header)` Remove named header from the request instance (both from regular and unredirected headers). New in version 3.4. `Request.get_full_url()` Return the URL given in the constructor. Changed in version 3.4. Returns [`Request.full_url`](#urllib.request.Request.full_url "urllib.request.Request.full_url") `Request.set_proxy(host, type)` Prepare the request by connecting to a proxy server. The *host* and *type* will replace those of the instance, and the instance’s selector will be the original URL given in the constructor. `Request.get_header(header_name, default=None)` Return the value of the given header. If the header is not present, return the default value. `Request.header_items()` Return a list of tuples (header\_name, header\_value) of the Request headers. Changed in version 3.4: The request methods add\_data, has\_data, get\_data, get\_type, get\_host, get\_selector, get\_origin\_req\_host and is\_unverifiable that were deprecated since 3.3 have been removed. OpenerDirector Objects ---------------------- [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") instances have the following methods: `OpenerDirector.add_handler(handler)` *handler* should be an instance of [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"). The following methods are searched, and added to the possible chains (note that HTTP errors are a special case). Note that, in the following, *protocol* should be replaced with the actual protocol to handle, for example `http_response()` would be the HTTP protocol response handler. Also *type* should be replaced with the actual HTTP code, for example `http_error_404()` would handle HTTP 404 errors. * `<protocol>_open()` — signal that the handler knows how to open *protocol* URLs. See [`BaseHandler.<protocol>_open()`](#protocol-open) for more information. * `http_error_<type>()` — signal that the handler knows how to handle HTTP errors with HTTP error code *type*. See [`BaseHandler.http_error_<nnn>()`](#http-error-nnn) for more information. * `<protocol>_error()` — signal that the handler knows how to handle errors from (non-`http`) *protocol*. * `<protocol>_request()` — signal that the handler knows how to pre-process *protocol* requests. See [`BaseHandler.<protocol>_request()`](#protocol-request) for more information. * `<protocol>_response()` — signal that the handler knows how to post-process *protocol* responses. See [`BaseHandler.<protocol>_response()`](#protocol-response) for more information. `OpenerDirector.open(url, data=None[, timeout])` Open the given *url* (which can be a request object or a string), optionally passing the given *data*. Arguments, return values and exceptions raised are the same as those of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") (which simply calls the [`open()`](functions#open "open") method on the currently installed global [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector")). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS and FTP connections. `OpenerDirector.error(proto, *args)` Handle an error of the given protocol. This will call the registered error handlers for the given protocol with the given arguments (which are protocol specific). The HTTP protocol is a special case which uses the HTTP response code to determine the specific error handler; refer to the `http_error_<type>()` methods of the handler classes. Return values and exceptions raised are the same as those of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). OpenerDirector objects open URLs in three stages: The order in which these methods are called within each stage is determined by sorting the handler instances. 1. Every handler with a method named like `<protocol>_request()` has that method called to pre-process the request. 2. Handlers with a method named like `<protocol>_open()` are called to handle the request. This stage ends when a handler either returns a non-[`None`](constants#None "None") value (ie. a response), or raises an exception (usually [`URLError`](urllib.error#urllib.error.URLError "urllib.error.URLError")). Exceptions are allowed to propagate. In fact, the above algorithm is first tried for methods named `default_open()`. If all such methods return [`None`](constants#None "None"), the algorithm is repeated for methods named like `<protocol>_open()`. If all such methods return [`None`](constants#None "None"), the algorithm is repeated for methods named `unknown_open()`. Note that the implementation of these methods may involve calls of the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") instance’s [`open()`](#urllib.request.OpenerDirector.open "urllib.request.OpenerDirector.open") and [`error()`](#urllib.request.OpenerDirector.error "urllib.request.OpenerDirector.error") methods. 3. Every handler with a method named like `<protocol>_response()` has that method called to post-process the response. BaseHandler Objects ------------------- [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler") objects provide a couple of methods that are directly useful, and others that are meant to be used by derived classes. These are intended for direct use: `BaseHandler.add_parent(director)` Add a director as parent. `BaseHandler.close()` Remove any parents. The following attribute and methods should only be used by classes derived from [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"). Note The convention has been adopted that subclasses defining `<protocol>_request()` or `<protocol>_response()` methods are named `*Processor`; all others are named `*Handler`. `BaseHandler.parent` A valid [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"), which can be used to open using a different protocol, or handle errors. `BaseHandler.default_open(req)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should define it if they want to catch all URLs. This method, if implemented, will be called by the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"). It should return a file-like object as described in the return value of the [`open()`](#urllib.request.OpenerDirector.open "urllib.request.OpenerDirector.open") method of [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"), or `None`. It should raise [`URLError`](urllib.error#urllib.error.URLError "urllib.error.URLError"), unless a truly exceptional thing happens (for example, [`MemoryError`](exceptions#MemoryError "MemoryError") should not be mapped to `URLError`). This method will be called before any protocol-specific open method. `BaseHandler.<protocol>_open(req)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should define it if they want to handle URLs with the given protocol. This method, if defined, will be called by the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"). Return values should be the same as for `default_open()`. `BaseHandler.unknown_open(req)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should define it if they want to catch all URLs with no specific registered handler to open it. This method, if implemented, will be called by the [`parent`](#urllib.request.BaseHandler.parent "urllib.request.BaseHandler.parent") [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"). Return values should be the same as for [`default_open()`](#urllib.request.BaseHandler.default_open "urllib.request.BaseHandler.default_open"). `BaseHandler.http_error_default(req, fp, code, msg, hdrs)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should override it if they intend to provide a catch-all for otherwise unhandled HTTP errors. It will be called automatically by the [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") getting the error, and should not normally be called in other circumstances. *req* will be a [`Request`](#urllib.request.Request "urllib.request.Request") object, *fp* will be a file-like object with the HTTP error body, *code* will be the three-digit code of the error, *msg* will be the user-visible explanation of the code and *hdrs* will be a mapping object with the headers of the error. Return values and exceptions raised should be the same as those of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). `BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)` *nnn* should be a three-digit HTTP error code. This method is also not defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but will be called, if it exists, on an instance of a subclass, when an HTTP error with code *nnn* occurs. Subclasses should override this method to handle specific HTTP errors. Arguments, return values and exceptions raised should be the same as for `http_error_default()`. `BaseHandler.<protocol>_request(req)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should define it if they want to pre-process requests of the given protocol. This method, if defined, will be called by the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"). *req* will be a [`Request`](#urllib.request.Request "urllib.request.Request") object. The return value should be a [`Request`](#urllib.request.Request "urllib.request.Request") object. `BaseHandler.<protocol>_response(req, response)` This method is *not* defined in [`BaseHandler`](#urllib.request.BaseHandler "urllib.request.BaseHandler"), but subclasses should define it if they want to post-process responses of the given protocol. This method, if defined, will be called by the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector"). *req* will be a [`Request`](#urllib.request.Request "urllib.request.Request") object. *response* will be an object implementing the same interface as the return value of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). The return value should implement the same interface as the return value of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). HTTPRedirectHandler Objects --------------------------- Note Some HTTP redirections require action from this module’s client code. If this is the case, [`HTTPError`](urllib.error#urllib.error.HTTPError "urllib.error.HTTPError") is raised. See [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html) for details of the precise meanings of the various redirection codes. An `HTTPError` exception raised as a security consideration if the HTTPRedirectHandler is presented with a redirected URL which is not an HTTP, HTTPS or FTP URL. `HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)` Return a [`Request`](#urllib.request.Request "urllib.request.Request") or `None` in response to a redirect. This is called by the default implementations of the `http_error_30*()` methods when a redirection is received from the server. If a redirection should take place, return a new [`Request`](#urllib.request.Request "urllib.request.Request") to allow `http_error_30*()` to perform the redirect to *newurl*. Otherwise, raise [`HTTPError`](urllib.error#urllib.error.HTTPError "urllib.error.HTTPError") if no other handler should try to handle this URL, or return `None` if you can’t but another handler might. Note The default implementation of this method does not strictly follow [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html), which says that 301 and 302 responses to `POST` requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a `GET`, and the default implementation reproduces this behavior. `HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)` Redirect to the `Location:` or `URI:` URL. This method is called by the parent [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") when getting an HTTP ‘moved permanently’ response. `HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)` The same as [`http_error_301()`](#urllib.request.HTTPRedirectHandler.http_error_301 "urllib.request.HTTPRedirectHandler.http_error_301"), but called for the ‘found’ response. `HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)` The same as [`http_error_301()`](#urllib.request.HTTPRedirectHandler.http_error_301 "urllib.request.HTTPRedirectHandler.http_error_301"), but called for the ‘see other’ response. `HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)` The same as [`http_error_301()`](#urllib.request.HTTPRedirectHandler.http_error_301 "urllib.request.HTTPRedirectHandler.http_error_301"), but called for the ‘temporary redirect’ response. HTTPCookieProcessor Objects --------------------------- [`HTTPCookieProcessor`](#urllib.request.HTTPCookieProcessor "urllib.request.HTTPCookieProcessor") instances have one attribute: `HTTPCookieProcessor.cookiejar` The [`http.cookiejar.CookieJar`](http.cookiejar#http.cookiejar.CookieJar "http.cookiejar.CookieJar") in which cookies are stored. ProxyHandler Objects -------------------- `ProxyHandler.<protocol>_open(request)` The [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") will have a method `<protocol>_open()` for every *protocol* which has a proxy in the *proxies* dictionary given in the constructor. The method will modify requests to go through the proxy, by calling `request.set_proxy()`, and call the next handler in the chain to actually execute the protocol. HTTPPasswordMgr Objects ----------------------- These methods are available on [`HTTPPasswordMgr`](#urllib.request.HTTPPasswordMgr "urllib.request.HTTPPasswordMgr") and [`HTTPPasswordMgrWithDefaultRealm`](#urllib.request.HTTPPasswordMgrWithDefaultRealm "urllib.request.HTTPPasswordMgrWithDefaultRealm") objects. `HTTPPasswordMgr.add_password(realm, uri, user, passwd)` *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and *passwd* must be strings. This causes `(user, passwd)` to be used as authentication tokens when authentication for *realm* and a super-URI of any of the given URIs is given. `HTTPPasswordMgr.find_user_password(realm, authuri)` Get user/password for given realm and URI, if any. This method will return `(None, None)` if there is no matching user/password. For [`HTTPPasswordMgrWithDefaultRealm`](#urllib.request.HTTPPasswordMgrWithDefaultRealm "urllib.request.HTTPPasswordMgrWithDefaultRealm") objects, the realm `None` will be searched if the given *realm* has no matching user/password. HTTPPasswordMgrWithPriorAuth Objects ------------------------------------ This password manager extends [`HTTPPasswordMgrWithDefaultRealm`](#urllib.request.HTTPPasswordMgrWithDefaultRealm "urllib.request.HTTPPasswordMgrWithDefaultRealm") to support tracking URIs for which authentication credentials should always be sent. `HTTPPasswordMgrWithPriorAuth.add_password(realm, uri, user, passwd, is_authenticated=False)` *realm*, *uri*, *user*, *passwd* are as for [`HTTPPasswordMgr.add_password()`](#urllib.request.HTTPPasswordMgr.add_password "urllib.request.HTTPPasswordMgr.add_password"). *is\_authenticated* sets the initial value of the `is_authenticated` flag for the given URI or list of URIs. If *is\_authenticated* is specified as `True`, *realm* is ignored. `HTTPPasswordMgrWithPriorAuth.find_user_password(realm, authuri)` Same as for [`HTTPPasswordMgrWithDefaultRealm`](#urllib.request.HTTPPasswordMgrWithDefaultRealm "urllib.request.HTTPPasswordMgrWithDefaultRealm") objects `HTTPPasswordMgrWithPriorAuth.update_authenticated(self, uri, is_authenticated=False)` Update the `is_authenticated` flag for the given *uri* or list of URIs. `HTTPPasswordMgrWithPriorAuth.is_authenticated(self, authuri)` Returns the current state of the `is_authenticated` flag for the given URI. AbstractBasicAuthHandler Objects -------------------------------- `AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)` Handle an authentication request by getting a user/password pair, and re-trying the request. *authreq* should be the name of the header where the information about the realm is included in the request, *host* specifies the URL and path to authenticate for, *req* should be the (failed) [`Request`](#urllib.request.Request "urllib.request.Request") object, and *headers* should be the error headers. *host* is either an authority (e.g. `"python.org"`) or a URL containing an authority component (e.g. `"http://python.org/"`). In either case, the authority must not contain a userinfo component (so, `"python.org"` and `"python.org:80"` are fine, `"joe:[email protected]"` is not). HTTPBasicAuthHandler Objects ---------------------------- `HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)` Retry the request with authentication information, if available. ProxyBasicAuthHandler Objects ----------------------------- `ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)` Retry the request with authentication information, if available. AbstractDigestAuthHandler Objects --------------------------------- `AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)` *authreq* should be the name of the header where the information about the realm is included in the request, *host* should be the host to authenticate to, *req* should be the (failed) [`Request`](#urllib.request.Request "urllib.request.Request") object, and *headers* should be the error headers. HTTPDigestAuthHandler Objects ----------------------------- `HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)` Retry the request with authentication information, if available. ProxyDigestAuthHandler Objects ------------------------------ `ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)` Retry the request with authentication information, if available. HTTPHandler Objects ------------------- `HTTPHandler.http_open(req)` Send an HTTP request, which can be either GET or POST, depending on `req.has_data()`. HTTPSHandler Objects -------------------- `HTTPSHandler.https_open(req)` Send an HTTPS request, which can be either GET or POST, depending on `req.has_data()`. FileHandler Objects ------------------- `FileHandler.file_open(req)` Open the file locally, if there is no host name, or the host name is `'localhost'`. Changed in version 3.2: This method is applicable only for local hostnames. When a remote hostname is given, an [`URLError`](urllib.error#urllib.error.URLError "urllib.error.URLError") is raised. DataHandler Objects ------------------- `DataHandler.data_open(req)` Read a data URL. This kind of URL contains the content encoded in the URL itself. The data URL syntax is specified in [**RFC 2397**](https://tools.ietf.org/html/rfc2397.html). This implementation ignores white spaces in base64 encoded data URLs so the URL may be wrapped in whatever source file it comes from. But even though some browsers don’t mind about a missing padding at the end of a base64 encoded data URL, this implementation will raise an [`ValueError`](exceptions#ValueError "ValueError") in that case. FTPHandler Objects ------------------ `FTPHandler.ftp_open(req)` Open the FTP file indicated by *req*. The login is always done with empty username and password. CacheFTPHandler Objects ----------------------- [`CacheFTPHandler`](#urllib.request.CacheFTPHandler "urllib.request.CacheFTPHandler") objects are [`FTPHandler`](#urllib.request.FTPHandler "urllib.request.FTPHandler") objects with the following additional methods: `CacheFTPHandler.setTimeout(t)` Set timeout of connections to *t* seconds. `CacheFTPHandler.setMaxConns(m)` Set maximum number of cached connections to *m*. UnknownHandler Objects ---------------------- `UnknownHandler.unknown_open()` Raise a [`URLError`](urllib.error#urllib.error.URLError "urllib.error.URLError") exception. HTTPErrorProcessor Objects -------------------------- `HTTPErrorProcessor.http_response(request, response)` Process HTTP error responses. For 200 error codes, the response object is returned immediately. For non-200 error codes, this simply passes the job on to the `http_error_<type>()` handler methods, via [`OpenerDirector.error()`](#urllib.request.OpenerDirector.error "urllib.request.OpenerDirector.error"). Eventually, [`HTTPDefaultErrorHandler`](#urllib.request.HTTPDefaultErrorHandler "urllib.request.HTTPDefaultErrorHandler") will raise an [`HTTPError`](urllib.error#urllib.error.HTTPError "urllib.error.HTTPError") if no other handler handles the error. `HTTPErrorProcessor.https_response(request, response)` Process HTTPS error responses. The behavior is same as [`http_response()`](#urllib.request.HTTPErrorProcessor.http_response "urllib.request.HTTPErrorProcessor.http_response"). Examples -------- In addition to the examples below, more examples are given in [HOWTO Fetch Internet Resources Using The urllib Package](../howto/urllib2#urllib-howto). This example gets the python.org main page and displays the first 300 bytes of it. ``` >>> import urllib.request >>> with urllib.request.urlopen('http://www.python.org/') as f: ... print(f.read(300)) ... b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n <meta http-equiv="content-type" content="text/html; charset=utf-8" />\n <title>Python Programming ' ``` Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the HTTP server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding. The following W3C document, <https://www.w3.org/International/O-charset>, lists the various ways in which an (X)HTML or an XML document could have specified its encoding information. As the python.org website uses *utf-8* encoding as specified in its meta tag, we will use the same for decoding the bytes object. ``` >>> with urllib.request.urlopen('http://www.python.org/') as f: ... print(f.read(100).decode('utf-8')) ... <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm ``` It is also possible to achieve the same result without using the [context manager](../glossary#term-context-manager) approach. ``` >>> import urllib.request >>> f = urllib.request.urlopen('http://www.python.org/') >>> print(f.read(100).decode('utf-8')) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm ``` In the following example, we are sending a data-stream to the stdin of a CGI and reading the data it returns to us. Note that this example will only work when the Python installation supports SSL. ``` >>> import urllib.request >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi', ... data=b'This data is passed to stdin of the CGI') >>> with urllib.request.urlopen(req) as f: ... print(f.read().decode('utf-8')) ... Got Data: "This data is passed to stdin of the CGI" ``` The code for the sample CGI used in the above example is: ``` #!/usr/bin/env python import sys data = sys.stdin.read() print('Content-type: text/plain\n\nGot Data: "%s"' % data) ``` Here is an example of doing a `PUT` request using [`Request`](#urllib.request.Request "urllib.request.Request"): ``` import urllib.request DATA = b'some data' req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT') with urllib.request.urlopen(req) as f: pass print(f.status) print(f.reason) ``` Use of Basic HTTP Authentication: ``` import urllib.request # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib.request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib.request.install_opener(opener) urllib.request.urlopen('http://www.example.com/login.html') ``` [`build_opener()`](#urllib.request.build_opener "urllib.request.build_opener") provides many handlers by default, including a [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler"). By default, [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") uses the environment variables named `<scheme>_proxy`, where `<scheme>` is the URL scheme involved. For example, the `http_proxy` environment variable is read to obtain the HTTP proxy’s URL. This example replaces the default [`ProxyHandler`](#urllib.request.ProxyHandler "urllib.request.ProxyHandler") with one that uses programmatically-supplied proxy URLs, and adds proxy authorization support with [`ProxyBasicAuthHandler`](#urllib.request.ProxyBasicAuthHandler "urllib.request.ProxyBasicAuthHandler"). ``` proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) # This time, rather than install the OpenerDirector, we use it directly: opener.open('http://www.example.com/login.html') ``` Adding HTTP headers: Use the *headers* argument to the [`Request`](#urllib.request.Request "urllib.request.Request") constructor, or: ``` import urllib.request req = urllib.request.Request('http://www.example.com/') req.add_header('Referer', 'http://www.python.org/') # Customize the default User-Agent header value: req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)') r = urllib.request.urlopen(req) ``` [`OpenerDirector`](#urllib.request.OpenerDirector "urllib.request.OpenerDirector") automatically adds a *User-Agent* header to every [`Request`](#urllib.request.Request "urllib.request.Request"). To change this: ``` import urllib.request opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] opener.open('http://www.example.com/') ``` Also, remember that a few standard headers (*Content-Length*, *Content-Type* and *Host*) are added when the [`Request`](#urllib.request.Request "urllib.request.Request") is passed to [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") (or [`OpenerDirector.open()`](#urllib.request.OpenerDirector.open "urllib.request.OpenerDirector.open")). Here is an example session that uses the `GET` method to retrieve a URL containing parameters: ``` >>> import urllib.request >>> import urllib.parse >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params >>> with urllib.request.urlopen(url) as f: ... print(f.read().decode('utf-8')) ... ``` The following example uses the `POST` method instead. Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data: ``` >>> import urllib.request >>> import urllib.parse >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> data = data.encode('ascii') >>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f: ... print(f.read().decode('utf-8')) ... ``` The following example uses an explicitly specified HTTP proxy, overriding environment settings: ``` >>> import urllib.request >>> proxies = {'http': 'http://proxy.example.com:8080/'} >>> opener = urllib.request.FancyURLopener(proxies) >>> with opener.open("http://www.python.org") as f: ... f.read().decode('utf-8') ... ``` The following example uses no proxies at all, overriding environment settings: ``` >>> import urllib.request >>> opener = urllib.request.FancyURLopener({}) >>> with opener.open("http://www.python.org/") as f: ... f.read().decode('utf-8') ... ``` Legacy interface ---------------- The following functions and classes are ported from the Python 2 module `urllib` (as opposed to `urllib2`). They might become deprecated at some point in the future. `urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)` Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple `(filename, headers)` where *filename* is the local file name under which the object can be found, and *headers* is whatever the `info()` method of the object returned by [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") returned (for a remote object). Exceptions are the same as for [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be `-1` on older FTP servers which do not return a file size in response to a retrieval request. The following example illustrates the most common usage scenario: ``` >>> import urllib.request >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/') >>> html = open(local_filename) >>> html.close() ``` If the *url* uses the `http:` scheme identifier, the optional *data* argument may be given to specify a `POST` request (normally the request type is `GET`). The *data* argument must be a bytes object in standard *application/x-www-form-urlencoded* format; see the [`urllib.parse.urlencode()`](urllib.parse#urllib.parse.urlencode "urllib.parse.urlencode") function. [`urlretrieve()`](#urllib.request.urlretrieve "urllib.request.urlretrieve") will raise `ContentTooShortError` when it detects that the amount of data available was less than the expected amount (which is the size reported by a *Content-Length* header). This can occur, for example, when the download is interrupted. The *Content-Length* is treated as a lower bound: if there’s more data to read, urlretrieve reads more data, but if less data is available, it raises the exception. You can still retrieve the downloaded data in this case, it is stored in the `content` attribute of the exception instance. If no *Content-Length* header was supplied, urlretrieve can not check the size of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. `urllib.request.urlcleanup()` Cleans up temporary files that may have been left behind by previous calls to [`urlretrieve()`](#urllib.request.urlretrieve "urllib.request.urlretrieve"). `class urllib.request.URLopener(proxies=None, **x509)` Deprecated since version 3.3. Base class for opening and reading URLs. Unless you need to support opening objects using schemes other than `http:`, `ftp:`, or `file:`, you probably want to use [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener"). By default, the [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener") class sends a *User-Agent* header of `urllib/VVV`, where *VVV* is the [`urllib`](urllib#module-urllib "urllib") version number. Applications can define their own *User-Agent* header by subclassing [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener") or [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener") and setting the class attribute [`version`](#urllib.request.URLopener.version "urllib.request.URLopener.version") to an appropriate string value in the subclass definition. The optional *proxies* parameter should be a dictionary mapping scheme names to proxy URLs, where an empty dictionary turns proxies off completely. Its default value is `None`, in which case environmental proxy settings will be used if present, as discussed in the definition of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"), above. Additional keyword parameters, collected in *x509*, may be used for authentication of the client when using the `https:` scheme. The keywords *key\_file* and *cert\_file* are supported to provide an SSL key and certificate; both are needed to support client authentication. [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener") objects will raise an [`OSError`](exceptions#OSError "OSError") exception if the server returns an error code. `open(fullurl, data=None)` Open *fullurl* using the appropriate protocol. This method sets up cache and proxy information, then calls the appropriate open method with its input arguments. If the scheme is not recognized, [`open_unknown()`](#urllib.request.URLopener.open_unknown "urllib.request.URLopener.open_unknown") is called. The *data* argument has the same meaning as the *data* argument of [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen"). This method always quotes *fullurl* using [`quote()`](urllib.parse#urllib.parse.quote "urllib.parse.quote"). `open_unknown(fullurl, data=None)` Overridable interface to open unknown URL types. `retrieve(url, filename=None, reporthook=None, data=None)` Retrieves the contents of *url* and places it in *filename*. The return value is a tuple consisting of a local filename and either an [`email.message.Message`](email.compat32-message#email.message.Message "email.message.Message") object containing the response headers (for remote URLs) or `None` (for local URLs). The caller must then open and read the contents of *filename*. If *filename* is not given and the URL refers to a local file, the input filename is returned. If the URL is non-local and *filename* is not given, the filename is the output of [`tempfile.mktemp()`](tempfile#tempfile.mktemp "tempfile.mktemp") with a suffix that matches the suffix of the last path component of the input URL. If *reporthook* is given, it must be a function accepting three numeric parameters: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start and after each chunk of data is read from the network. *reporthook* is ignored for local URLs. If the *url* uses the `http:` scheme identifier, the optional *data* argument may be given to specify a `POST` request (normally the request type is `GET`). The *data* argument must in standard *application/x-www-form-urlencoded* format; see the [`urllib.parse.urlencode()`](urllib.parse#urllib.parse.urlencode "urllib.parse.urlencode") function. `version` Variable that specifies the user agent of the opener object. To get [`urllib`](urllib#module-urllib "urllib") to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor. `class urllib.request.FancyURLopener(...)` Deprecated since version 3.3. [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener") subclasses [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener") providing default handling for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x response codes listed above, the *Location* header is used to fetch the actual URL. For 401 response codes (authentication required), basic HTTP authentication is performed. For the 30x response codes, recursion is bounded by the value of the *maxtries* attribute, which defaults to 10. For all other response codes, the method `http_error_default()` is called which you can override in subclasses to handle the error appropriately. Note According to the letter of [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html), 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and [`urllib`](urllib#module-urllib "urllib") reproduces this behaviour. The parameters to the constructor are the same as those for [`URLopener`](#urllib.request.URLopener "urllib.request.URLopener"). Note When performing basic authentication, a [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener") instance calls its [`prompt_user_passwd()`](#urllib.request.FancyURLopener.prompt_user_passwd "urllib.request.FancyURLopener.prompt_user_passwd") method. The default implementation asks the users for the required information on the controlling terminal. A subclass may override this method to support more appropriate behavior if needed. The [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener") class offers one additional method that should be overloaded to provide the appropriate behavior: `prompt_user_passwd(host, realm)` Return information needed to authenticate the user at the given host in the specified security realm. The return value should be a tuple, `(user, password)`, which can be used for basic authentication. The implementation prompts for this information on the terminal; an application should override this method to use an appropriate interaction model in the local environment. urllib.request Restrictions --------------------------- * Currently, only the following protocols are supported: HTTP (versions 0.9 and 1.0), FTP, local files, and data URLs. Changed in version 3.4: Added support for data URLs. * The caching feature of [`urlretrieve()`](#urllib.request.urlretrieve "urllib.request.urlretrieve") has been disabled until someone finds the time to hack proper processing of Expiration time headers. * There should be a function to query whether a particular URL is in the cache. * For backward compatibility, if a URL appears to point to a local file but the file can’t be opened, the URL is re-interpreted using the FTP protocol. This can sometimes cause confusing error messages. * The [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") and [`urlretrieve()`](#urllib.request.urlretrieve "urllib.request.urlretrieve") functions can cause arbitrarily long delays while waiting for a network connection to be set up. This means that it is difficult to build an interactive Web client using these functions without using threads. * The data returned by [`urlopen()`](#urllib.request.urlopen "urllib.request.urlopen") or [`urlretrieve()`](#urllib.request.urlretrieve "urllib.request.urlretrieve") is the raw data returned by the server. This may be binary data (such as an image), plain text or (for example) HTML. The HTTP protocol provides type information in the reply header, which can be inspected by looking at the *Content-Type* header. If the returned data is HTML, you can use the module [`html.parser`](html.parser#module-html.parser "html.parser: A simple parser that can handle HTML and XHTML.") to parse it. * The code handling the FTP protocol cannot differentiate between a file and a directory. This can lead to unexpected behavior when attempting to read a URL that points to a file that is not accessible. If the URL ends in a `/`, it is assumed to refer to a directory and will be handled accordingly. But if an attempt to read a file leads to a 550 error (meaning the URL cannot be found or is not accessible, often for permission reasons), then the path is treated as a directory in order to handle the case when a directory is specified by a URL but the trailing `/` has been left off. This can cause misleading results when you try to fetch a file whose read permissions make it inaccessible; the FTP code will try to read it, fail with a 550 error, and then perform a directory listing for the unreadable file. If fine-grained control is needed, consider using the [`ftplib`](ftplib#module-ftplib "ftplib: FTP protocol client (requires sockets).") module, subclassing [`FancyURLopener`](#urllib.request.FancyURLopener "urllib.request.FancyURLopener"), or changing *\_urlopener* to meet your needs.
programming_docs
python http.cookiejar — Cookie handling for HTTP clients http.cookiejar — Cookie handling for HTTP clients ================================================= **Source code:** [Lib/http/cookiejar.py](https://github.com/python/cpython/tree/3.9/Lib/http/cookiejar.py) The [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – *cookies* – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests. Both the regular Netscape cookie protocol and the protocol defined by [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) are handled. RFC 2965 handling is switched off by default. [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookies are parsed as Netscape cookies and subsequently treated either as Netscape or RFC 2965 cookies according to the ‘policy’ in effect. Note that the great majority of cookies on the Internet are Netscape cookies. [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") attempts to follow the de-facto Netscape cookie protocol (which differs substantially from that set out in the original Netscape specification), including taking note of the `max-age` and `port` cookie-attributes introduced with RFC 2965. Note The various named parameters found in *Set-Cookie* and *Set-Cookie2* headers (eg. `domain` and `expires`) are conventionally referred to as *attributes*. To distinguish them from Python attributes, the documentation for this module uses the term *cookie-attribute* instead. The module defines the following exception: `exception http.cookiejar.LoadError` Instances of [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") raise this exception on failure to load cookies from a file. [`LoadError`](#http.cookiejar.LoadError "http.cookiejar.LoadError") is a subclass of [`OSError`](exceptions#OSError "OSError"). Changed in version 3.3: LoadError was made a subclass of [`OSError`](exceptions#OSError "OSError") instead of [`IOError`](exceptions#IOError "IOError"). The following classes are provided: `class http.cookiejar.CookieJar(policy=None)` *policy* is an object implementing the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") interface. The [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database. `class http.cookiejar.FileCookieJar(filename, delayload=None, policy=None)` *policy* is an object implementing the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") interface. For the other arguments, see the documentation for the corresponding attributes. A [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are **NOT** loaded from the named file until either the [`load()`](#http.cookiejar.FileCookieJar.load "http.cookiejar.FileCookieJar.load") or [`revert()`](#http.cookiejar.FileCookieJar.revert "http.cookiejar.FileCookieJar.revert") method is called. Subclasses of this class are documented in section [FileCookieJar subclasses and co-operation with web browsers](#file-cookie-jar-classes). Changed in version 3.8: The filename parameter supports a [path-like object](../glossary#term-path-like-object). `class http.cookiejar.CookiePolicy` This class is responsible for deciding whether each cookie should be accepted from / returned to the server. `class http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=("https", "wss"))` Constructor arguments should be passed as keyword arguments only. *blocked\_domains* is a sequence of domain names that we never accept cookies from, nor return cookies to. *allowed\_domains* if not [`None`](constants#None "None"), this is a sequence of the only domains for which we accept and return cookies. *secure\_protocols* is a sequence of protocols for which secure cookies can be added to. By default *https* and *wss* (secure websocket) are considered secure protocols. For all other arguments, see the documentation for [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") and [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") objects. [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") implements the standard accept / reject rules for Netscape and [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) cookies. By default, [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookies (ie. cookies received in a *Set-Cookie* header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or [`rfc2109_as_netscape`](#http.cookiejar.DefaultCookiePolicy.rfc2109_as_netscape "http.cookiejar.DefaultCookiePolicy.rfc2109_as_netscape") is `True`, RFC 2109 cookies are ‘downgraded’ by the [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") instance to Netscape cookies, by setting the `version` attribute of the [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instance to 0. [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") also provides some parameters to allow some fine-tuning of policy. `class http.cookiejar.Cookie` This class represents Netscape, [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) and [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) cookies. It is not expected that users of [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") construct their own [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instances. Instead, if necessary, call `make_cookies()` on a [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") instance. See also `Module` [`urllib.request`](urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs.") URL opening with automatic cookie handling. `Module` [`http.cookies`](http.cookies#module-http.cookies "http.cookies: Support for HTTP state management (cookies).") HTTP cookie classes, principally useful for server-side code. The [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") and [`http.cookies`](http.cookies#module-http.cookies "http.cookies: Support for HTTP state management (cookies).") modules do not depend on each other. <https://curl.se/rfc/cookie_spec.html> The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the ‘Netscape cookie protocol’ implemented by all the major browsers (and [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.")) only bears a passing resemblance to the one sketched out in `cookie_spec.html`. [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) - HTTP State Management Mechanism Obsoleted by [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html). Uses *Set-Cookie* with version=1. [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) - HTTP State Management Mechanism The Netscape protocol with the bugs fixed. Uses *Set-Cookie2* in place of *Set-Cookie*. Not widely used. <http://kristol.org/cookie/errata.html> Unfinished errata to [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html). [**RFC 2964**](https://tools.ietf.org/html/rfc2964.html) - Use of HTTP State Management CookieJar and FileCookieJar Objects ----------------------------------- [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") objects support the [iterator](../glossary#term-iterator) protocol for iterating over contained [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") objects. [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") has the following methods: `CookieJar.add_cookie_header(request)` Add correct *Cookie* header to *request*. If policy allows (ie. the `rfc2965` and `hide_cookie2` attributes of the [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar")’s [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") instance are true and false respectively), the *Cookie2* header is also added when appropriate. The *request* object (usually a [`urllib.request.Request`](urllib.request#urllib.request.Request "urllib.request.Request") instance) must support the methods `get_full_url()`, `get_host()`, `get_type()`, `unverifiable()`, `has_header()`, `get_header()`, `header_items()`, `add_unredirected_header()` and `origin_req_host` attribute as documented by [`urllib.request`](urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs."). Changed in version 3.3: *request* object needs `origin_req_host` attribute. Dependency on a deprecated method `get_origin_req_host()` has been removed. `CookieJar.extract_cookies(response, request)` Extract cookies from HTTP *response* and store them in the [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar"), where allowed by policy. The [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") will look for allowable *Set-Cookie* and *Set-Cookie2* headers in the *response* argument, and store cookies as appropriate (subject to the [`CookiePolicy.set_ok()`](#http.cookiejar.CookiePolicy.set_ok "http.cookiejar.CookiePolicy.set_ok") method’s approval). The *response* object (usually the result of a call to [`urllib.request.urlopen()`](urllib.request#urllib.request.urlopen "urllib.request.urlopen"), or similar) should support an `info()` method, which returns an [`email.message.Message`](email.compat32-message#email.message.Message "email.message.Message") instance. The *request* object (usually a [`urllib.request.Request`](urllib.request#urllib.request.Request "urllib.request.Request") instance) must support the methods `get_full_url()`, `get_host()`, `unverifiable()`, and `origin_req_host` attribute, as documented by [`urllib.request`](urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs."). The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set. Changed in version 3.3: *request* object needs `origin_req_host` attribute. Dependency on a deprecated method `get_origin_req_host()` has been removed. `CookieJar.set_policy(policy)` Set the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") instance to be used. `CookieJar.make_cookies(response, request)` Return sequence of [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") objects extracted from *response* object. See the documentation for [`extract_cookies()`](#http.cookiejar.CookieJar.extract_cookies "http.cookiejar.CookieJar.extract_cookies") for the interfaces required of the *response* and *request* arguments. `CookieJar.set_cookie_if_ok(cookie, request)` Set a [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") if policy says it’s OK to do so. `CookieJar.set_cookie(cookie)` Set a [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie"), without checking with policy to see whether or not it should be set. `CookieJar.clear([domain[, path[, name]]])` Clear some cookies. If invoked without arguments, clear all cookies. If given a single argument, only cookies belonging to that *domain* will be removed. If given two arguments, cookies belonging to the specified *domain* and URL *path* are removed. If given three arguments, then the cookie with the specified *domain*, *path* and *name* is removed. Raises [`KeyError`](exceptions#KeyError "KeyError") if no matching cookie exists. `CookieJar.clear_session_cookies()` Discard all session cookies. Discards all contained cookies that have a true `discard` attribute (usually because they had either no `max-age` or `expires` cookie-attribute, or an explicit `discard` cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window. Note that the `save()` method won’t save session cookies anyway, unless you ask otherwise by passing a true *ignore\_discard* argument. [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") implements the following additional methods: `FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)` Save cookies to a file. This base class raises [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). Subclasses may leave this method unimplemented. *filename* is the name of file in which to save cookies. If *filename* is not specified, `self.filename` is used (whose default is the value passed to the constructor, if any); if `self.filename` is [`None`](constants#None "None"), [`ValueError`](exceptions#ValueError "ValueError") is raised. *ignore\_discard*: save even cookies set to be discarded. *ignore\_expires*: save even cookies that have expired The file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the [`load()`](#http.cookiejar.FileCookieJar.load "http.cookiejar.FileCookieJar.load") or [`revert()`](#http.cookiejar.FileCookieJar.revert "http.cookiejar.FileCookieJar.revert") methods. `FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)` Load cookies from a file. Old cookies are kept unless overwritten by newly loaded ones. Arguments are as for [`save()`](#http.cookiejar.FileCookieJar.save "http.cookiejar.FileCookieJar.save"). The named file must be in the format understood by the class, or [`LoadError`](#http.cookiejar.LoadError "http.cookiejar.LoadError") will be raised. Also, [`OSError`](exceptions#OSError "OSError") may be raised, for example if the file does not exist. Changed in version 3.3: [`IOError`](exceptions#IOError "IOError") used to be raised, it is now an alias of [`OSError`](exceptions#OSError "OSError"). `FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)` Clear all cookies and reload cookies from a saved file. [`revert()`](#http.cookiejar.FileCookieJar.revert "http.cookiejar.FileCookieJar.revert") can raise the same exceptions as [`load()`](#http.cookiejar.FileCookieJar.load "http.cookiejar.FileCookieJar.load"). If there is a failure, the object’s state will not be altered. [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") instances have the following public attributes: `FileCookieJar.filename` Filename of default file in which to keep cookies. This attribute may be assigned to. `FileCookieJar.delayload` If true, load cookies lazily from disk. This attribute should not be assigned to. This is only a hint, since this only affects performance, not behaviour (unless the cookies on disk are changing). A [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") object may ignore it. None of the [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") classes included in the standard library lazily loads cookies. FileCookieJar subclasses and co-operation with web browsers ----------------------------------------------------------- The following [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") subclasses are provided for reading and writing. `class http.cookiejar.MozillaCookieJar(filename, delayload=None, policy=None)` A [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") that can load from and save cookies to disk in the Mozilla `cookies.txt` file format (which is also used by the Lynx and Netscape browsers). Note This loses information about [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) cookies, and also about newer or non-standard cookie-attributes such as `port`. Warning Back up your cookies before saving if you have cookies whose loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip). Also note that cookies saved while Mozilla is running will get clobbered by Mozilla. `class http.cookiejar.LWPCookieJar(filename, delayload=None, policy=None)` A [`FileCookieJar`](#http.cookiejar.FileCookieJar "http.cookiejar.FileCookieJar") that can load from and save cookies to disk in format compatible with the libwww-perl library’s `Set-Cookie3` file format. This is convenient if you want to store cookies in a human-readable file. Changed in version 3.8: The filename parameter supports a [path-like object](../glossary#term-path-like-object). CookiePolicy Objects -------------------- Objects implementing the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") interface have the following methods: `CookiePolicy.set_ok(cookie, request)` Return boolean value indicating whether cookie should be accepted from server. *cookie* is a [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instance. *request* is an object implementing the interface defined by the documentation for [`CookieJar.extract_cookies()`](#http.cookiejar.CookieJar.extract_cookies "http.cookiejar.CookieJar.extract_cookies"). `CookiePolicy.return_ok(cookie, request)` Return boolean value indicating whether cookie should be returned to server. *cookie* is a [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instance. *request* is an object implementing the interface defined by the documentation for [`CookieJar.add_cookie_header()`](#http.cookiejar.CookieJar.add_cookie_header "http.cookiejar.CookieJar.add_cookie_header"). `CookiePolicy.domain_return_ok(domain, request)` Return `False` if cookies should not be returned, given cookie domain. This method is an optimization. It removes the need for checking every cookie with a particular domain (which might involve reading many files). Returning true from [`domain_return_ok()`](#http.cookiejar.CookiePolicy.domain_return_ok "http.cookiejar.CookiePolicy.domain_return_ok") and [`path_return_ok()`](#http.cookiejar.CookiePolicy.path_return_ok "http.cookiejar.CookiePolicy.path_return_ok") leaves all the work to [`return_ok()`](#http.cookiejar.CookiePolicy.return_ok "http.cookiejar.CookiePolicy.return_ok"). If [`domain_return_ok()`](#http.cookiejar.CookiePolicy.domain_return_ok "http.cookiejar.CookiePolicy.domain_return_ok") returns true for the cookie domain, [`path_return_ok()`](#http.cookiejar.CookiePolicy.path_return_ok "http.cookiejar.CookiePolicy.path_return_ok") is called for the cookie path. Otherwise, [`path_return_ok()`](#http.cookiejar.CookiePolicy.path_return_ok "http.cookiejar.CookiePolicy.path_return_ok") and [`return_ok()`](#http.cookiejar.CookiePolicy.return_ok "http.cookiejar.CookiePolicy.return_ok") are never called for that cookie domain. If [`path_return_ok()`](#http.cookiejar.CookiePolicy.path_return_ok "http.cookiejar.CookiePolicy.path_return_ok") returns true, [`return_ok()`](#http.cookiejar.CookiePolicy.return_ok "http.cookiejar.CookiePolicy.return_ok") is called with the [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") object itself for a full check. Otherwise, [`return_ok()`](#http.cookiejar.CookiePolicy.return_ok "http.cookiejar.CookiePolicy.return_ok") is never called for that cookie path. Note that [`domain_return_ok()`](#http.cookiejar.CookiePolicy.domain_return_ok "http.cookiejar.CookiePolicy.domain_return_ok") is called for every *cookie* domain, not just for the *request* domain. For example, the function might be called with both `".example.com"` and `"www.example.com"` if the request domain is `"www.example.com"`. The same goes for [`path_return_ok()`](#http.cookiejar.CookiePolicy.path_return_ok "http.cookiejar.CookiePolicy.path_return_ok"). The *request* argument is as documented for [`return_ok()`](#http.cookiejar.CookiePolicy.return_ok "http.cookiejar.CookiePolicy.return_ok"). `CookiePolicy.path_return_ok(path, request)` Return `False` if cookies should not be returned, given cookie path. See the documentation for [`domain_return_ok()`](#http.cookiejar.CookiePolicy.domain_return_ok "http.cookiejar.CookiePolicy.domain_return_ok"). In addition to implementing the methods above, implementations of the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") interface must also supply the following attributes, indicating which protocols should be used, and how. All of these attributes may be assigned to. `CookiePolicy.netscape` Implement Netscape protocol. `CookiePolicy.rfc2965` Implement [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) protocol. `CookiePolicy.hide_cookie2` Don’t add *Cookie2* header to requests (the presence of this header indicates to the server that we understand [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) cookies). The most useful way to define a [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") class is by subclassing from [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") and overriding some or all of the methods above. [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") itself may be used as a ‘null policy’ to allow setting and receiving any and all cookies (this is unlikely to be useful). DefaultCookiePolicy Objects --------------------------- Implements the standard rules for accepting and returning cookies. Both [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) and Netscape cookies are covered. RFC 2965 handling is switched off by default. The easiest way to provide your own policy is to override this class and call its methods in your overridden implementations before adding your own additional checks: ``` import http.cookiejar class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy): def set_ok(self, cookie, request): if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request): return False if i_dont_want_to_store_this_cookie(cookie): return False return True ``` In addition to the features required to implement the [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") interface, this class allows you to block and allow domains from setting and receiving cookies. There are also some strictness switches that allow you to tighten up the rather loose Netscape protocol rules a little bit (at the cost of blocking some benign cookies). A domain blacklist and whitelist is provided (both off by default). Only domains not in the blacklist and present in the whitelist (if the whitelist is active) participate in cookie setting and returning. Use the *blocked\_domains* constructor argument, and `blocked_domains()` and `set_blocked_domains()` methods (and the corresponding argument and methods for *allowed\_domains*). If you set a whitelist, you can turn it off again by setting it to [`None`](constants#None "None"). Domains in block or allow lists that do not start with a dot must equal the cookie domain to be matched. For example, `"example.com"` matches a blacklist entry of `"example.com"`, but `"www.example.com"` does not. Domains that do start with a dot are matched by more specific domains too. For example, both `"www.example.com"` and `"www.coyote.example.com"` match `".example.com"` (but `"example.com"` itself does not). IP addresses are an exception, and must match exactly. For example, if blocked\_domains contains `"192.168.1.2"` and `".168.1.2"`, 192.168.1.2 is blocked, but 193.168.1.2 is not. [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") implements the following additional methods: `DefaultCookiePolicy.blocked_domains()` Return the sequence of blocked domains (as a tuple). `DefaultCookiePolicy.set_blocked_domains(blocked_domains)` Set the sequence of blocked domains. `DefaultCookiePolicy.is_blocked(domain)` Return whether *domain* is on the blacklist for setting or receiving cookies. `DefaultCookiePolicy.allowed_domains()` Return [`None`](constants#None "None"), or the sequence of allowed domains (as a tuple). `DefaultCookiePolicy.set_allowed_domains(allowed_domains)` Set the sequence of allowed domains, or [`None`](constants#None "None"). `DefaultCookiePolicy.is_not_allowed(domain)` Return whether *domain* is not on the whitelist for setting or receiving cookies. [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy") instances have the following attributes, which are all initialised from the constructor arguments of the same name, and which may all be assigned to. `DefaultCookiePolicy.rfc2109_as_netscape` If true, request that the [`CookieJar`](#http.cookiejar.CookieJar "http.cookiejar.CookieJar") instance downgrade [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookies (ie. cookies received in a *Set-Cookie* header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instance to 0. The default value is [`None`](constants#None "None"), in which case RFC 2109 cookies are downgraded if and only if [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) handling is turned off. Therefore, RFC 2109 cookies are downgraded by default. General strictness switches: `DefaultCookiePolicy.strict_domain` Don’t allow sites to set two-component domains with country-code top-level domains like `.co.uk`, `.gov.uk`, `.co.nz`.etc. This is far from perfect and isn’t guaranteed to work! [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) protocol strictness switches: `DefaultCookiePolicy.strict_rfc2965_unverifiable` Follow [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) rules on unverifiable transactions (usually, an unverifiable transaction is one resulting from a redirect or a request for an image hosted on another site). If this is false, cookies are *never* blocked on the basis of verifiability Netscape protocol strictness switches: `DefaultCookiePolicy.strict_ns_unverifiable` Apply [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) rules on unverifiable transactions even to Netscape cookies. `DefaultCookiePolicy.strict_ns_domain` Flags indicating how strict to be with domain-matching rules for Netscape cookies. See below for acceptable values. `DefaultCookiePolicy.strict_ns_set_initial_dollar` Ignore cookies in Set-Cookie: headers that have names starting with `'$'`. `DefaultCookiePolicy.strict_ns_set_path` Don’t allow setting cookies whose path doesn’t path-match request URI. `strict_ns_domain` is a collection of flags. Its value is constructed by or-ing together (for example, `DomainStrictNoDots|DomainStrictNonDomain` means both flags are set). `DefaultCookiePolicy.DomainStrictNoDots` When setting cookies, the ‘host prefix’ must not contain a dot (eg. `www.foo.bar.com` can’t set a cookie for `.bar.com`, because `www.foo` contains a dot). `DefaultCookiePolicy.DomainStrictNonDomain` Cookies that did not explicitly specify a `domain` cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg. `spam.example.com` won’t be returned cookies from `example.com` that had no `domain` cookie-attribute). `DefaultCookiePolicy.DomainRFC2965Match` When setting cookies, require a full [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) domain-match. The following attributes are provided for convenience, and are the most useful combinations of the above flags: `DefaultCookiePolicy.DomainLiberal` Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched off). `DefaultCookiePolicy.DomainStrict` Equivalent to `DomainStrictNoDots|DomainStrictNonDomain`. Cookie Objects -------------- [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") instances have Python attributes roughly corresponding to the standard cookie-attributes specified in the various cookie standards. The correspondence is not one-to-one, because there are complicated rules for assigning default values, because the `max-age` and `expires` cookie-attributes contain equivalent information, and because [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookies may be ‘downgraded’ by [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") from version 1 to version 0 (Netscape) cookies. Assignment to these attributes should not be necessary other than in rare circumstances in a [`CookiePolicy`](#http.cookiejar.CookiePolicy "http.cookiejar.CookiePolicy") method. The class does not enforce internal consistency, so you should know what you’re doing if you do that. `Cookie.version` Integer or [`None`](constants#None "None"). Netscape cookies have [`version`](#http.cookiejar.Cookie.version "http.cookiejar.Cookie.version") 0. [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) and [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookies have a `version` cookie-attribute of 1. However, note that [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case [`version`](#http.cookiejar.Cookie.version "http.cookiejar.Cookie.version") is 0. `Cookie.name` Cookie name (a string). `Cookie.value` Cookie value (a string), or [`None`](constants#None "None"). `Cookie.port` String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or [`None`](constants#None "None"). `Cookie.path` Cookie path (a string, eg. `'/acme/rocket_launchers'`). `Cookie.secure` `True` if cookie should only be returned over a secure connection. `Cookie.expires` Integer expiry date in seconds since epoch, or [`None`](constants#None "None"). See also the [`is_expired()`](#http.cookiejar.Cookie.is_expired "http.cookiejar.Cookie.is_expired") method. `Cookie.discard` `True` if this is a session cookie. `Cookie.comment` String comment from the server explaining the function of this cookie, or [`None`](constants#None "None"). `Cookie.comment_url` URL linking to a comment from the server explaining the function of this cookie, or [`None`](constants#None "None"). `Cookie.rfc2109` `True` if this cookie was received as an [**RFC 2109**](https://tools.ietf.org/html/rfc2109.html) cookie (ie. the cookie arrived in a *Set-Cookie* header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided because [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies.") may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case [`version`](#http.cookiejar.Cookie.version "http.cookiejar.Cookie.version") is 0. `Cookie.port_specified` `True` if a port or set of ports was explicitly specified by the server (in the *Set-Cookie* / *Set-Cookie2* header). `Cookie.domain_specified` `True` if a domain was explicitly specified by the server. `Cookie.domain_initial_dot` `True` if the domain explicitly specified by the server began with a dot (`'.'`). Cookies may have additional non-standard cookie-attributes. These may be accessed using the following methods: `Cookie.has_nonstandard_attr(name)` Return `True` if cookie has the named cookie-attribute. `Cookie.get_nonstandard_attr(name, default=None)` If cookie has the named cookie-attribute, return its value. Otherwise, return *default*. `Cookie.set_nonstandard_attr(name, value)` Set the value of the named cookie-attribute. The [`Cookie`](#http.cookiejar.Cookie "http.cookiejar.Cookie") class also defines the following method: `Cookie.is_expired(now=None)` `True` if cookie has passed the time at which the server requested it should expire. If *now* is given (in seconds since the epoch), return whether the cookie has expired at the specified time. Examples -------- The first example shows the most common usage of [`http.cookiejar`](#module-http.cookiejar "http.cookiejar: Classes for automatic handling of HTTP cookies."): ``` import http.cookiejar, urllib.request cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") ``` This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx cookies (assumes Unix/Netscape convention for location of the cookies file): ``` import os, http.cookiejar, urllib.request cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt")) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") ``` The next example illustrates the use of [`DefaultCookiePolicy`](#http.cookiejar.DefaultCookiePolicy "http.cookiejar.DefaultCookiePolicy"). Turn on [**RFC 2965**](https://tools.ietf.org/html/rfc2965.html) cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned: ``` import urllib.request from http.cookiejar import CookieJar, DefaultCookiePolicy policy = DefaultCookiePolicy( rfc2965=True, strict_ns_domain=Policy.DomainStrict, blocked_domains=["ads.net", ".ads.net"]) cj = CookieJar(policy) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") ```
programming_docs
python colorsys — Conversions between color systems colorsys — Conversions between color systems ============================================ **Source code:** [Lib/colorsys.py](https://github.com/python/cpython/tree/3.9/Lib/colorsys.py) The [`colorsys`](#module-colorsys "colorsys: Conversion functions between RGB and other color systems.") module defines bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) color space used in computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1. See also More information about color spaces can be found at <https://poynton.ca/ColorFAQ.html> and <https://www.cambridgeincolour.com/tutorials/color-spaces.htm>. The [`colorsys`](#module-colorsys "colorsys: Conversion functions between RGB and other color systems.") module defines the following functions: `colorsys.rgb_to_yiq(r, g, b)` Convert the color from RGB coordinates to YIQ coordinates. `colorsys.yiq_to_rgb(y, i, q)` Convert the color from YIQ coordinates to RGB coordinates. `colorsys.rgb_to_hls(r, g, b)` Convert the color from RGB coordinates to HLS coordinates. `colorsys.hls_to_rgb(h, l, s)` Convert the color from HLS coordinates to RGB coordinates. `colorsys.rgb_to_hsv(r, g, b)` Convert the color from RGB coordinates to HSV coordinates. `colorsys.hsv_to_rgb(h, s, v)` Convert the color from HSV coordinates to RGB coordinates. Example: ``` >>> import colorsys >>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4) (0.5, 0.5, 0.4) >>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4) (0.2, 0.4, 0.4) ``` python select — Waiting for I/O completion select — Waiting for I/O completion =================================== This module provides access to the `select()` and `poll()` functions available in most operating systems, `devpoll()` available on Solaris and derivatives, `epoll()` available on Linux 2.5+ and `kqueue()` available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read. Note The [`selectors`](selectors#module-selectors "selectors: High-level I/O multiplexing.") module allows high-level and efficient I/O multiplexing, built upon the [`select`](#module-select "select: Wait for I/O completion on multiple streams.") module primitives. Users are encouraged to use the [`selectors`](selectors#module-selectors "selectors: High-level I/O multiplexing.") module instead, unless they want precise control over the OS-level primitives used. The module defines the following: `exception select.error` A deprecated alias of [`OSError`](exceptions#OSError "OSError"). Changed in version 3.3: Following [**PEP 3151**](https://www.python.org/dev/peps/pep-3151), this class was made an alias of [`OSError`](exceptions#OSError "OSError"). `select.devpoll()` (Only supported on Solaris and derivatives.) Returns a `/dev/poll` polling object; see section [/dev/poll Polling Objects](#devpoll-objects) below for the methods supported by devpoll objects. `devpoll()` objects are linked to the number of file descriptors allowed at the time of instantiation. If your program reduces this value, `devpoll()` will fail. If your program increases this value, `devpoll()` may return an incomplete list of active file descriptors. The new file descriptor is [non-inheritable](os#fd-inheritance). New in version 3.3. Changed in version 3.4: The new file descriptor is now non-inheritable. `select.epoll(sizehint=-1, flags=0)` (Only supported on Linux 2.5.44 and newer.) Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events. *sizehint* informs epoll about the expected number of events to be registered. It must be positive, or `-1` to use the default. It is only used on older systems where `epoll_create1()` is not available; otherwise it has no effect (though its value is still checked). *flags* is deprecated and completely ignored. However, when supplied, its value must be `0` or `select.EPOLL_CLOEXEC`, otherwise `OSError` is raised. See the [Edge and Level Trigger Polling (epoll) Objects](#epoll-objects) section below for the methods supported by epolling objects. `epoll` objects support the context management protocol: when used in a [`with`](../reference/compound_stmts#with) statement, the new file descriptor is automatically closed at the end of the block. The new file descriptor is [non-inheritable](os#fd-inheritance). Changed in version 3.3: Added the *flags* parameter. Changed in version 3.4: Support for the [`with`](../reference/compound_stmts#with) statement was added. The new file descriptor is now non-inheritable. Deprecated since version 3.4: The *flags* parameter. `select.EPOLL_CLOEXEC` is used by default now. Use [`os.set_inheritable()`](os#os.set_inheritable "os.set_inheritable") to make the file descriptor inheritable. `select.poll()` (Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section [Polling Objects](#poll-objects) below for the methods supported by polling objects. `select.kqueue()` (Only supported on BSD.) Returns a kernel queue object; see section [Kqueue Objects](#kqueue-objects) below for the methods supported by kqueue objects. The new file descriptor is [non-inheritable](os#fd-inheritance). Changed in version 3.4: The new file descriptor is now non-inheritable. `select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)` (Only supported on BSD.) Returns a kernel event object; see section [Kevent Objects](#kevent-objects) below for the methods supported by kevent objects. `select.select(rlist, wlist, xlist[, timeout])` This is a straightforward interface to the Unix `select()` system call. The first three arguments are iterables of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") returning such an integer: * *rlist*: wait until ready for reading * *wlist*: wait until ready for writing * *xlist*: wait for an “exceptional condition” (see the manual page for what your system considers such a condition) Empty iterables are allowed, but acceptance of three empty iterables is platform-dependent. (It is known to work on Unix but not on Windows.) The optional *timeout* argument specifies a time-out as a floating point number in seconds. When the *timeout* argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks. The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned. Among the acceptable object types in the iterables are Python [file objects](../glossary#term-file-object) (e.g. `sys.stdin`, or objects returned by [`open()`](functions#open "open") or [`os.popen()`](os#os.popen "os.popen")), socket objects returned by [`socket.socket()`](socket#socket.socket "socket.socket"). You may also define a *wrapper* class yourself, as long as it has an appropriate [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method (that really returns a file descriptor, not just a random integer). Note File objects on Windows are not acceptable, but sockets are. On Windows, the underlying `select()` function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale), instead of raising [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). `select.PIPE_BUF` The minimum number of bytes which can be written without blocking to a pipe when the pipe has been reported as ready for writing by [`select()`](#select.select "select.select"), [`poll()`](#select.poll "select.poll") or another interface in this module. This doesn’t apply to other kind of file-like objects such as sockets. This value is guaranteed by POSIX to be at least 512. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Unix New in version 3.2. `/dev/poll` Polling Objects ---------------------------- Solaris and derivatives have `/dev/poll`. While `select()` is O(highest file descriptor) and `poll()` is O(number of file descriptors), `/dev/poll` is O(active file descriptors). `/dev/poll` behaviour is very close to the standard `poll()` object. `devpoll.close()` Close the file descriptor of the polling object. New in version 3.4. `devpoll.closed` `True` if the polling object is closed. New in version 3.4. `devpoll.fileno()` Return the file descriptor number of the polling object. New in version 3.4. `devpoll.register(fd[, eventmask])` Register a file descriptor with the polling object. Future calls to the [`poll()`](#select.poll "select.poll") method will then check whether the file descriptor has any pending I/O events. *fd* can be either an integer, or an object with a [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method that returns an integer. File objects implement `fileno()`, so they can also be used as the argument. *eventmask* is an optional bitmask describing the type of events you want to check for. The constants are the same that with `poll()` object. The default value is a combination of the constants `POLLIN`, `POLLPRI`, and `POLLOUT`. Warning Registering a file descriptor that’s already registered is not an error, but the result is undefined. The appropriate action is to unregister or modify it first. This is an important difference compared with `poll()`. `devpoll.modify(fd[, eventmask])` This method does an [`unregister()`](#select.devpoll.unregister "select.devpoll.unregister") followed by a [`register()`](#select.devpoll.register "select.devpoll.register"). It is (a bit) more efficient that doing the same explicitly. `devpoll.unregister(fd)` Remove a file descriptor being tracked by a polling object. Just like the [`register()`](#select.devpoll.register "select.devpoll.register") method, *fd* can be an integer or an object with a [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method that returns an integer. Attempting to remove a file descriptor that was never registered is safely ignored. `devpoll.poll([timeout])` Polls the set of registered file descriptors, and returns a possibly-empty list containing `(fd, event)` 2-tuples for the descriptors that have events or errors to report. *fd* is the file descriptor, and *event* is a bitmask with bits set for the reported events for that descriptor — `POLLIN` for waiting input, `POLLOUT` to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If *timeout* is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If *timeout* is omitted, -1, or [`None`](constants#None "None"), the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale), instead of raising [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). Edge and Level Trigger Polling (epoll) Objects ---------------------------------------------- <https://linux.die.net/man/4/epoll> *eventmask* | Constant | Meaning | | --- | --- | | `EPOLLIN` | Available for read | | `EPOLLOUT` | Available for write | | `EPOLLPRI` | Urgent data for read | | `EPOLLERR` | Error condition happened on the assoc. fd | | `EPOLLHUP` | Hang up happened on the assoc. fd | | `EPOLLET` | Set Edge Trigger behavior, the default is Level Trigger behavior | | `EPOLLONESHOT` | Set one-shot behavior. After one event is pulled out, the fd is internally disabled | | `EPOLLEXCLUSIVE` | Wake only one epoll object when the associated fd has an event. The default (if this flag is not set) is to wake all epoll objects polling on a fd. | | `EPOLLRDHUP` | Stream socket peer closed connection or shut down writing half of connection. | | `EPOLLRDNORM` | Equivalent to `EPOLLIN` | | `EPOLLRDBAND` | Priority data band can be read. | | `EPOLLWRNORM` | Equivalent to `EPOLLOUT` | | `EPOLLWRBAND` | Priority data may be written. | | `EPOLLMSG` | Ignored. | New in version 3.6: `EPOLLEXCLUSIVE` was added. It’s only supported by Linux Kernel 4.5 or later. `epoll.close()` Close the control file descriptor of the epoll object. `epoll.closed` `True` if the epoll object is closed. `epoll.fileno()` Return the file descriptor number of the control fd. `epoll.fromfd(fd)` Create an epoll object from a given file descriptor. `epoll.register(fd[, eventmask])` Register a fd descriptor with the epoll object. `epoll.modify(fd, eventmask)` Modify a registered file descriptor. `epoll.unregister(fd)` Remove a registered file descriptor from the epoll object. Changed in version 3.9: The method no longer ignores the [`EBADF`](errno#errno.EBADF "errno.EBADF") error. `epoll.poll(timeout=None, maxevents=-1)` Wait for events. timeout in seconds (float) Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale), instead of raising [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). Polling Objects --------------- The `poll()` system call, supported on most Unix systems, provides better scalability for network servers that service many, many clients at the same time. `poll()` scales better because the system call only requires listing the file descriptors of interest, while `select()` builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be linearly scanned again. `select()` is O(highest file descriptor), while `poll()` is O(number of file descriptors). `poll.register(fd[, eventmask])` Register a file descriptor with the polling object. Future calls to the [`poll()`](#select.poll "select.poll") method will then check whether the file descriptor has any pending I/O events. *fd* can be either an integer, or an object with a [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method that returns an integer. File objects implement `fileno()`, so they can also be used as the argument. *eventmask* is an optional bitmask describing the type of events you want to check for, and can be a combination of the constants `POLLIN`, `POLLPRI`, and `POLLOUT`, described in the table below. If not specified, the default value used will check for all 3 types of events. | Constant | Meaning | | --- | --- | | `POLLIN` | There is data to read | | `POLLPRI` | There is urgent data to read | | `POLLOUT` | Ready for output: writing will not block | | `POLLERR` | Error condition of some sort | | `POLLHUP` | Hung up | | `POLLRDHUP` | Stream socket peer closed connection, or shut down writing half of connection | | `POLLNVAL` | Invalid request: descriptor not open | Registering a file descriptor that’s already registered is not an error, and has the same effect as registering the descriptor exactly once. `poll.modify(fd, eventmask)` Modifies an already registered fd. This has the same effect as `register(fd, eventmask)`. Attempting to modify a file descriptor that was never registered causes an [`OSError`](exceptions#OSError "OSError") exception with errno `ENOENT` to be raised. `poll.unregister(fd)` Remove a file descriptor being tracked by a polling object. Just like the [`register()`](#select.poll.register "select.poll.register") method, *fd* can be an integer or an object with a [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method that returns an integer. Attempting to remove a file descriptor that was never registered causes a [`KeyError`](exceptions#KeyError "KeyError") exception to be raised. `poll.poll([timeout])` Polls the set of registered file descriptors, and returns a possibly-empty list containing `(fd, event)` 2-tuples for the descriptors that have events or errors to report. *fd* is the file descriptor, and *event* is a bitmask with bits set for the reported events for that descriptor — `POLLIN` for waiting input, `POLLOUT` to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If *timeout* is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If *timeout* is omitted, negative, or [`None`](constants#None "None"), the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale), instead of raising [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). Kqueue Objects -------------- `kqueue.close()` Close the control file descriptor of the kqueue object. `kqueue.closed` `True` if the kqueue object is closed. `kqueue.fileno()` Return the file descriptor number of the control fd. `kqueue.fromfd(fd)` Create a kqueue object from a given file descriptor. `kqueue.control(changelist, max_events[, timeout]) → eventlist` Low level interface to kevent * changelist must be an iterable of kevent objects or `None` * max\_events must be 0 or a positive integer * timeout in seconds (floats possible); the default is `None`, to wait forever Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale), instead of raising [`InterruptedError`](exceptions#InterruptedError "InterruptedError"). Kevent Objects -------------- <https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2> `kevent.ident` Value used to identify the event. The interpretation depends on the filter but it’s usually the file descriptor. In the constructor ident can either be an int or an object with a [`fileno()`](io#io.IOBase.fileno "io.IOBase.fileno") method. kevent stores the integer internally. `kevent.filter` Name of the kernel filter. | Constant | Meaning | | --- | --- | | `KQ_FILTER_READ` | Takes a descriptor and returns whenever there is data available to read | | `KQ_FILTER_WRITE` | Takes a descriptor and returns whenever there is data available to write | | `KQ_FILTER_AIO` | AIO requests | | `KQ_FILTER_VNODE` | Returns when one or more of the requested events watched in *fflag* occurs | | `KQ_FILTER_PROC` | Watch for events on a process id | | `KQ_FILTER_NETDEV` | Watch for events on a network device [not available on macOS] | | `KQ_FILTER_SIGNAL` | Returns whenever the watched signal is delivered to the process | | `KQ_FILTER_TIMER` | Establishes an arbitrary timer | `kevent.flags` Filter action. | Constant | Meaning | | --- | --- | | `KQ_EV_ADD` | Adds or modifies an event | | `KQ_EV_DELETE` | Removes an event from the queue | | `KQ_EV_ENABLE` | Permitscontrol() to returns the event | | `KQ_EV_DISABLE` | Disablesevent | | `KQ_EV_ONESHOT` | Removes event after first occurrence | | `KQ_EV_CLEAR` | Reset the state after an event is retrieved | | `KQ_EV_SYSFLAGS` | internal event | | `KQ_EV_FLAG1` | internal event | | `KQ_EV_EOF` | Filter specific EOF condition | | `KQ_EV_ERROR` | See return values | `kevent.fflags` Filter specific flags. `KQ_FILTER_READ` and `KQ_FILTER_WRITE` filter flags: | Constant | Meaning | | --- | --- | | `KQ_NOTE_LOWAT` | low water mark of a socket buffer | `KQ_FILTER_VNODE` filter flags: | Constant | Meaning | | --- | --- | | `KQ_NOTE_DELETE` | *unlink()* was called | | `KQ_NOTE_WRITE` | a write occurred | | `KQ_NOTE_EXTEND` | the file was extended | | `KQ_NOTE_ATTRIB` | an attribute was changed | | `KQ_NOTE_LINK` | the link count has changed | | `KQ_NOTE_RENAME` | the file was renamed | | `KQ_NOTE_REVOKE` | access to the file was revoked | `KQ_FILTER_PROC` filter flags: | Constant | Meaning | | --- | --- | | `KQ_NOTE_EXIT` | the process has exited | | `KQ_NOTE_FORK` | the process has called *fork()* | | `KQ_NOTE_EXEC` | the process has executed a new process | | `KQ_NOTE_PCTRLMASK` | internal filter flag | | `KQ_NOTE_PDATAMASK` | internal filter flag | | `KQ_NOTE_TRACK` | follow a process across *fork()* | | `KQ_NOTE_CHILD` | returned on the child process for *NOTE\_TRACK* | | `KQ_NOTE_TRACKERR` | unable to attach to a child | `KQ_FILTER_NETDEV` filter flags (not available on macOS): | Constant | Meaning | | --- | --- | | `KQ_NOTE_LINKUP` | link is up | | `KQ_NOTE_LINKDOWN` | link is down | | `KQ_NOTE_LINKINV` | link state is invalid | `kevent.data` Filter specific data. `kevent.udata` User defined value.
programming_docs
python warnings — Warning control warnings — Warning control ========================== **Source code:** [Lib/warnings.py](https://github.com/python/cpython/tree/3.9/Lib/warnings.py) Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module. Python programmers issue warnings by calling the [`warn()`](#warnings.warn "warnings.warn") function defined in this module. (C programmers use [`PyErr_WarnEx()`](../c-api/exceptions#c.PyErr_WarnEx "PyErr_WarnEx"); see [Exception Handling](../c-api/exceptions#exceptionhandling) for details). Warning messages are normally written to [`sys.stderr`](sys#sys.stderr "sys.stderr"), but their disposition can be changed flexibly, from ignoring all warnings to turning them into exceptions. The disposition of warnings can vary based on the [warning category](#warning-categories), the text of the warning message, and the source location where it is issued. Repetitions of a particular warning for the same source location are typically suppressed. There are two stages in warning control: first, each time a warning is issued, a determination is made whether a message should be issued or not; next, if a message is to be issued, it is formatted and printed using a user-settable hook. The determination whether to issue a warning message is controlled by the [warning filter](#warning-filter), which is a sequence of matching rules and actions. Rules can be added to the filter by calling [`filterwarnings()`](#warnings.filterwarnings "warnings.filterwarnings") and reset to its default state by calling [`resetwarnings()`](#warnings.resetwarnings "warnings.resetwarnings"). The printing of warning messages is done by calling [`showwarning()`](#warnings.showwarning "warnings.showwarning"), which may be overridden; the default implementation of this function formats the message by calling [`formatwarning()`](#warnings.formatwarning "warnings.formatwarning"), which is also available for use by custom implementations. See also [`logging.captureWarnings()`](logging#logging.captureWarnings "logging.captureWarnings") allows you to handle all warnings with the standard logging infrastructure. Warning Categories ------------------ There are a number of built-in exceptions that represent warning categories. This categorization is useful to be able to filter out groups of warnings. While these are technically [built-in exceptions](exceptions#warning-categories-as-exceptions), they are documented here, because conceptually they belong to the warnings mechanism. User code can define additional warning categories by subclassing one of the standard warning categories. A warning category must always be a subclass of the [`Warning`](exceptions#Warning "Warning") class. The following warnings category classes are currently defined: | Class | Description | | --- | --- | | [`Warning`](exceptions#Warning "Warning") | This is the base class of all warning category classes. It is a subclass of [`Exception`](exceptions#Exception "Exception"). | | [`UserWarning`](exceptions#UserWarning "UserWarning") | The default category for [`warn()`](#warnings.warn "warnings.warn"). | | [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") | Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in `__main__`). | | [`SyntaxWarning`](exceptions#SyntaxWarning "SyntaxWarning") | Base category for warnings about dubious syntactic features. | | [`RuntimeWarning`](exceptions#RuntimeWarning "RuntimeWarning") | Base category for warnings about dubious runtime features. | | [`FutureWarning`](exceptions#FutureWarning "FutureWarning") | Base category for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python. | | [`PendingDeprecationWarning`](exceptions#PendingDeprecationWarning "PendingDeprecationWarning") | Base category for warnings about features that will be deprecated in the future (ignored by default). | | [`ImportWarning`](exceptions#ImportWarning "ImportWarning") | Base category for warnings triggered during the process of importing a module (ignored by default). | | [`UnicodeWarning`](exceptions#UnicodeWarning "UnicodeWarning") | Base category for warnings related to Unicode. | | [`BytesWarning`](exceptions#BytesWarning "BytesWarning") | Base category for warnings related to [`bytes`](stdtypes#bytes "bytes") and [`bytearray`](stdtypes#bytearray "bytearray"). | | [`ResourceWarning`](exceptions#ResourceWarning "ResourceWarning") | Base category for warnings related to resource usage (ignored by default). | Changed in version 3.7: Previously [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") and [`FutureWarning`](exceptions#FutureWarning "FutureWarning") were distinguished based on whether a feature was being removed entirely or changing its behaviour. They are now distinguished based on their intended audience and the way they’re handled by the default warnings filters. The Warnings Filter ------------------- The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). Conceptually, the warnings filter maintains an ordered list of filter specifications; any specific warning is matched against each filter specification in the list in turn until a match is found; the filter determines the disposition of the match. Each entry is a tuple of the form (*action*, *message*, *category*, *module*, *lineno*), where: * *action* is one of the following strings: | Value | Disposition | | --- | --- | | `"default"` | print the first occurrence of matching warnings for each location (module + line number) where the warning is issued | | `"error"` | turn matching warnings into exceptions | | `"ignore"` | never print matching warnings | | `"always"` | always print matching warnings | | `"module"` | print the first occurrence of matching warnings for each module where the warning is issued (regardless of line number) | | `"once"` | print only the first occurrence of matching warnings, regardless of location | * *message* is a string containing a regular expression that the start of the warning message must match. The expression is compiled to always be case-insensitive. * *category* is a class (a subclass of [`Warning`](exceptions#Warning "Warning")) of which the warning category must be a subclass in order to match. * *module* is a string containing a regular expression that the module name must match. The expression is compiled to be case-sensitive. * *lineno* is an integer that the line number where the warning occurred must match, or `0` to match all line numbers. Since the [`Warning`](exceptions#Warning "Warning") class is derived from the built-in [`Exception`](exceptions#Exception "Exception") class, to turn a warning into an error we simply raise `category(message)`. If a warning is reported and doesn’t match any registered filter then the “default” action is applied (hence its name). ### Describing Warning Filters The warnings filter is initialized by [`-W`](../using/cmdline#cmdoption-w) options passed to the Python interpreter command line and the [`PYTHONWARNINGS`](../using/cmdline#envvar-PYTHONWARNINGS) environment variable. The interpreter saves the arguments for all supplied entries without interpretation in [`sys.warnoptions`](sys#sys.warnoptions "sys.warnoptions"); the [`warnings`](#module-warnings "warnings: Issue warning messages and control their disposition.") module parses these when it is first imported (invalid options are ignored, after printing a message to [`sys.stderr`](sys#sys.stderr "sys.stderr")). Individual warnings filters are specified as a sequence of fields separated by colons: ``` action:message:category:module:line ``` The meaning of each of these fields is as described in [The Warnings Filter](#warning-filter). When listing multiple filters on a single line (as for [`PYTHONWARNINGS`](../using/cmdline#envvar-PYTHONWARNINGS)), the individual filters are separated by commas and the filters listed later take precedence over those listed before them (as they’re applied left-to-right, and the most recently applied filters take precedence over earlier ones). Commonly used warning filters apply to either all warnings, warnings in a particular category, or warnings raised by particular modules or packages. Some examples: ``` default # Show all warnings (even those ignored by default) ignore # Ignore all warnings error # Convert all warnings to errors error::ResourceWarning # Treat ResourceWarning messages as errors default::DeprecationWarning # Show DeprecationWarning messages ignore,default:::mymodule # Only report warnings triggered by "mymodule" error:::mymodule[.*] # Convert warnings to errors in "mymodule" # and any subpackages of "mymodule" ``` ### Default Warning Filter By default, Python installs several warning filters, which can be overridden by the [`-W`](../using/cmdline#cmdoption-w) command-line option, the [`PYTHONWARNINGS`](../using/cmdline#envvar-PYTHONWARNINGS) environment variable and calls to [`filterwarnings()`](#warnings.filterwarnings "warnings.filterwarnings"). In regular release builds, the default warning filter has the following entries (in order of precedence): ``` default::DeprecationWarning:__main__ ignore::DeprecationWarning ignore::PendingDeprecationWarning ignore::ImportWarning ignore::ResourceWarning ``` In debug builds, the list of default warning filters is empty. Changed in version 3.2: [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") is now ignored by default in addition to [`PendingDeprecationWarning`](exceptions#PendingDeprecationWarning "PendingDeprecationWarning"). Changed in version 3.7: [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") is once again shown by default when triggered directly by code in `__main__`. Changed in version 3.7: [`BytesWarning`](exceptions#BytesWarning "BytesWarning") no longer appears in the default filter list and is instead configured via [`sys.warnoptions`](sys#sys.warnoptions "sys.warnoptions") when [`-b`](../using/cmdline#cmdoption-b) is specified twice. ### Overriding the default filter Developers of applications written in Python may wish to hide *all* Python level warnings from their users by default, and only display them when running tests or otherwise working on the application. The [`sys.warnoptions`](sys#sys.warnoptions "sys.warnoptions") attribute used to pass filter configurations to the interpreter can be used as a marker to indicate whether or not warnings should be disabled: ``` import sys if not sys.warnoptions: import warnings warnings.simplefilter("ignore") ``` Developers of test runners for Python code are advised to instead ensure that *all* warnings are displayed by default for the code under test, using code like: ``` import sys if not sys.warnoptions: import os, warnings warnings.simplefilter("default") # Change the filter in this process os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses ``` Finally, developers of interactive shells that run user code in a namespace other than `__main__` are advised to ensure that [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") messages are made visible by default, using code like the following (where `user_ns` is the module used to execute code entered interactively): ``` import warnings warnings.filterwarnings("default", category=DeprecationWarning, module=user_ns.get("__name__")) ``` Temporarily Suppressing Warnings -------------------------------- If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning (even when warnings have been explicitly configured via the command line), then it is possible to suppress the warning using the [`catch_warnings`](#warnings.catch_warnings "warnings.catch_warnings") context manager: ``` import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() ``` While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the [`catch_warnings`](#warnings.catch_warnings "warnings.catch_warnings") context manager at the same time, the behavior is undefined. Testing Warnings ---------------- To test warnings raised by code, use the [`catch_warnings`](#warnings.catch_warnings "warnings.catch_warnings") context manager. With it you can temporarily mutate the warnings filter to facilitate your testing. For instance, do the following to capture all raised warnings to check: ``` import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. fxn() # Verify some things assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "deprecated" in str(w[-1].message) ``` One can also cause all warnings to be exceptions by using `error` instead of `always`. One thing to be aware of is that if a warning has already been raised because of a `once`/`default` rule, then no matter what filters are set the warning will not be seen again unless the warnings registry related to the warning has been cleared. Once the context manager exits, the warnings filter is restored to its state when the context was entered. This prevents tests from changing the warnings filter in unexpected ways between tests and leading to indeterminate test results. The [`showwarning()`](#warnings.showwarning "warnings.showwarning") function in the module is also restored to its original value. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the [`catch_warnings`](#warnings.catch_warnings "warnings.catch_warnings") context manager at the same time, the behavior is undefined. When testing multiple operations that raise the same kind of warning, it is important to test them in a manner that confirms each operation is raising a new warning (e.g. set warnings to be raised as exceptions and check the operations raise exceptions, check that the length of the warning list continues to increase after each operation, or else delete the previous entries from the warnings list before each new operation). Updating Code For New Versions of Dependencies ---------------------------------------------- Warning categories that are primarily of interest to Python developers (rather than end users of applications written in Python) are ignored by default. Notably, this “ignored by default” list includes [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") (for every module except `__main__`), which means developers should make sure to test their code with typically ignored warnings made visible in order to receive timely notifications of future breaking API changes (whether in the standard library or third party packages). In the ideal case, the code will have a suitable test suite, and the test runner will take care of implicitly enabling all warnings when running tests (the test runner provided by the [`unittest`](unittest#module-unittest "unittest: Unit testing framework for Python.") module does this). In less ideal cases, applications can be checked for use of deprecated interfaces by passing [`-Wd`](../using/cmdline#cmdoption-w) to the Python interpreter (this is shorthand for `-W default`) or setting `PYTHONWARNINGS=default` in the environment. This enables default handling for all warnings, including those that are ignored by default. To change what action is taken for encountered warnings you can change what argument is passed to [`-W`](../using/cmdline#cmdoption-w) (e.g. `-W error`). See the [`-W`](../using/cmdline#cmdoption-w) flag for more details on what is possible. Available Functions ------------------- `warnings.warn(message, category=None, stacklevel=1, source=None)` Issue a warning, or maybe ignore it or raise an exception. The *category* argument, if given, must be a [warning category class](#warning-categories); it defaults to [`UserWarning`](exceptions#UserWarning "UserWarning"). Alternatively, *message* can be a [`Warning`](exceptions#Warning "Warning") instance, in which case *category* will be ignored and `message.__class__` will be used. In this case, the message text will be `str(message)`. This function raises an exception if the particular warning issued is changed into an error by the [warnings filter](#warning-filter). The *stacklevel* argument can be used by wrapper functions written in Python, like this: ``` def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2) ``` This makes the warning refer to `deprecation()`’s caller, rather than to the source of `deprecation()` itself (since the latter would defeat the purpose of the warning message). *source*, if supplied, is the destroyed object which emitted a [`ResourceWarning`](exceptions#ResourceWarning "ResourceWarning"). Changed in version 3.6: Added *source* parameter. `warnings.warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)` This is a low-level interface to the functionality of [`warn()`](#warnings.warn "warnings.warn"), passing in explicitly the message, category, filename and line number, and optionally the module name and the registry (which should be the `__warningregistry__` dictionary of the module). The module name defaults to the filename with `.py` stripped; if no registry is passed, the warning is never suppressed. *message* must be a string and *category* a subclass of [`Warning`](exceptions#Warning "Warning") or *message* may be a [`Warning`](exceptions#Warning "Warning") instance, in which case *category* will be ignored. *module\_globals*, if supplied, should be the global namespace in use by the code for which the warning is issued. (This argument is used to support displaying source for modules found in zipfiles or other non-filesystem import sources). *source*, if supplied, is the destroyed object which emitted a [`ResourceWarning`](exceptions#ResourceWarning "ResourceWarning"). Changed in version 3.6: Add the *source* parameter. `warnings.showwarning(message, category, filename, lineno, file=None, line=None)` Write a warning to a file. The default implementation calls `formatwarning(message, category, filename, lineno, line)` and writes the resulting string to *file*, which defaults to [`sys.stderr`](sys#sys.stderr "sys.stderr"). You may replace this function with any callable by assigning to `warnings.showwarning`. *line* is a line of source code to be included in the warning message; if *line* is not supplied, [`showwarning()`](#warnings.showwarning "warnings.showwarning") will try to read the line specified by *filename* and *lineno*. `warnings.formatwarning(message, category, filename, lineno, line=None)` Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. *line* is a line of source code to be included in the warning message; if *line* is not supplied, [`formatwarning()`](#warnings.formatwarning "warnings.formatwarning") will try to read the line specified by *filename* and *lineno*. `warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)` Insert an entry into the list of [warnings filter specifications](#warning-filter). The entry is inserted at the front by default; if *append* is true, it is inserted at the end. This checks the types of the arguments, compiles the *message* and *module* regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything. `warnings.simplefilter(action, category=Warning, lineno=0, append=False)` Insert a simple entry into the list of [warnings filter specifications](#warning-filter). The meaning of the function parameters is as for [`filterwarnings()`](#warnings.filterwarnings "warnings.filterwarnings"), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match. `warnings.resetwarnings()` Reset the warnings filter. This discards the effect of all previous calls to [`filterwarnings()`](#warnings.filterwarnings "warnings.filterwarnings"), including that of the [`-W`](../using/cmdline#cmdoption-w) command line options and calls to [`simplefilter()`](#warnings.simplefilter "warnings.simplefilter"). Available Context Managers -------------------------- `class warnings.catch_warnings(*, record=False, module=None)` A context manager that copies and, upon exit, restores the warnings filter and the [`showwarning()`](#warnings.showwarning "warnings.showwarning") function. If the *record* argument is [`False`](constants#False "False") (the default) the context manager returns [`None`](constants#None "None") on entry. If *record* is [`True`](constants#True "True"), a list is returned that is progressively populated with objects as seen by a custom [`showwarning()`](#warnings.showwarning "warnings.showwarning") function (which also suppresses output to `sys.stdout`). Each object in the list has attributes with the same names as the arguments to [`showwarning()`](#warnings.showwarning "warnings.showwarning"). The *module* argument takes a module that will be used instead of the module returned when you import [`warnings`](#module-warnings "warnings: Issue warning messages and control their disposition.") whose filter will be protected. This argument exists primarily for testing the [`warnings`](#module-warnings "warnings: Issue warning messages and control their disposition.") module itself. Note The [`catch_warnings`](#warnings.catch_warnings "warnings.catch_warnings") manager works by replacing and then later restoring the module’s [`showwarning()`](#warnings.showwarning "warnings.showwarning") function and internal list of filter specifications. This means the context manager is modifying global state and therefore is not thread-safe.
programming_docs
python hashlib — Secure hashes and message digests hashlib — Secure hashes and message digests =========================================== **Source code:** [Lib/hashlib.py](https://github.com/python/cpython/tree/3.9/Lib/hashlib.py) This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in Internet [**RFC 1321**](https://tools.ietf.org/html/rfc1321.html)). The terms “secure hash” and “message digest” are interchangeable. Older algorithms were called message digests. The modern term is secure hash. Note If you want the adler32 or crc32 hash functions, they are available in the [`zlib`](zlib#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.") module. Warning Some algorithms have known hash collision weaknesses, refer to the “See also” section at the end. Hash algorithms --------------- There is one constructor method named for each type of *hash*. All return a hash object with the same simple interface. For example: use `sha256()` to create a SHA-256 hash object. You can now feed this object with [bytes-like objects](../glossary#term-bytes-like-object) (normally [`bytes`](stdtypes#bytes "bytes")) using the `update()` method. At any point you can ask it for the *digest* of the concatenation of the data fed to it so far using the `digest()` or `hexdigest()` methods. Note For better multithreading performance, the Python [GIL](../glossary#term-gil) is released for data larger than 2047 bytes at object creation or on update. Note Feeding string objects into `update()` is not supported, as hashes work on bytes, not on characters. Constructors for hash algorithms that are always present in this module are `sha1()`, `sha224()`, `sha256()`, `sha384()`, `sha512()`, [`blake2b()`](#hashlib.blake2b "hashlib.blake2b"), and [`blake2s()`](#hashlib.blake2s "hashlib.blake2s"). `md5()` is normally available as well, though it may be missing or blocked if you are using a rare “FIPS compliant” build of Python. Additional algorithms may also be available depending upon the OpenSSL library that Python uses on your platform. On most platforms the `sha3_224()`, `sha3_256()`, `sha3_384()`, `sha3_512()`, `shake_128()`, `shake_256()` are also available. New in version 3.6: SHA3 (Keccak) and SHAKE constructors `sha3_224()`, `sha3_256()`, `sha3_384()`, `sha3_512()`, `shake_128()`, `shake_256()`. New in version 3.6: [`blake2b()`](#hashlib.blake2b "hashlib.blake2b") and [`blake2s()`](#hashlib.blake2s "hashlib.blake2s") were added. Changed in version 3.9: All hashlib constructors take a keyword-only argument *usedforsecurity* with default value `True`. A false value allows the use of insecure and blocked hashing algorithms in restricted environments. `False` indicates that the hashing algorithm is not used in a security context, e.g. as a non-cryptographic one-way compression function. Hashlib now uses SHA3 and SHAKE from OpenSSL 1.1.1 and newer. For example, to obtain the digest of the byte string `b'Nobody inspects the spammish repetition'`: ``` >>> import hashlib >>> m = hashlib.sha256() >>> m.update(b"Nobody inspects") >>> m.update(b" the spammish repetition") >>> m.digest() b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06' >>> m.digest_size 32 >>> m.block_size 64 ``` More condensed: ``` >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' ``` `hashlib.new(name, [data, ]*, usedforsecurity=True)` Is a generic constructor that takes the string *name* of the desired algorithm as its first parameter. It also exists to allow access to the above listed hashes as well as any other algorithms that your OpenSSL library may offer. The named constructors are much faster than [`new()`](#hashlib.new "hashlib.new") and should be preferred. Using [`new()`](#hashlib.new "hashlib.new") with an algorithm provided by OpenSSL: ``` >>> h = hashlib.new('sha256') >>> h.update(b"Nobody inspects the spammish repetition") >>> h.hexdigest() '031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406' ``` Hashlib provides the following constant attributes: `hashlib.algorithms_guaranteed` A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms. Note that ‘md5’ is in this list despite some upstream vendors offering an odd “FIPS compliant” Python build that excludes it. New in version 3.2. `hashlib.algorithms_available` A set containing the names of the hash algorithms that are available in the running Python interpreter. These names will be recognized when passed to [`new()`](#hashlib.new "hashlib.new"). [`algorithms_guaranteed`](#hashlib.algorithms_guaranteed "hashlib.algorithms_guaranteed") will always be a subset. The same algorithm may appear multiple times in this set under different names (thanks to OpenSSL). New in version 3.2. The following values are provided as constant attributes of the hash objects returned by the constructors: `hash.digest_size` The size of the resulting hash in bytes. `hash.block_size` The internal block size of the hash algorithm in bytes. A hash object has the following attributes: `hash.name` The canonical name of this hash, always lowercase and always suitable as a parameter to [`new()`](#hashlib.new "hashlib.new") to create another hash of this type. Changed in version 3.4: The name attribute has been present in CPython since its inception, but until Python 3.4 was not formally specified, so may not exist on some platforms. A hash object has the following methods: `hash.update(data)` Update the hash object with the [bytes-like object](../glossary#term-bytes-like-object). Repeated calls are equivalent to a single call with the concatenation of all the arguments: `m.update(a); m.update(b)` is equivalent to `m.update(a+b)`. Changed in version 3.1: The Python GIL is released to allow other threads to run while hash updates on data larger than 2047 bytes is taking place when using hash algorithms supplied by OpenSSL. `hash.digest()` Return the digest of the data passed to the [`update()`](#hashlib.hash.update "hashlib.hash.update") method so far. This is a bytes object of size [`digest_size`](#hashlib.hash.digest_size "hashlib.hash.digest_size") which may contain bytes in the whole range from 0 to 255. `hash.hexdigest()` Like [`digest()`](#hashlib.hash.digest "hashlib.hash.digest") except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. `hash.copy()` Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of data sharing a common initial substring. SHAKE variable length digests ----------------------------- The `shake_128()` and `shake_256()` algorithms provide variable length digests with length\_in\_bits//2 up to 128 or 256 bits of security. As such, their digest methods require a length. Maximum length is not limited by the SHAKE algorithm. `shake.digest(length)` Return the digest of the data passed to the `update()` method so far. This is a bytes object of size *length* which may contain bytes in the whole range from 0 to 255. `shake.hexdigest(length)` Like [`digest()`](#hashlib.shake.digest "hashlib.shake.digest") except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. Key derivation -------------- Key derivation and key stretching algorithms are designed for secure password hashing. Naive algorithms such as `sha1(password)` are not resistant against brute-force attacks. A good password hashing function must be tunable, slow, and include a [salt](https://en.wikipedia.org/wiki/Salt_%28cryptography%29). `hashlib.pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)` The function provides PKCS#5 password-based key derivation function 2. It uses HMAC as pseudorandom function. The string *hash\_name* is the desired name of the hash digest algorithm for HMAC, e.g. ‘sha1’ or ‘sha256’. *password* and *salt* are interpreted as buffers of bytes. Applications and libraries should limit *password* to a sensible length (e.g. 1024). *salt* should be about 16 or more bytes from a proper source, e.g. [`os.urandom()`](os#os.urandom "os.urandom"). The number of *iterations* should be chosen based on the hash algorithm and computing power. As of 2013, at least 100,000 iterations of SHA-256 are suggested. *dklen* is the length of the derived key. If *dklen* is `None` then the digest size of the hash algorithm *hash\_name* is used, e.g. 64 for SHA-512. ``` >>> import hashlib >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000) >>> dk.hex() '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5' ``` New in version 3.4. Note A fast implementation of *pbkdf2\_hmac* is available with OpenSSL. The Python implementation uses an inline version of [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"). It is about three times slower and doesn’t release the GIL. `hashlib.scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64)` The function provides scrypt password-based key derivation function as defined in [**RFC 7914**](https://tools.ietf.org/html/rfc7914.html). *password* and *salt* must be [bytes-like objects](../glossary#term-bytes-like-object). Applications and libraries should limit *password* to a sensible length (e.g. 1024). *salt* should be about 16 or more bytes from a proper source, e.g. [`os.urandom()`](os#os.urandom "os.urandom"). *n* is the CPU/Memory cost factor, *r* the block size, *p* parallelization factor and *maxmem* limits memory (OpenSSL 1.1.0 defaults to 32 MiB). *dklen* is the length of the derived key. [Availability](https://docs.python.org/3.9/library/intro.html#availability): OpenSSL 1.1+. New in version 3.6. BLAKE2 ------ [BLAKE2](https://blake2.net) is a cryptographic hash function defined in [**RFC 7693**](https://tools.ietf.org/html/rfc7693.html) that comes in two flavors: * **BLAKE2b**, optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes, * **BLAKE2s**, optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes. BLAKE2 supports **keyed mode** (a faster and simpler replacement for [HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)), **salted hashing**, **personalization**, and **tree hashing**. Hash objects from this module follow the API of standard library’s [`hashlib`](#module-hashlib "hashlib: Secure hash and message digest algorithms.") objects. ### Creating hash objects New hash objects are created by calling constructor functions: `hashlib.blake2b(data=b'', *, digest_size=64, key=b'', salt=b'', person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)` `hashlib.blake2s(data=b'', *, digest_size=32, key=b'', salt=b'', person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)` These functions return the corresponding hash objects for calculating BLAKE2b or BLAKE2s. They optionally take these general parameters: * *data*: initial chunk of data to hash, which must be [bytes-like object](../glossary#term-bytes-like-object). It can be passed only as positional argument. * *digest\_size*: size of output digest in bytes. * *key*: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for BLAKE2s). * *salt*: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s). * *person*: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s). The following table shows limits for general parameters (in bytes): | Hash | digest\_size | len(key) | len(salt) | len(person) | | --- | --- | --- | --- | --- | | BLAKE2b | 64 | 64 | 16 | 16 | | BLAKE2s | 32 | 32 | 8 | 8 | Note BLAKE2 specification defines constant lengths for salt and personalization parameters, however, for convenience, this implementation accepts byte strings of any size up to the specified length. If the length of the parameter is less than specified, it is padded with zeros, thus, for example, `b'salt'` and `b'salt\x00'` is the same value. (This is not the case for *key*.) These sizes are available as module [constants](#constants) described below. Constructor functions also accept the following tree hashing parameters: * *fanout*: fanout (0 to 255, 0 if unlimited, 1 in sequential mode). * *depth*: maximal depth of tree (1 to 255, 255 if unlimited, 1 in sequential mode). * *leaf\_size*: maximal byte length of leaf (0 to `2**32-1`, 0 if unlimited or in sequential mode). * *node\_offset*: node offset (0 to `2**64-1` for BLAKE2b, 0 to `2**48-1` for BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode). * *node\_depth*: node depth (0 to 255, 0 for leaves, or in sequential mode). * *inner\_size*: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for BLAKE2s, 0 in sequential mode). * *last\_node*: boolean indicating whether the processed node is the last one (`False` for sequential mode). See section 2.10 in [BLAKE2 specification](https://blake2.net/blake2_20130129.pdf) for comprehensive review of tree hashing. ### Constants `blake2b.SALT_SIZE` `blake2s.SALT_SIZE` Salt length (maximum length accepted by constructors). `blake2b.PERSON_SIZE` `blake2s.PERSON_SIZE` Personalization string length (maximum length accepted by constructors). `blake2b.MAX_KEY_SIZE` `blake2s.MAX_KEY_SIZE` Maximum key size. `blake2b.MAX_DIGEST_SIZE` `blake2s.MAX_DIGEST_SIZE` Maximum digest size that the hash function can output. ### Examples #### Simple hashing To calculate hash of some data, you should first construct a hash object by calling the appropriate constructor function ([`blake2b()`](#hashlib.blake2b "hashlib.blake2b") or [`blake2s()`](#hashlib.blake2s "hashlib.blake2s")), then update it with the data by calling `update()` on the object, and, finally, get the digest out of the object by calling `digest()` (or `hexdigest()` for hex-encoded string). ``` >>> from hashlib import blake2b >>> h = blake2b() >>> h.update(b'Hello world') >>> h.hexdigest() '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' ``` As a shortcut, you can pass the first chunk of data to update directly to the constructor as the positional argument: ``` >>> from hashlib import blake2b >>> blake2b(b'Hello world').hexdigest() '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' ``` You can call [`hash.update()`](#hashlib.hash.update "hashlib.hash.update") as many times as you need to iteratively update the hash: ``` >>> from hashlib import blake2b >>> items = [b'Hello', b' ', b'world'] >>> h = blake2b() >>> for item in items: ... h.update(item) >>> h.hexdigest() '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' ``` #### Using different digest sizes BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32 bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing the size of output, we can tell BLAKE2b to produce 20-byte digests: ``` >>> from hashlib import blake2b >>> h = blake2b(digest_size=20) >>> h.update(b'Replacing SHA1 with the more secure function') >>> h.hexdigest() 'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c' >>> h.digest_size 20 >>> len(h.digest()) 20 ``` Hash objects with different digest sizes have completely different outputs (shorter hashes are *not* prefixes of longer hashes); BLAKE2b and BLAKE2s produce different outputs even if the output length is the same: ``` >>> from hashlib import blake2b, blake2s >>> blake2b(digest_size=10).hexdigest() '6fa1d8fcfd719046d762' >>> blake2b(digest_size=11).hexdigest() 'eb6ec15daf9546254f0809' >>> blake2s(digest_size=10).hexdigest() '1bf21a98c78a1c376ae9' >>> blake2s(digest_size=11).hexdigest() '567004bf96e4a25773ebf4' ``` #### Keyed hashing Keyed hashing can be used for authentication as a faster and simpler replacement for [Hash-based message authentication code](https://en.wikipedia.org/wiki/HMAC) (HMAC). BLAKE2 can be securely used in prefix-MAC mode thanks to the indifferentiability property inherited from BLAKE. This example shows how to get a (hex-encoded) 128-bit authentication code for message `b'message data'` with key `b'pseudorandom key'`: ``` >>> from hashlib import blake2b >>> h = blake2b(key=b'pseudorandom key', digest_size=16) >>> h.update(b'message data') >>> h.hexdigest() '3d363ff7401e02026f4a4687d4863ced' ``` As a practical example, a web application can symmetrically sign cookies sent to users and later verify them to make sure they weren’t tampered with: ``` >>> from hashlib import blake2b >>> from hmac import compare_digest >>> >>> SECRET_KEY = b'pseudorandomly generated server secret key' >>> AUTH_SIZE = 16 >>> >>> def sign(cookie): ... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY) ... h.update(cookie) ... return h.hexdigest().encode('utf-8') >>> >>> def verify(cookie, sig): ... good_sig = sign(cookie) ... return compare_digest(good_sig, sig) >>> >>> cookie = b'user-alice' >>> sig = sign(cookie) >>> print("{0},{1}".format(cookie.decode('utf-8'), sig)) user-alice,b'43b3c982cf697e0c5ab22172d1ca7421' >>> verify(cookie, sig) True >>> verify(b'user-bob', sig) False >>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00') False ``` Even though there’s a native keyed hashing mode, BLAKE2 can, of course, be used in HMAC construction with [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation") module: ``` >>> import hmac, hashlib >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s) >>> m.update(b'message') >>> m.hexdigest() 'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142' ``` #### Randomized hashing By setting *salt* parameter users can introduce randomization to the hash function. Randomized hashing is useful for protecting against collision attacks on the hash function used in digital signatures. Randomized hashing is designed for situations where one party, the message preparer, generates all or part of a message to be signed by a second party, the message signer. If the message preparer is able to find cryptographic hash function collisions (i.e., two messages producing the same hash value), then they might prepare meaningful versions of the message that would produce the same hash value and digital signature, but with different results (e.g., transferring $1,000,000 to an account, rather than $10). Cryptographic hash functions have been designed with collision resistance as a major goal, but the current concentration on attacking cryptographic hash functions may result in a given cryptographic hash function providing less collision resistance than expected. Randomized hashing offers the signer additional protection by reducing the likelihood that a preparer can generate two or more messages that ultimately yield the same hash value during the digital signature generation process — even if it is practical to find collisions for the hash function. However, the use of randomized hashing may reduce the amount of security provided by a digital signature when all portions of the message are prepared by the signer. ([NIST SP-800-106 “Randomized Hashing for Digital Signatures”](https://csrc.nist.gov/publications/detail/sp/800-106/final)) In BLAKE2 the salt is processed as a one-time input to the hash function during initialization, rather than as an input to each compression function. Warning *Salted hashing* (or just hashing) with BLAKE2 or any other general-purpose cryptographic hash function, such as SHA-256, is not suitable for hashing passwords. See [BLAKE2 FAQ](https://blake2.net/#qa) for more information. ``` >>> import os >>> from hashlib import blake2b >>> msg = b'some message' >>> # Calculate the first hash with a random salt. >>> salt1 = os.urandom(blake2b.SALT_SIZE) >>> h1 = blake2b(salt=salt1) >>> h1.update(msg) >>> # Calculate the second hash with a different random salt. >>> salt2 = os.urandom(blake2b.SALT_SIZE) >>> h2 = blake2b(salt=salt2) >>> h2.update(msg) >>> # The digests are different. >>> h1.digest() != h2.digest() True ``` #### Personalization Sometimes it is useful to force hash function to produce different digests for the same input for different purposes. Quoting the authors of the Skein hash function: We recommend that all application designers seriously consider doing this; we have seen many protocols where a hash that is computed in one part of the protocol can be used in an entirely different part because two hash computations were done on similar or related data, and the attacker can force the application to make the hash inputs the same. Personalizing each hash function used in the protocol summarily stops this type of attack. ([The Skein Hash Function Family](http://www.skein-hash.info/sites/default/files/skein1.3.pdf), p. 21) BLAKE2 can be personalized by passing bytes to the *person* argument: ``` >>> from hashlib import blake2b >>> FILES_HASH_PERSON = b'MyApp Files Hash' >>> BLOCK_HASH_PERSON = b'MyApp Block Hash' >>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON) >>> h.update(b'the same content') >>> h.hexdigest() '20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4' >>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON) >>> h.update(b'the same content') >>> h.hexdigest() 'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3' ``` Personalization together with the keyed mode can also be used to derive different keys from a single one. ``` >>> from hashlib import blake2s >>> from base64 import b64decode, b64encode >>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=') >>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest() >>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest() >>> print(b64encode(enc_key).decode('utf-8')) rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw= >>> print(b64encode(mac_key).decode('utf-8')) G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o= ``` #### Tree mode Here’s an example of hashing a minimal tree with two leaf nodes: ``` 10 / \ 00 01 ``` This example uses 64-byte internal digests, and returns the 32-byte final digest: ``` >>> from hashlib import blake2b >>> >>> FANOUT = 2 >>> DEPTH = 2 >>> LEAF_SIZE = 4096 >>> INNER_SIZE = 64 >>> >>> buf = bytearray(6000) >>> >>> # Left leaf ... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH, ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, ... node_offset=0, node_depth=0, last_node=False) >>> # Right leaf ... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH, ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, ... node_offset=1, node_depth=0, last_node=True) >>> # Root node ... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH, ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, ... node_offset=0, node_depth=1, last_node=True) >>> h10.update(h00.digest()) >>> h10.update(h01.digest()) >>> h10.hexdigest() '3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa' ``` ### Credits [BLAKE2](https://blake2.net) was designed by *Jean-Philippe Aumasson*, *Samuel Neves*, *Zooko Wilcox-O’Hearn*, and *Christian Winnerlein* based on [SHA-3](https://en.wikipedia.org/wiki/NIST_hash_function_competition) finalist [BLAKE](https://131002.net/blake/) created by *Jean-Philippe Aumasson*, *Luca Henzen*, *Willi Meier*, and *Raphael C.-W. Phan*. It uses core algorithm from [ChaCha](https://cr.yp.to/chacha.html) cipher designed by *Daniel J. Bernstein*. The stdlib implementation is based on [pyblake2](https://pythonhosted.org/pyblake2/) module. It was written by *Dmitry Chestnykh* based on C implementation written by *Samuel Neves*. The documentation was copied from [pyblake2](https://pythonhosted.org/pyblake2/) and written by *Dmitry Chestnykh*. The C code was partly rewritten for Python by *Christian Heimes*. The following public domain dedication applies for both C hash function implementation, extension code, and this documentation: To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <https://creativecommons.org/publicdomain/zero/1.0/>. The following people have helped with development or contributed their changes to the project and the public domain according to the Creative Commons Public Domain Dedication 1.0 Universal: * *Alexandr Sokolovskiy* See also `Module` [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation") A module to generate message authentication codes using hashes. `Module` [`base64`](base64#module-base64 "base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85") Another way to encode binary hashes for non-binary environments. <https://blake2.net> Official BLAKE2 website. <https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf> The FIPS 180-2 publication on Secure Hash Algorithms. <https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms> Wikipedia article with information on which algorithms have known issues and what that means regarding their use. <https://www.ietf.org/rfc/rfc2898.txt> PKCS #5: Password-Based Cryptography Specification Version 2.0
programming_docs
python shlex — Simple lexical analysis shlex — Simple lexical analysis =============================== **Source code:** [Lib/shlex.py](https://github.com/python/cpython/tree/3.9/Lib/shlex.py) The [`shlex`](#shlex.shlex "shlex.shlex") class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings. The [`shlex`](#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") module defines the following functions: `shlex.split(s, comments=False, posix=True)` Split the string *s* using shell-like syntax. If *comments* is [`False`](constants#False "False") (the default), the parsing of comments in the given string will be disabled (setting the [`commenters`](#shlex.shlex.commenters "shlex.shlex.commenters") attribute of the [`shlex`](#shlex.shlex "shlex.shlex") instance to the empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is false. Note Since the [`split()`](#shlex.split "shlex.split") function instantiates a [`shlex`](#shlex.shlex "shlex.shlex") instance, passing `None` for *s* will read the string to split from standard input. Deprecated since version 3.9: Passing `None` for *s* will raise an exception in future Python versions. `shlex.join(split_command)` Concatenate the tokens of the list *split\_command* and return a string. This function is the inverse of [`split()`](#shlex.split "shlex.split"). ``` >>> from shlex import join >>> print(join(['echo', '-n', 'Multiple words'])) echo -n 'Multiple words' ``` The returned value is shell-escaped to protect against injection vulnerabilities (see [`quote()`](#shlex.quote "shlex.quote")). New in version 3.8. `shlex.quote(s)` Return a shell-escaped version of the string *s*. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list. This idiom would be unsafe: ``` >>> filename = 'somefile; rm -rf ~' >>> command = 'ls -l {}'.format(filename) >>> print(command) # executed by a shell: boom! ls -l somefile; rm -rf ~ ``` [`quote()`](#shlex.quote "shlex.quote") lets you plug the security hole: ``` >>> from shlex import quote >>> command = 'ls -l {}'.format(quote(filename)) >>> print(command) ls -l 'somefile; rm -rf ~' >>> remote_command = 'ssh home {}'.format(quote(command)) >>> print(remote_command) ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"'' ``` The quoting is compatible with UNIX shells and with [`split()`](#shlex.split "shlex.split"): ``` >>> from shlex import split >>> remote_command = split(remote_command) >>> remote_command ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"] >>> command = split(remote_command[-1]) >>> command ['ls', '-l', 'somefile; rm -rf ~'] ``` New in version 3.3. The [`shlex`](#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") module defines the following class: `class shlex.shlex(instream=None, infile=None, posix=False, punctuation_chars=False)` A [`shlex`](#shlex.shlex "shlex.shlex") instance or subclass instance is a lexical analyzer object. The initialization argument, if present, specifies where to read characters from. It must be a file-/stream-like object with [`read()`](io#io.TextIOBase.read "io.TextIOBase.read") and [`readline()`](io#io.TextIOBase.readline "io.TextIOBase.readline") methods, or a string. If no argument is given, input will be taken from `sys.stdin`. The second optional argument is a filename string, which sets the initial value of the [`infile`](#shlex.shlex.infile "shlex.shlex.infile") attribute. If the *instream* argument is omitted or equal to `sys.stdin`, this second argument defaults to “stdin”. The *posix* argument defines the operational mode: when *posix* is not true (default), the [`shlex`](#shlex.shlex "shlex.shlex") instance will operate in compatibility mode. When operating in POSIX mode, [`shlex`](#shlex.shlex "shlex.shlex") will try to be as close as possible to the POSIX shell parsing rules. The *punctuation\_chars* argument provides a way to make the behaviour even closer to how real shells parse. This can take a number of values: the default value, `False`, preserves the behaviour seen under Python 3.5 and earlier. If set to `True`, then parsing of the characters `();<>|&` is changed: any run of these characters (considered punctuation characters) is returned as a single token. If set to a non-empty string of characters, those characters will be used as the punctuation characters. Any characters in the [`wordchars`](#shlex.shlex.wordchars "shlex.shlex.wordchars") attribute that appear in *punctuation\_chars* will be removed from [`wordchars`](#shlex.shlex.wordchars "shlex.shlex.wordchars"). See [Improved Compatibility with Shells](#improved-shell-compatibility) for more information. *punctuation\_chars* can be set only upon [`shlex`](#shlex.shlex "shlex.shlex") instance creation and can’t be modified later. Changed in version 3.6: The *punctuation\_chars* parameter was added. See also `Module` [`configparser`](configparser#module-configparser "configparser: Configuration file parser.") Parser for configuration files similar to the Windows `.ini` files. shlex Objects ------------- A [`shlex`](#shlex.shlex "shlex.shlex") instance has the following methods: `shlex.get_token()` Return a token. If tokens have been stacked using [`push_token()`](#shlex.shlex.push_token "shlex.shlex.push_token"), pop a token off the stack. Otherwise, read one from the input stream. If reading encounters an immediate end-of-file, [`eof`](#shlex.shlex.eof "shlex.shlex.eof") is returned (the empty string (`''`) in non-POSIX mode, and `None` in POSIX mode). `shlex.push_token(str)` Push the argument onto the token stack. `shlex.read_token()` Read a raw token. Ignore the pushback stack, and do not interpret source requests. (This is not ordinarily a useful entry point, and is documented here only for the sake of completeness.) `shlex.sourcehook(filename)` When [`shlex`](#shlex.shlex "shlex.shlex") detects a source request (see [`source`](#shlex.shlex.source "shlex.shlex.source") below) this method is given the following token as argument, and expected to return a tuple consisting of a filename and an open file-like object. Normally, this method first strips any quotes off the argument. If the result is an absolute pathname, or there was no previous source request in effect, or the previous source was a stream (such as `sys.stdin`), the result is left alone. Otherwise, if the result is a relative pathname, the directory part of the name of the file immediately before it on the source inclusion stack is prepended (this behavior is like the way the C preprocessor handles `#include "file.h"`). The result of the manipulations is treated as a filename, and returned as the first component of the tuple, with [`open()`](functions#open "open") called on it to yield the second component. (Note: this is the reverse of the order of arguments in instance initialization!) This hook is exposed so that you can use it to implement directory search paths, addition of file extensions, and other namespace hacks. There is no corresponding ‘close’ hook, but a shlex instance will call the [`close()`](io#io.IOBase.close "io.IOBase.close") method of the sourced input stream when it returns EOF. For more explicit control of source stacking, use the [`push_source()`](#shlex.shlex.push_source "shlex.shlex.push_source") and [`pop_source()`](#shlex.shlex.pop_source "shlex.shlex.pop_source") methods. `shlex.push_source(newstream, newfile=None)` Push an input source stream onto the input stack. If the filename argument is specified it will later be available for use in error messages. This is the same method used internally by the [`sourcehook()`](#shlex.shlex.sourcehook "shlex.shlex.sourcehook") method. `shlex.pop_source()` Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream. `shlex.error_leader(infile=None, lineno=None)` This method generates an error message leader in the format of a Unix C compiler error label; the format is `'"%s", line %d: '`, where the `%s` is replaced with the name of the current source file and the `%d` with the current input line number (the optional arguments can be used to override these). This convenience is provided to encourage [`shlex`](#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") users to generate error messages in the standard, parseable format understood by Emacs and other Unix tools. Instances of [`shlex`](#shlex.shlex "shlex.shlex") subclasses have some public instance variables which either control lexical analysis or can be used for debugging: `shlex.commenters` The string of characters that are recognized as comment beginners. All characters from the comment beginner to end of line are ignored. Includes just `'#'` by default. `shlex.wordchars` The string of characters that will accumulate into multi-character tokens. By default, includes all ASCII alphanumerics and underscore. In POSIX mode, the accented characters in the Latin-1 set are also included. If [`punctuation_chars`](#shlex.shlex.punctuation_chars "shlex.shlex.punctuation_chars") is not empty, the characters `~-./*?=`, which can appear in filename specifications and command line parameters, will also be included in this attribute, and any characters which appear in `punctuation_chars` will be removed from `wordchars` if they are present there. If [`whitespace_split`](#shlex.shlex.whitespace_split "shlex.shlex.whitespace_split") is set to `True`, this will have no effect. `shlex.whitespace` Characters that will be considered whitespace and skipped. Whitespace bounds tokens. By default, includes space, tab, linefeed and carriage-return. `shlex.escape` Characters that will be considered as escape. This will be only used in POSIX mode, and includes just `'\'` by default. `shlex.quotes` Characters that will be considered string quotes. The token accumulates until the same quote is encountered again (thus, different quote types protect each other as in the shell.) By default, includes ASCII single and double quotes. `shlex.escapedquotes` Characters in [`quotes`](#shlex.shlex.quotes "shlex.shlex.quotes") that will interpret escape characters defined in [`escape`](#shlex.shlex.escape "shlex.shlex.escape"). This is only used in POSIX mode, and includes just `'"'` by default. `shlex.whitespace_split` If `True`, tokens will only be split in whitespaces. This is useful, for example, for parsing command lines with [`shlex`](#shlex.shlex "shlex.shlex"), getting tokens in a similar way to shell arguments. When used in combination with [`punctuation_chars`](#shlex.shlex.punctuation_chars "shlex.shlex.punctuation_chars"), tokens will be split on whitespace in addition to those characters. Changed in version 3.8: The [`punctuation_chars`](#shlex.shlex.punctuation_chars "shlex.shlex.punctuation_chars") attribute was made compatible with the [`whitespace_split`](#shlex.shlex.whitespace_split "shlex.shlex.whitespace_split") attribute. `shlex.infile` The name of the current input file, as initially set at class instantiation time or stacked by later source requests. It may be useful to examine this when constructing error messages. `shlex.instream` The input stream from which this [`shlex`](#shlex.shlex "shlex.shlex") instance is reading characters. `shlex.source` This attribute is `None` by default. If you assign a string to it, that string will be recognized as a lexical-level inclusion request similar to the `source` keyword in various shells. That is, the immediately following token will be opened as a filename and input will be taken from that stream until EOF, at which point the [`close()`](io#io.IOBase.close "io.IOBase.close") method of that stream will be called and the input source will again become the original input stream. Source requests may be stacked any number of levels deep. `shlex.debug` If this attribute is numeric and `1` or more, a [`shlex`](#shlex.shlex "shlex.shlex") instance will print verbose progress output on its behavior. If you need to use this, you can read the module source code to learn the details. `shlex.lineno` Source line number (count of newlines seen so far plus one). `shlex.token` The token buffer. It may be useful to examine this when catching exceptions. `shlex.eof` Token used to determine end of file. This will be set to the empty string (`''`), in non-POSIX mode, and to `None` in POSIX mode. `shlex.punctuation_chars` A read-only property. Characters that will be considered punctuation. Runs of punctuation characters will be returned as a single token. However, note that no semantic validity checking will be performed: for example, ‘>>>’ could be returned as a token, even though it may not be recognised as such by shells. New in version 3.6. Parsing Rules ------------- When operating in non-POSIX mode, [`shlex`](#shlex.shlex "shlex.shlex") will try to obey to the following rules. * Quote characters are not recognized within words (`Do"Not"Separate` is parsed as the single word `Do"Not"Separate`); * Escape characters are not recognized; * Enclosing characters in quotes preserve the literal value of all characters within the quotes; * Closing quotes separate words (`"Do"Separate` is parsed as `"Do"` and `Separate`); * If [`whitespace_split`](#shlex.shlex.whitespace_split "shlex.shlex.whitespace_split") is `False`, any character not declared to be a word character, whitespace, or a quote will be returned as a single-character token. If it is `True`, [`shlex`](#shlex.shlex "shlex.shlex") will only split words in whitespaces; * EOF is signaled with an empty string (`''`); * It’s not possible to parse empty strings, even if quoted. When operating in POSIX mode, [`shlex`](#shlex.shlex "shlex.shlex") will try to obey to the following parsing rules. * Quotes are stripped out, and do not separate words (`"Do"Not"Separate"` is parsed as the single word `DoNotSeparate`); * Non-quoted escape characters (e.g. `'\'`) preserve the literal value of the next character that follows; * Enclosing characters in quotes which are not part of [`escapedquotes`](#shlex.shlex.escapedquotes "shlex.shlex.escapedquotes") (e.g. `"'"`) preserve the literal value of all characters within the quotes; * Enclosing characters in quotes which are part of [`escapedquotes`](#shlex.shlex.escapedquotes "shlex.shlex.escapedquotes") (e.g. `'"'`) preserves the literal value of all characters within the quotes, with the exception of the characters mentioned in [`escape`](#shlex.shlex.escape "shlex.shlex.escape"). The escape characters retain its special meaning only when followed by the quote in use, or the escape character itself. Otherwise the escape character will be considered a normal character. * EOF is signaled with a [`None`](constants#None "None") value; * Quoted empty strings (`''`) are allowed. Improved Compatibility with Shells ---------------------------------- New in version 3.6. The [`shlex`](#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") class provides compatibility with the parsing performed by common Unix shells like `bash`, `dash`, and `sh`. To take advantage of this compatibility, specify the `punctuation_chars` argument in the constructor. This defaults to `False`, which preserves pre-3.6 behaviour. However, if it is set to `True`, then parsing of the characters `();<>|&` is changed: any run of these characters is returned as a single token. While this is short of a full parser for shells (which would be out of scope for the standard library, given the multiplicity of shells out there), it does allow you to perform processing of command lines more easily than you could otherwise. To illustrate, you can see the difference in the following snippet: ``` >>> import shlex >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")" >>> s = shlex.shlex(text, posix=True) >>> s.whitespace_split = True >>> list(s) ['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)'] >>> s = shlex.shlex(text, posix=True, punctuation_chars=True) >>> s.whitespace_split = True >>> list(s) ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';', '(', 'def', 'ghi', ')'] ``` Of course, tokens will be returned which are not valid for shells, and you’ll need to implement your own error checks on the returned tokens. Instead of passing `True` as the value for the punctuation\_chars parameter, you can pass a string with specific characters, which will be used to determine which characters constitute punctuation. For example: ``` >>> import shlex >>> s = shlex.shlex("a && b || c", punctuation_chars="|") >>> list(s) ['a', '&', '&', 'b', '||', 'c'] ``` Note When `punctuation_chars` is specified, the [`wordchars`](#shlex.shlex.wordchars "shlex.shlex.wordchars") attribute is augmented with the characters `~-./*?=`. That is because these characters can appear in file names (including wildcards) and command-line arguments (e.g. `--color=auto`). Hence: ``` >>> import shlex >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?', ... punctuation_chars=True) >>> list(s) ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?'] ``` However, to match the shell as closely as possible, it is recommended to always use `posix` and [`whitespace_split`](#shlex.shlex.whitespace_split "shlex.shlex.whitespace_split") when using [`punctuation_chars`](#shlex.shlex.punctuation_chars "shlex.shlex.punctuation_chars"), which will negate [`wordchars`](#shlex.shlex.wordchars "shlex.shlex.wordchars") entirely. For best effect, `punctuation_chars` should be set in conjunction with `posix=True`. (Note that `posix=False` is the default for [`shlex`](#shlex.shlex "shlex.shlex").) python getopt — C-style parser for command line options getopt — C-style parser for command line options ================================================ **Source code:** [Lib/getopt.py](https://github.com/python/cpython/tree/3.9/Lib/getopt.py) Note The [`getopt`](#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") module is a parser for command line options whose API is designed to be familiar to users of the C `getopt()` function. Users who are unfamiliar with the C `getopt()` function or who would like to write less code and get better help and error messages should consider using the [`argparse`](argparse#module-argparse "argparse: Command-line option and argument parsing library.") module instead. This module helps scripts to parse the command line arguments in `sys.argv`. It supports the same conventions as the Unix `getopt()` function (including the special meanings of arguments of the form ‘`-`’ and ‘`--`‘). Long options similar to those supported by GNU software may be used as well via an optional third argument. This module provides two functions and an exception: `getopt.getopt(args, shortopts, longopts=[])` Parses command line options and parameter list. *args* is the argument list to be parsed, without the leading reference to the running program. Typically, this means `sys.argv[1:]`. *shortopts* is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (`':'`; i.e., the same format that Unix `getopt()` uses). Note Unlike GNU `getopt()`, after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work. *longopts*, if specified, must be a list of strings with the names of the long options which should be supported. The leading `'--'` characters should not be included in the option name. Long options which require an argument should be followed by an equal sign (`'='`). Optional arguments are not supported. To accept only long options, *shortopts* should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if *longopts* is `['foo', 'frob']`, the option `--fo` will match as `--foo`, but `--f` will not match uniquely, so [`GetoptError`](#getopt.GetoptError "getopt.GetoptError") will be raised. The return value consists of two elements: the first is a list of `(option, value)` pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of *args*). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., `'-x'`) or two hyphens for long options (e.g., `'--long-option'`), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed. `getopt.gnu_getopt(args, shortopts, longopts=[])` This function works like [`getopt()`](#module-getopt "getopt: Portable parser for command line options; support both short and long option names."), except that GNU style scanning mode is used by default. This means that option and non-option arguments may be intermixed. The [`getopt()`](#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") function stops processing options as soon as a non-option argument is encountered. If the first character of the option string is `'+'`, or if the environment variable `POSIXLY_CORRECT` is set, then option processing stops as soon as a non-option argument is encountered. `exception getopt.GetoptError` This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. For long options, an argument given to an option which does not require one will also cause this exception to be raised. The attributes `msg` and `opt` give the error message and related option; if there is no specific option to which the exception relates, `opt` is an empty string. `exception getopt.error` Alias for [`GetoptError`](#getopt.GetoptError "getopt.GetoptError"); for backward compatibility. An example using only Unix style options: ``` >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] ``` Using long option names is equally easy: ``` >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] ``` In a script, typical usage is something like this: ``` import getopt, sys def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None verbose = False for o, a in opts: if o == "-v": verbose = True elif o in ("-h", "--help"): usage() sys.exit() elif o in ("-o", "--output"): output = a else: assert False, "unhandled option" # ... if __name__ == "__main__": main() ``` Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the [`argparse`](argparse#module-argparse "argparse: Command-line option and argument parsing library.") module: ``` import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-o', '--output') parser.add_argument('-v', dest='verbose', action='store_true') args = parser.parse_args() # ... do something with args.output ... # ... do something with args.verbose .. ``` See also `Module` [`argparse`](argparse#module-argparse "argparse: Command-line option and argument parsing library.") Alternative command line option and argument parsing library.
programming_docs
python The Python Profilers The Python Profilers ==================== **Source code:** [Lib/profile.py](https://github.com/python/cpython/tree/3.9/Lib/profile.py) and [Lib/pstats.py](https://github.com/python/cpython/tree/3.9/Lib/pstats.py) Introduction to the profilers ----------------------------- [`cProfile`](#module-cProfile "cProfile") and [`profile`](#module-profile "profile: Python source profiler.") provide *deterministic profiling* of Python programs. A *profile* is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the [`pstats`](#module-pstats "pstats: Statistics object for use with the profiler.") module. The Python standard library provides two different implementations of the same profiling interface: 1. [`cProfile`](#module-cProfile "cProfile") is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs. Based on `lsprof`, contributed by Brett Rosen and Ted Czotter. 2. [`profile`](#module-profile "profile: Python source profiler."), a pure Python module whose interface is imitated by [`cProfile`](#module-cProfile "cProfile"), but which adds significant overhead to profiled programs. If you’re trying to extend the profiler in some way, the task might be easier with this module. Originally designed and written by Jim Roskind. Note The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is [`timeit`](timeit#module-timeit "timeit: Measure the execution time of small code snippets.") for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one. Instant User’s Manual --------------------- This section is provided for users that “don’t want to read the manual.” It provides a very brief overview, and allows a user to rapidly perform profiling on an existing application. To profile a function that takes a single argument, you can do: ``` import cProfile import re cProfile.run('re.compile("foo|bar")') ``` (Use [`profile`](#module-profile "profile: Python source profiler.") instead of [`cProfile`](#module-cProfile "cProfile") if the latter is not available on your system.) The above action would run [`re.compile()`](re#re.compile "re.compile") and print profile results like the following: ``` 197 function calls (192 primitive calls) in 0.002 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 <string>:1(<module>) 1 0.000 0.000 0.001 0.001 re.py:212(compile) 1 0.000 0.000 0.001 0.001 re.py:268(_compile) 1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset) 1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset) 4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction) 3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile) ``` The first line indicates that 197 calls were monitored. Of those calls, 192 were *primitive*, meaning that the call was not induced via recursion. The next line: `Ordered by: standard name`, indicates that the text string in the far right column was used to sort the output. The column headings include: ncalls for the number of calls. tottime for the total time spent in the given function (and excluding time made in calls to sub-functions) percall is the quotient of `tottime` divided by `ncalls` cumtime is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate *even* for recursive functions. percall is the quotient of `cumtime` divided by primitive calls filename:lineno(function) provides the respective data of each function When there are two numbers in the first column (for example `3/1`), it means that the function recursed. The second value is the number of primitive calls and the former is the total number of calls. Note that when the function does not recurse, these two values are the same, and only the single figure is printed. Instead of printing the output at the end of the profile run, you can save the results to a file by specifying a filename to the `run()` function: ``` import cProfile import re cProfile.run('re.compile("foo|bar")', 'restats') ``` The [`pstats.Stats`](#pstats.Stats "pstats.Stats") class reads profile results from a file and formats them in various ways. The files [`cProfile`](#module-cProfile "cProfile") and [`profile`](#module-profile "profile: Python source profiler.") can also be invoked as a script to profile another script. For example: ``` python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py) ``` `-o` writes the profile results to a file instead of to stdout `-s` specifies one of the [`sort_stats()`](#pstats.Stats.sort_stats "pstats.Stats.sort_stats") sort values to sort the output by. This only applies when `-o` is not supplied. `-m` specifies that a module is being profiled instead of a script. New in version 3.7: Added the `-m` option to [`cProfile`](#module-cProfile "cProfile"). New in version 3.8: Added the `-m` option to [`profile`](#module-profile "profile: Python source profiler."). The [`pstats`](#module-pstats "pstats: Statistics object for use with the profiler.") module’s [`Stats`](#pstats.Stats "pstats.Stats") class has a variety of methods for manipulating and printing the data saved into a profile results file: ``` import pstats from pstats import SortKey p = pstats.Stats('restats') p.strip_dirs().sort_stats(-1).print_stats() ``` The [`strip_dirs()`](#pstats.Stats.strip_dirs "pstats.Stats.strip_dirs") method removed the extraneous path from all the module names. The [`sort_stats()`](#pstats.Stats.sort_stats "pstats.Stats.sort_stats") method sorted all the entries according to the standard module/line/name string that is printed. The [`print_stats()`](#pstats.Stats.print_stats "pstats.Stats.print_stats") method printed out all the statistics. You might try the following sort calls: ``` p.sort_stats(SortKey.NAME) p.print_stats() ``` The first call will actually sort the list by function name, and the second call will print out the statistics. The following are some interesting calls to experiment with: ``` p.sort_stats(SortKey.CUMULATIVE).print_stats(10) ``` This sorts the profile by cumulative time in a function, and then only prints the ten most significant lines. If you want to understand what algorithms are taking time, the above line is what you would use. If you were looking to see what functions were looping a lot, and taking a lot of time, you would do: ``` p.sort_stats(SortKey.TIME).print_stats(10) ``` to sort according to time spent within each function, and then print the statistics for the top ten functions. You might also try: ``` p.sort_stats(SortKey.FILENAME).print_stats('__init__') ``` This will sort all the statistics by file name, and then print out statistics for only the class init methods (since they are spelled with `__init__` in them). As one final example, you could try: ``` p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init') ``` This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. To be specific, the list is first culled down to 50% (re: `.5`) of its original size, then only lines containing `init` are maintained, and that sub-sub-list is printed. If you wondered what functions called the above functions, you could now (`p` is still sorted according to the last criteria) do: ``` p.print_callers(.5, 'init') ``` and you would get a list of callers for each of the listed functions. If you want more functionality, you’re going to have to read the manual, or guess what the following functions do: ``` p.print_callees() p.add('restats') ``` Invoked as a script, the [`pstats`](#module-pstats "pstats: Statistics object for use with the profiler.") module is a statistics browser for reading and examining profile dumps. It has a simple line-oriented interface (implemented using [`cmd`](cmd#module-cmd "cmd: Build line-oriented command interpreters.")) and interactive help. profile and cProfile Module Reference ------------------------------------- Both the [`profile`](#module-profile "profile: Python source profiler.") and [`cProfile`](#module-cProfile "cProfile") modules provide the following functions: `profile.run(command, filename=None, sort=-1)` This function takes a single argument that can be passed to the [`exec()`](functions#exec "exec") function, and an optional file name. In all cases this routine executes: ``` exec(command, __main__.__dict__, __main__.__dict__) ``` and gathers profiling statistics from the execution. If no file name is present, then this function automatically creates a [`Stats`](#pstats.Stats "pstats.Stats") instance and prints a simple profiling report. If the sort value is specified, it is passed to this [`Stats`](#pstats.Stats "pstats.Stats") instance to control how the results are sorted. `profile.runctx(command, globals, locals, filename=None, sort=-1)` This function is similar to [`run()`](#profile.run "profile.run"), with added arguments to supply the globals and locals dictionaries for the *command* string. This routine executes: ``` exec(command, globals, locals) ``` and gathers profiling statistics as in the [`run()`](#profile.run "profile.run") function above. `class profile.Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)` This class is normally only used if more precise control over profiling is needed than what the `cProfile.run()` function provides. A custom timer can be supplied for measuring how long code takes to run via the *timer* argument. This must be a function that returns a single number representing the current time. If the number is an integer, the *timeunit* specifies a multiplier that specifies the duration of each unit of time. For example, if the timer returns times measured in thousands of seconds, the time unit would be `.001`. Directly using the [`Profile`](#profile.Profile "profile.Profile") class allows formatting profile results without writing the profile data to a file: ``` import cProfile, pstats, io from pstats import SortKey pr = cProfile.Profile() pr.enable() # ... do something ... pr.disable() s = io.StringIO() sortby = SortKey.CUMULATIVE ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) ``` The [`Profile`](#profile.Profile "profile.Profile") class can also be used as a context manager (supported only in [`cProfile`](#module-cProfile "cProfile") module. see [Context Manager Types](stdtypes#typecontextmanager)): ``` import cProfile with cProfile.Profile() as pr: # ... do something ... pr.print_stats() ``` Changed in version 3.8: Added context manager support. `enable()` Start collecting profiling data. Only in [`cProfile`](#module-cProfile "cProfile"). `disable()` Stop collecting profiling data. Only in [`cProfile`](#module-cProfile "cProfile"). `create_stats()` Stop collecting profiling data and record the results internally as the current profile. `print_stats(sort=-1)` Create a [`Stats`](#pstats.Stats "pstats.Stats") object based on the current profile and print the results to stdout. `dump_stats(filename)` Write the results of the current profile to *filename*. `run(cmd)` Profile the cmd via [`exec()`](functions#exec "exec"). `runctx(cmd, globals, locals)` Profile the cmd via [`exec()`](functions#exec "exec") with the specified global and local environment. `runcall(func, /, *args, **kwargs)` Profile `func(*args, **kwargs)` Note that profiling will only work if the called command/function actually returns. If the interpreter is terminated (e.g. via a [`sys.exit()`](sys#sys.exit "sys.exit") call during the called command/function execution) no profiling results will be printed. The `Stats` Class ----------------- Analysis of the profiler data is done using the [`Stats`](#pstats.Stats "pstats.Stats") class. `class pstats.Stats(*filenames or profile, stream=sys.stdout)` This class constructor creates an instance of a “statistics object” from a *filename* (or list of filenames) or from a `Profile` instance. Output will be printed to the stream specified by *stream*. The file selected by the above constructor must have been created by the corresponding version of [`profile`](#module-profile "profile: Python source profiler.") or [`cProfile`](#module-cProfile "cProfile"). To be specific, there is *no* file compatibility guaranteed with future versions of this profiler, and there is no compatibility with files produced by other profilers, or the same profiler run on a different operating system. If several files are provided, all the statistics for identical functions will be coalesced, so that an overall view of several processes can be considered in a single report. If additional files need to be combined with data in an existing [`Stats`](#pstats.Stats "pstats.Stats") object, the [`add()`](#pstats.Stats.add "pstats.Stats.add") method can be used. Instead of reading the profile data from a file, a `cProfile.Profile` or [`profile.Profile`](#profile.Profile "profile.Profile") object can be used as the profile data source. [`Stats`](#pstats.Stats "pstats.Stats") objects have the following methods: `strip_dirs()` This method for the [`Stats`](#pstats.Stats "pstats.Stats") class removes all leading path information from file names. It is very useful in reducing the size of the printout to fit within (close to) 80 columns. This method modifies the object, and the stripped information is lost. After performing a strip operation, the object is considered to have its entries in a “random” order, as it was just after object initialization and loading. If [`strip_dirs()`](#pstats.Stats.strip_dirs "pstats.Stats.strip_dirs") causes two function names to be indistinguishable (they are on the same line of the same filename, and have the same function name), then the statistics for these two entries are accumulated into a single entry. `add(*filenames)` This method of the [`Stats`](#pstats.Stats "pstats.Stats") class accumulates additional profiling information into the current profiling object. Its arguments should refer to filenames created by the corresponding version of [`profile.run()`](#profile.run "profile.run") or `cProfile.run()`. Statistics for identically named (re: file, line, name) functions are automatically accumulated into single function statistics. `dump_stats(filename)` Save the data loaded into the [`Stats`](#pstats.Stats "pstats.Stats") object to a file named *filename*. The file is created if it does not exist, and is overwritten if it already exists. This is equivalent to the method of the same name on the [`profile.Profile`](#profile.Profile "profile.Profile") and `cProfile.Profile` classes. `sort_stats(*keys)` This method modifies the [`Stats`](#pstats.Stats "pstats.Stats") object by sorting it according to the supplied criteria. The argument can be either a string or a SortKey enum identifying the basis of a sort (example: `'time'`, `'name'`, `SortKey.TIME` or `SortKey.NAME`). The SortKey enums argument have advantage over the string argument in that it is more robust and less error prone. When more than one key is provided, then additional keys are used as secondary criteria when there is equality in all keys selected before them. For example, `sort_stats(SortKey.NAME, SortKey.FILE)` will sort all the entries according to their function name, and resolve all ties (identical function names) by sorting by file name. For the string argument, abbreviations can be used for any key names, as long as the abbreviation is unambiguous. The following are the valid string and SortKey: | Valid String Arg | Valid enum Arg | Meaning | | --- | --- | --- | | `'calls'` | SortKey.CALLS | call count | | `'cumulative'` | SortKey.CUMULATIVE | cumulative time | | `'cumtime'` | N/A | cumulative time | | `'file'` | N/A | file name | | `'filename'` | SortKey.FILENAME | file name | | `'module'` | N/A | file name | | `'ncalls'` | N/A | call count | | `'pcalls'` | SortKey.PCALLS | primitive call count | | `'line'` | SortKey.LINE | line number | | `'name'` | SortKey.NAME | function name | | `'nfl'` | SortKey.NFL | name/file/line | | `'stdname'` | SortKey.STDNAME | standard name | | `'time'` | SortKey.TIME | internal time | | `'tottime'` | N/A | internal time | Note that all sorts on statistics are in descending order (placing most time consuming items first), where as name, file, and line number searches are in ascending order (alphabetical). The subtle distinction between `SortKey.NFL` and `SortKey.STDNAME` is that the standard name is a sort of the name as printed, which means that the embedded line numbers get compared in an odd way. For example, lines 3, 20, and 40 would (if the file names were the same) appear in the string order 20, 3 and 40. In contrast, `SortKey.NFL` does a numeric compare of the line numbers. In fact, `sort_stats(SortKey.NFL)` is the same as `sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)`. For backward-compatibility reasons, the numeric arguments `-1`, `0`, `1`, and `2` are permitted. They are interpreted as `'stdname'`, `'calls'`, `'time'`, and `'cumulative'` respectively. If this old style format (numeric) is used, only one sort key (the numeric key) will be used, and additional arguments will be silently ignored. New in version 3.7: Added the SortKey enum. `reverse_order()` This method for the [`Stats`](#pstats.Stats "pstats.Stats") class reverses the ordering of the basic list within the object. Note that by default ascending vs descending order is properly selected based on the sort key of choice. `print_stats(*restrictions)` This method for the [`Stats`](#pstats.Stats "pstats.Stats") class prints out a report as described in the [`profile.run()`](#profile.run "profile.run") definition. The order of the printing is based on the last [`sort_stats()`](#pstats.Stats.sort_stats "pstats.Stats.sort_stats") operation done on the object (subject to caveats in [`add()`](#pstats.Stats.add "pstats.Stats.add") and [`strip_dirs()`](#pstats.Stats.strip_dirs "pstats.Stats.strip_dirs")). The arguments provided (if any) can be used to limit the list down to the significant entries. Initially, the list is taken to be the complete set of profiled functions. Each restriction is either an integer (to select a count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines), or a string that will interpreted as a regular expression (to pattern match the standard name that is printed). If several restrictions are provided, then they are applied sequentially. For example: ``` print_stats(.1, 'foo:') ``` would first limit the printing to first 10% of list, and then only print functions that were part of filename `.*foo:`. In contrast, the command: ``` print_stats('foo:', .1) ``` would limit the list to all functions having file names `.*foo:`, and then proceed to only print the first 10% of them. `print_callers(*restrictions)` This method for the [`Stats`](#pstats.Stats "pstats.Stats") class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided by [`print_stats()`](#pstats.Stats.print_stats "pstats.Stats.print_stats"), and the definition of the restricting argument is also identical. Each caller is reported on its own line. The format differs slightly depending on the profiler that produced the stats: * With [`profile`](#module-profile "profile: Python source profiler."), a number is shown in parentheses after each caller to show how many times this specific call was made. For convenience, a second non-parenthesized number repeats the cumulative time spent in the function at the right. * With [`cProfile`](#module-cProfile "cProfile"), each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller. `print_callees(*restrictions)` This method for the [`Stats`](#pstats.Stats "pstats.Stats") class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and ordering are identical to the [`print_callers()`](#pstats.Stats.print_callers "pstats.Stats.print_callers") method. `get_stats_profile()` This method returns an instance of StatsProfile, which contains a mapping of function names to instances of FunctionProfile. Each FunctionProfile instance holds information related to the function’s profile such as how long the function took to run, how many times it was called, etc… New in version 3.9: Added the following dataclasses: StatsProfile, FunctionProfile. Added the following function: get\_stats\_profile. What Is Deterministic Profiling? -------------------------------- *Deterministic profiling* is meant to reflect the fact that all *function call*, *function return*, and *exception* events are monitored, and precise timings are made for the intervals between these events (during which time the user’s code is executing). In contrast, *statistical profiling* (which is not done by this module) randomly samples the effective instruction pointer, and deduces where time is being spent. The latter technique traditionally involves less overhead (as the code does not need to be instrumented), but provides only relative indications of where time is being spent. In Python, since there is an interpreter active during execution, the presence of instrumented code is not required in order to do deterministic profiling. Python automatically provides a *hook* (optional callback) for each event. In addition, the interpreted nature of Python tends to add so much overhead to execution, that deterministic profiling tends to only add small processing overhead in typical applications. The result is that deterministic profiling is not that expensive, yet provides extensive run time statistics about the execution of a Python program. Call count statistics can be used to identify bugs in code (surprising counts), and to identify possible inline-expansion points (high call counts). Internal time statistics can be used to identify “hot loops” that should be carefully optimized. Cumulative time statistics should be used to identify high level errors in the selection of algorithms. Note that the unusual handling of cumulative times in this profiler allows statistics for recursive implementations of algorithms to be directly compared to iterative implementations. Limitations ----------- One limitation has to do with accuracy of timing information. There is a fundamental problem with deterministic profilers involving accuracy. The most obvious restriction is that the underlying “clock” is only ticking at a rate (typically) of about .001 seconds. Hence no measurements will be more accurate than the underlying clock. If enough measurements are taken, then the “error” will tend to average out. Unfortunately, removing this first error induces a second source of error. The second problem is that it “takes a while” from when an event is dispatched until the profiler’s call to get the time actually *gets* the state of the clock. Similarly, there is a certain lag when exiting the profiler event handler from the time that the clock’s value was obtained (and then squirreled away), until the user’s code is once again executing. As a result, functions that are called many times, or call many functions, will typically accumulate this error. The error that accumulates in this fashion is typically less than the accuracy of the clock (less than one clock tick), but it *can* accumulate and become very significant. The problem is more important with [`profile`](#module-profile "profile: Python source profiler.") than with the lower-overhead [`cProfile`](#module-cProfile "cProfile"). For this reason, [`profile`](#module-profile "profile: Python source profiler.") provides a means of calibrating itself for a given platform so that this error can be probabilistically (on the average) removed. After the profiler is calibrated, it will be more accurate (in a least square sense), but it will sometimes produce negative numbers (when call counts are exceptionally low, and the gods of probability work against you :-). ) Do *not* be alarmed by negative numbers in the profile. They should *only* appear if you have calibrated your profiler, and the results are actually better than without calibration. Calibration ----------- The profiler of the [`profile`](#module-profile "profile: Python source profiler.") module subtracts a constant from each event handling time to compensate for the overhead of calling the time function, and socking away the results. By default, the constant is 0. The following procedure can be used to obtain a better constant for a given platform (see [Limitations](#profile-limitations)). ``` import profile pr = profile.Profile() for i in range(5): print(pr.calibrate(10000)) ``` The method executes the number of Python calls given by the argument, directly and again under the profiler, measuring the time for both. It then computes the hidden overhead per profiler event, and returns that as a float. For example, on a 1.8Ghz Intel Core i5 running macOS, and using Python’s time.process\_time() as the timer, the magical number is about 4.04e-6. The object of this exercise is to get a fairly consistent result. If your computer is *very* fast, or your timer function has poor resolution, you might have to pass 100000, or even 1000000, to get consistent results. When you have a consistent answer, there are three ways you can use it: ``` import profile # 1. Apply computed bias to all Profile instances created hereafter. profile.Profile.bias = your_computed_bias # 2. Apply computed bias to a specific Profile instance. pr = profile.Profile() pr.bias = your_computed_bias # 3. Specify computed bias in instance constructor. pr = profile.Profile(bias=your_computed_bias) ``` If you have a choice, you are better off choosing a smaller constant, and then your results will “less often” show up as negative in profile statistics. Using a custom timer -------------------- If you want to change how current time is determined (for example, to force use of wall-clock time or elapsed process time), pass the timing function you want to the `Profile` class constructor: ``` pr = profile.Profile(your_time_func) ``` The resulting profiler will then call `your_time_func`. Depending on whether you are using [`profile.Profile`](#profile.Profile "profile.Profile") or `cProfile.Profile`, `your_time_func`’s return value will be interpreted differently: [`profile.Profile`](#profile.Profile "profile.Profile") `your_time_func` should return a single number, or a list of numbers whose sum is the current time (like what [`os.times()`](os#os.times "os.times") returns). If the function returns a single time number, or the list of returned numbers has length 2, then you will get an especially fast version of the dispatch routine. Be warned that you should calibrate the profiler class for the timer function that you choose (see [Calibration](#profile-calibration)). For most machines, a timer that returns a lone integer value will provide the best results in terms of low overhead during profiling. ([`os.times()`](os#os.times "os.times") is *pretty* bad, as it returns a tuple of floating point values). If you want to substitute a better timer in the cleanest fashion, derive a class and hardwire a replacement dispatch method that best handles your timer call, along with the appropriate calibration constant. `cProfile.Profile` `your_time_func` should return a single number. If it returns integers, you can also invoke the class constructor with a second argument specifying the real duration of one unit of time. For example, if `your_integer_time_func` returns times measured in thousands of seconds, you would construct the `Profile` instance as follows: ``` pr = cProfile.Profile(your_integer_time_func, 0.001) ``` As the `cProfile.Profile` class cannot be calibrated, custom timer functions should be used with care and should be as fast as possible. For the best results with a custom timer, it might be necessary to hard-code it in the C source of the internal `_lsprof` module. Python 3.3 adds several new functions in [`time`](time#module-time "time: Time access and conversions.") that can be used to make precise measurements of process or wall-clock time. For example, see [`time.perf_counter()`](time#time.perf_counter "time.perf_counter").
programming_docs
python email.generator: Generating MIME documents email.generator: Generating MIME documents ========================================== **Source code:** [Lib/email/generator.py](https://github.com/python/cpython/tree/3.9/Lib/email/generator.py) One of the most common tasks is to generate the flat (serialized) version of the email message represented by a message object structure. You will need to do this if you want to send your message via [`smtplib.SMTP.sendmail()`](smtplib#smtplib.SMTP.sendmail "smtplib.SMTP.sendmail") or the [`nntplib`](nntplib#module-nntplib "nntplib: NNTP protocol client (requires sockets). (deprecated)") module, or print the message on the console. Taking a message object structure and producing a serialized representation is the job of the generator classes. As with the [`email.parser`](email.parser#module-email.parser "email.parser: Parse flat text email messages to produce a message object structure.") module, you aren’t limited to the functionality of the bundled generator; you could write one from scratch yourself. However the bundled generator knows how to generate most email in a standards-compliant way, should handle MIME and non-MIME email messages just fine, and is designed so that the bytes-oriented parsing and generation operations are inverses, assuming the same non-transforming [`policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") is used for both. That is, parsing the serialized byte stream via the [`BytesParser`](email.parser#email.parser.BytesParser "email.parser.BytesParser") class and then regenerating the serialized byte stream using [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator") should produce output identical to the input [1](#id3). (On the other hand, using the generator on an [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") constructed by program may result in changes to the [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") object as defaults are filled in.) The [`Generator`](#email.generator.Generator "email.generator.Generator") class can be used to flatten a message into a text (as opposed to binary) serialized representation, but since Unicode cannot represent binary data directly, the message is of necessity transformed into something that contains only ASCII characters, using the standard email RFC Content Transfer Encoding techniques for encoding email messages for transport over channels that are not “8 bit clean”. To accommodate reproducible processing of SMIME-signed messages [`Generator`](#email.generator.Generator "email.generator.Generator") disables header folding for message parts of type `multipart/signed` and all subparts. `class email.generator.BytesGenerator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)` Return a [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator") object that will write any message provided to the [`flatten()`](#email.generator.BytesGenerator.flatten "email.generator.BytesGenerator.flatten") method, or any surrogateescape encoded text provided to the [`write()`](#email.generator.BytesGenerator.write "email.generator.BytesGenerator.write") method, to the [file-like object](../glossary#term-file-like-object) *outfp*. *outfp* must support a `write` method that accepts binary data. If optional *mangle\_from\_* is `True`, put a `>` character in front of any line in the body that starts with the exact string `"From "`, that is `From` followed by a space at the beginning of a line. *mangle\_from\_* defaults to the value of the [`mangle_from_`](email.policy#email.policy.Policy.mangle_from_ "email.policy.Policy.mangle_from_") setting of the *policy* (which is `True` for the [`compat32`](email.policy#email.policy.compat32 "email.policy.compat32") policy and `False` for all others). *mangle\_from\_* is intended for use when messages are stored in unix mbox format (see [`mailbox`](mailbox#module-mailbox "mailbox: Manipulate mailboxes in various formats") and [WHY THE CONTENT-LENGTH FORMAT IS BAD](https://www.jwz.org/doc/content-length.html)). If *maxheaderlen* is not `None`, refold any header lines that are longer than *maxheaderlen*, or if `0`, do not rewrap any headers. If *manheaderlen* is `None` (the default), wrap headers and other message lines according to the *policy* settings. If *policy* is specified, use that policy to control message generation. If *policy* is `None` (the default), use the policy associated with the [`Message`](email.compat32-message#email.message.Message "email.message.Message") or [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") object passed to `flatten` to control the message generation. See [`email.policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") for details on what *policy* controls. New in version 3.2. Changed in version 3.3: Added the *policy* keyword. Changed in version 3.6: The default behavior of the *mangle\_from\_* and *maxheaderlen* parameters is to follow the policy. `flatten(msg, unixfrom=False, linesep=None)` Print the textual representation of the message object structure rooted at *msg* to the output file specified when the [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator") instance was created. If the [`policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") option [`cte_type`](email.policy#email.policy.Policy.cte_type "email.policy.Policy.cte_type") is `8bit` (the default), copy any headers in the original parsed message that have not been modified to the output with any bytes with the high bit set reproduced as in the original, and preserve the non-ASCII *Content-Transfer-Encoding* of any body parts that have them. If `cte_type` is `7bit`, convert the bytes with the high bit set as needed using an ASCII-compatible *Content-Transfer-Encoding*. That is, transform parts with non-ASCII *Content-Transfer-Encoding* (*Content-Transfer-Encoding: 8bit*) to an ASCII compatible *Content-Transfer-Encoding*, and encode RFC-invalid non-ASCII bytes in headers using the MIME `unknown-8bit` character set, thus rendering them RFC-compliant. If *unixfrom* is `True`, print the envelope header delimiter used by the Unix mailbox format (see [`mailbox`](mailbox#module-mailbox "mailbox: Manipulate mailboxes in various formats")) before the first of the [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) headers of the root message object. If the root object has no envelope header, craft a standard one. The default is `False`. Note that for subparts, no envelope header is ever printed. If *linesep* is not `None`, use it as the separator character between all the lines of the flattened message. If *linesep* is `None` (the default), use the value specified in the *policy*. `clone(fp)` Return an independent clone of this [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator") instance with the exact same option settings, and *fp* as the new *outfp*. `write(s)` Encode *s* using the `ASCII` codec and the `surrogateescape` error handler, and pass it to the *write* method of the *outfp* passed to the [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator")’s constructor. As a convenience, [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") provides the methods [`as_bytes()`](email.message#email.message.EmailMessage.as_bytes "email.message.EmailMessage.as_bytes") and `bytes(aMessage)` (a.k.a. [`__bytes__()`](email.message#email.message.EmailMessage.__bytes__ "email.message.EmailMessage.__bytes__")), which simplify the generation of a serialized binary representation of a message object. For more detail, see [`email.message`](email.message#module-email.message "email.message: The base class representing email messages."). Because strings cannot represent binary data, the [`Generator`](#email.generator.Generator "email.generator.Generator") class must convert any binary data in any message it flattens to an ASCII compatible format, by converting them to an ASCII compatible *Content-Transfer\_Encoding*. Using the terminology of the email RFCs, you can think of this as [`Generator`](#email.generator.Generator "email.generator.Generator") serializing to an I/O stream that is not “8 bit clean”. In other words, most applications will want to be using [`BytesGenerator`](#email.generator.BytesGenerator "email.generator.BytesGenerator"), and not [`Generator`](#email.generator.Generator "email.generator.Generator"). `class email.generator.Generator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)` Return a [`Generator`](#email.generator.Generator "email.generator.Generator") object that will write any message provided to the [`flatten()`](#email.generator.Generator.flatten "email.generator.Generator.flatten") method, or any text provided to the [`write()`](#email.generator.Generator.write "email.generator.Generator.write") method, to the [file-like object](../glossary#term-file-like-object) *outfp*. *outfp* must support a `write` method that accepts string data. If optional *mangle\_from\_* is `True`, put a `>` character in front of any line in the body that starts with the exact string `"From "`, that is `From` followed by a space at the beginning of a line. *mangle\_from\_* defaults to the value of the [`mangle_from_`](email.policy#email.policy.Policy.mangle_from_ "email.policy.Policy.mangle_from_") setting of the *policy* (which is `True` for the [`compat32`](email.policy#email.policy.compat32 "email.policy.compat32") policy and `False` for all others). *mangle\_from\_* is intended for use when messages are stored in unix mbox format (see [`mailbox`](mailbox#module-mailbox "mailbox: Manipulate mailboxes in various formats") and [WHY THE CONTENT-LENGTH FORMAT IS BAD](https://www.jwz.org/doc/content-length.html)). If *maxheaderlen* is not `None`, refold any header lines that are longer than *maxheaderlen*, or if `0`, do not rewrap any headers. If *manheaderlen* is `None` (the default), wrap headers and other message lines according to the *policy* settings. If *policy* is specified, use that policy to control message generation. If *policy* is `None` (the default), use the policy associated with the [`Message`](email.compat32-message#email.message.Message "email.message.Message") or [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") object passed to `flatten` to control the message generation. See [`email.policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") for details on what *policy* controls. Changed in version 3.3: Added the *policy* keyword. Changed in version 3.6: The default behavior of the *mangle\_from\_* and *maxheaderlen* parameters is to follow the policy. `flatten(msg, unixfrom=False, linesep=None)` Print the textual representation of the message object structure rooted at *msg* to the output file specified when the [`Generator`](#email.generator.Generator "email.generator.Generator") instance was created. If the [`policy`](email.policy#module-email.policy "email.policy: Controlling the parsing and generating of messages") option [`cte_type`](email.policy#email.policy.Policy.cte_type "email.policy.Policy.cte_type") is `8bit`, generate the message as if the option were set to `7bit`. (This is required because strings cannot represent non-ASCII bytes.) Convert any bytes with the high bit set as needed using an ASCII-compatible *Content-Transfer-Encoding*. That is, transform parts with non-ASCII *Content-Transfer-Encoding* (*Content-Transfer-Encoding: 8bit*) to an ASCII compatible *Content-Transfer-Encoding*, and encode RFC-invalid non-ASCII bytes in headers using the MIME `unknown-8bit` character set, thus rendering them RFC-compliant. If *unixfrom* is `True`, print the envelope header delimiter used by the Unix mailbox format (see [`mailbox`](mailbox#module-mailbox "mailbox: Manipulate mailboxes in various formats")) before the first of the [**RFC 5322**](https://tools.ietf.org/html/rfc5322.html) headers of the root message object. If the root object has no envelope header, craft a standard one. The default is `False`. Note that for subparts, no envelope header is ever printed. If *linesep* is not `None`, use it as the separator character between all the lines of the flattened message. If *linesep* is `None` (the default), use the value specified in the *policy*. Changed in version 3.2: Added support for re-encoding `8bit` message bodies, and the *linesep* argument. `clone(fp)` Return an independent clone of this [`Generator`](#email.generator.Generator "email.generator.Generator") instance with the exact same options, and *fp* as the new *outfp*. `write(s)` Write *s* to the *write* method of the *outfp* passed to the [`Generator`](#email.generator.Generator "email.generator.Generator")’s constructor. This provides just enough file-like API for [`Generator`](#email.generator.Generator "email.generator.Generator") instances to be used in the [`print()`](functions#print "print") function. As a convenience, [`EmailMessage`](email.message#email.message.EmailMessage "email.message.EmailMessage") provides the methods [`as_string()`](email.message#email.message.EmailMessage.as_string "email.message.EmailMessage.as_string") and `str(aMessage)` (a.k.a. [`__str__()`](email.message#email.message.EmailMessage.__str__ "email.message.EmailMessage.__str__")), which simplify the generation of a formatted string representation of a message object. For more detail, see [`email.message`](email.message#module-email.message "email.message: The base class representing email messages."). The [`email.generator`](#module-email.generator "email.generator: Generate flat text email messages from a message structure.") module also provides a derived class, [`DecodedGenerator`](#email.generator.DecodedGenerator "email.generator.DecodedGenerator"), which is like the [`Generator`](#email.generator.Generator "email.generator.Generator") base class, except that non-*text* parts are not serialized, but are instead represented in the output stream by a string derived from a template filled in with information about the part. `class email.generator.DecodedGenerator(outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None)` Act like [`Generator`](#email.generator.Generator "email.generator.Generator"), except that for any subpart of the message passed to [`Generator.flatten()`](#email.generator.Generator.flatten "email.generator.Generator.flatten"), if the subpart is of main type *text*, print the decoded payload of the subpart, and if the main type is not *text*, instead of printing it fill in the string *fmt* using information from the part and print the resulting filled-in string. To fill in *fmt*, execute `fmt % part_info`, where `part_info` is a dictionary composed of the following keys and values: * `type` – Full MIME type of the non-*text* part * `maintype` – Main MIME type of the non-*text* part * `subtype` – Sub-MIME type of the non-*text* part * `filename` – Filename of the non-*text* part * `description` – Description associated with the non-*text* part * `encoding` – Content transfer encoding of the non-*text* part If *fmt* is `None`, use the following default *fmt*: “[Non-text (%(type)s) part of message omitted, filename %(filename)s]” Optional *\_mangle\_from\_* and *maxheaderlen* are as with the [`Generator`](#email.generator.Generator "email.generator.Generator") base class. #### Footnotes `1` This statement assumes that you use the appropriate setting for `unixfrom`, and that there are no `policy` settings calling for automatic adjustments (for example, `refold_source` must be `none`, which is *not* the default). It is also not 100% true, since if the message does not conform to the RFC standards occasionally information about the exact original text is lost during parsing error recovery. It is a goal to fix these latter edge cases when possible. python pyclbr — Python module browser support pyclbr — Python module browser support ====================================== **Source code:** [Lib/pyclbr.py](https://github.com/python/cpython/tree/3.9/Lib/pyclbr.py) The [`pyclbr`](#module-pyclbr "pyclbr: Supports information extraction for a Python module browser.") module provides limited information about the functions, classes, and methods defined in a Python-coded module. The information is sufficient to implement a module browser. The information is extracted from the Python source code rather than by importing the module, so this module is safe to use with untrusted code. This restriction makes it impossible to use this module with modules not implemented in Python, including all standard and optional extension modules. `pyclbr.readmodule(module, path=None)` Return a dictionary mapping module-level class names to class descriptors. If possible, descriptors for imported base classes are included. Parameter *module* is a string with the name of the module to read; it may be the name of a module within a package. If given, *path* is a sequence of directory paths prepended to `sys.path`, which is used to locate the module source code. This function is the original interface and is only kept for back compatibility. It returns a filtered version of the following. `pyclbr.readmodule_ex(module, path=None)` Return a dictionary-based tree containing a function or class descriptors for each function and class defined in the module with a `def` or `class` statement. The returned dictionary maps module-level function and class names to their descriptors. Nested objects are entered into the children dictionary of their parent. As with readmodule, *module* names the module to be read and *path* is prepended to sys.path. If the module being read is a package, the returned dictionary has a key `'__path__'` whose value is a list containing the package search path. New in version 3.7: Descriptors for nested definitions. They are accessed through the new children attribute. Each has a new parent attribute. The descriptors returned by these functions are instances of Function and Class classes. Users are not expected to create instances of these classes. Function Objects ---------------- Class `Function` instances describe functions defined by def statements. They have the following attributes: `Function.file` Name of the file in which the function is defined. `Function.module` The name of the module defining the function described. `Function.name` The name of the function. `Function.lineno` The line number in the file where the definition starts. `Function.parent` For top-level functions, None. For nested functions, the parent. New in version 3.7. `Function.children` A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7. Class Objects ------------- Class `Class` instances describe classes defined by class statements. They have the same attributes as Functions and two more. `Class.file` Name of the file in which the class is defined. `Class.module` The name of the module defining the class described. `Class.name` The name of the class. `Class.lineno` The line number in the file where the definition starts. `Class.parent` For top-level classes, None. For nested classes, the parent. New in version 3.7. `Class.children` A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7. `Class.super` A list of `Class` objects which describe the immediate base classes of the class being described. Classes which are named as superclasses but which are not discoverable by [`readmodule_ex()`](#pyclbr.readmodule_ex "pyclbr.readmodule_ex") are listed as a string with the class name instead of as `Class` objects. `Class.methods` A dictionary mapping method names to line numbers. This can be derived from the newer children dictionary, but remains for back-compatibility.
programming_docs
python pickle — Python object serialization pickle — Python object serialization ==================================== **Source code:** [Lib/pickle.py](https://github.com/python/cpython/tree/3.9/Lib/pickle.py) The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module implements binary protocols for serializing and de-serializing a Python object structure. *“Pickling”* is the process whereby a Python object hierarchy is converted into a byte stream, and *“unpickling”* is the inverse operation, whereby a byte stream (from a [binary file](../glossary#term-binary-file) or [bytes-like object](../glossary#term-bytes-like-object)) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1](#id7) or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”. Warning The `pickle` module **is not secure**. Only unpickle data you trust. It is possible to construct malicious pickle data which will **execute arbitrary code during unpickling**. Never unpickle data that could have come from an untrusted source, or that could have been tampered with. Consider signing data with [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation") if you need to ensure that it has not been tampered with. Safer serialization formats such as [`json`](json#module-json "json: Encode and decode the JSON format.") may be more appropriate if you are processing untrusted data. See [Comparison with json](#comparison-with-json). Relationship to other Python modules ------------------------------------ ### Comparison with `marshal` Python has a more primitive serialization module called [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints)."), but in general [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") should always be the preferred way to serialize Python objects. [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") exists primarily to support Python’s `.pyc` files. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module differs from [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") in several significant ways: * The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module keeps track of the objects it has already serialized, so that later references to the same object won’t be serialized again. [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") doesn’t do this. This has implications both for recursive objects and object sharing. Recursive objects are objects that contain references to themselves. These are not handled by marshal, and in fact, attempting to marshal recursive objects will crash your Python interpreter. Object sharing happens when there are multiple references to the same object in different places in the object hierarchy being serialized. [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") stores such objects only once, and ensures that all other references point to the master copy. Shared objects remain shared, which can be very important for mutable objects. * [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") cannot be used to serialize user-defined classes and their instances. [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") can save and restore class instances transparently, however the class definition must be importable and live in the same module as when the object was stored. * The [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") serialization format is not guaranteed to be portable across Python versions. Because its primary job in life is to support `.pyc` files, the Python implementers reserve the right to change the serialization format in non-backwards compatible ways should the need arise. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") serialization format is guaranteed to be backwards compatible across Python releases provided a compatible pickle protocol is chosen and pickling and unpickling code deals with Python 2 to Python 3 type differences if your data is crossing that unique breaking change language boundary. ### Comparison with `json` There are fundamental differences between the pickle protocols and [JSON (JavaScript Object Notation)](http://json.org): * JSON is a text serialization format (it outputs unicode text, although most of the time it is then encoded to `utf-8`), while pickle is a binary serialization format; * JSON is human-readable, while pickle is not; * JSON is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific; * JSON, by default, can only represent a subset of the Python built-in types, and no custom classes; pickle can represent an extremely large number of Python types (many of them automatically, by clever usage of Python’s introspection facilities; complex cases can be tackled by implementing [specific object APIs](#pickle-inst)); * Unlike pickle, deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability. See also The [`json`](json#module-json "json: Encode and decode the JSON format.") module: a standard library module allowing JSON serialization and deserialization. Data stream format ------------------ The data format used by [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") is Python-specific. This has the advantage that there are no restrictions imposed by external standards such as JSON or XDR (which can’t represent pointer sharing); however it means that non-Python programs may not be able to reconstruct pickled Python objects. By default, the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") data format uses a relatively compact binary representation. If you need optimal size characteristics, you can efficiently [compress](archiving) pickled data. The module [`pickletools`](pickletools#module-pickletools "pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.") contains tools for analyzing data streams generated by [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back."). [`pickletools`](pickletools#module-pickletools "pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.") source code has extensive comments about opcodes used by pickle protocols. There are currently 6 different protocols which can be used for pickling. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. * Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python. * Protocol version 1 is an old binary format which is also compatible with earlier versions of Python. * Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of [new-style classes](../glossary#term-new-style-class). Refer to [**PEP 307**](https://www.python.org/dev/peps/pep-0307) for information about improvements brought by protocol 2. * Protocol version 3 was added in Python 3.0. It has explicit support for [`bytes`](stdtypes#bytes "bytes") objects and cannot be unpickled by Python 2.x. This was the default protocol in Python 3.0–3.7. * Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. It is the default protocol starting with Python 3.8. Refer to [**PEP 3154**](https://www.python.org/dev/peps/pep-3154) for information about improvements brought by protocol 4. * Protocol version 5 was added in Python 3.8. It adds support for out-of-band data and speedup for in-band data. Refer to [**PEP 574**](https://www.python.org/dev/peps/pep-0574) for information about improvements brought by protocol 5. Note Serialization is a more primitive notion than persistence; although [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") reads and writes file objects, it does not handle the issue of naming persistent objects, nor the (even more complicated) issue of concurrent access to persistent objects. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure. Perhaps the most obvious thing to do with these byte streams is to write them onto a file, but it is also conceivable to send them across a network or store them in a database. The [`shelve`](shelve#module-shelve "shelve: Python object persistence.") module provides a simple interface to pickle and unpickle objects on DBM-style database files. Module Interface ---------------- To serialize an object hierarchy, you simply call the [`dumps()`](#pickle.dumps "pickle.dumps") function. Similarly, to de-serialize a data stream, you call the [`loads()`](#pickle.loads "pickle.loads") function. However, if you want more control over serialization and de-serialization, you can create a [`Pickler`](#pickle.Pickler "pickle.Pickler") or an [`Unpickler`](#pickle.Unpickler "pickle.Unpickler") object, respectively. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module provides the following constants: `pickle.HIGHEST_PROTOCOL` An integer, the highest [protocol version](#pickle-protocols) available. This value can be passed as a *protocol* value to functions [`dump()`](#pickle.dump "pickle.dump") and [`dumps()`](#pickle.dumps "pickle.dumps") as well as the [`Pickler`](#pickle.Pickler "pickle.Pickler") constructor. `pickle.DEFAULT_PROTOCOL` An integer, the default [protocol version](#pickle-protocols) used for pickling. May be less than [`HIGHEST_PROTOCOL`](#pickle.HIGHEST_PROTOCOL "pickle.HIGHEST_PROTOCOL"). Currently the default protocol is 4, first introduced in Python 3.4 and incompatible with previous versions. Changed in version 3.0: The default protocol is 3. Changed in version 3.8: The default protocol is 4. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module provides the following functions to make the pickling process more convenient: `pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)` Write the pickled representation of the object *obj* to the open [file object](../glossary#term-file-object) *file*. This is equivalent to `Pickler(file, protocol).dump(obj)`. Arguments *file*, *protocol*, *fix\_imports* and *buffer\_callback* have the same meaning as in the [`Pickler`](#pickle.Pickler "pickle.Pickler") constructor. Changed in version 3.8: The *buffer\_callback* argument was added. `pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)` Return the pickled representation of the object *obj* as a [`bytes`](stdtypes#bytes "bytes") object, instead of writing it to a file. Arguments *protocol*, *fix\_imports* and *buffer\_callback* have the same meaning as in the [`Pickler`](#pickle.Pickler "pickle.Pickler") constructor. Changed in version 3.8: The *buffer\_callback* argument was added. `pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)` Read the pickled representation of an object from the open [file object](../glossary#term-file-object) *file* and return the reconstituted object hierarchy specified therein. This is equivalent to `Unpickler(file).load()`. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled representation of the object are ignored. Arguments *file*, *fix\_imports*, *encoding*, *errors*, *strict* and *buffers* have the same meaning as in the [`Unpickler`](#pickle.Unpickler "pickle.Unpickler") constructor. Changed in version 3.8: The *buffers* argument was added. `pickle.loads(data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)` Return the reconstituted object hierarchy of the pickled representation *data* of an object. *data* must be a [bytes-like object](../glossary#term-bytes-like-object). The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled representation of the object are ignored. Arguments *fix\_imports*, *encoding*, *errors*, *strict* and *buffers* have the same meaning as in the [`Unpickler`](#pickle.Unpickler "pickle.Unpickler") constructor. Changed in version 3.8: The *buffers* argument was added. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module defines three exceptions: `exception pickle.PickleError` Common base class for the other pickling exceptions. It inherits [`Exception`](exceptions#Exception "Exception"). `exception pickle.PicklingError` Error raised when an unpicklable object is encountered by [`Pickler`](#pickle.Pickler "pickle.Pickler"). It inherits [`PickleError`](#pickle.PickleError "pickle.PickleError"). Refer to [What can be pickled and unpickled?](#pickle-picklable) to learn what kinds of objects can be pickled. `exception pickle.UnpicklingError` Error raised when there is a problem unpickling an object, such as a data corruption or a security violation. It inherits [`PickleError`](#pickle.PickleError "pickle.PickleError"). Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) AttributeError, EOFError, ImportError, and IndexError. The [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module exports three classes, [`Pickler`](#pickle.Pickler "pickle.Pickler"), [`Unpickler`](#pickle.Unpickler "pickle.Unpickler") and [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer"): `class pickle.Pickler(file, protocol=None, *, fix_imports=True, buffer_callback=None)` This takes a binary file for writing a pickle data stream. The optional *protocol* argument, an integer, tells the pickler to use the given protocol; supported protocols are 0 to [`HIGHEST_PROTOCOL`](#pickle.HIGHEST_PROTOCOL "pickle.HIGHEST_PROTOCOL"). If not specified, the default is [`DEFAULT_PROTOCOL`](#pickle.DEFAULT_PROTOCOL "pickle.DEFAULT_PROTOCOL"). If a negative number is specified, [`HIGHEST_PROTOCOL`](#pickle.HIGHEST_PROTOCOL "pickle.HIGHEST_PROTOCOL") is selected. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an [`io.BytesIO`](io#io.BytesIO "io.BytesIO") instance, or any other custom object that meets this interface. If *fix\_imports* is true and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. If *buffer\_callback* is None (the default), buffer views are serialized into *file* as part of the pickle stream. If *buffer\_callback* is not None, then it can be called any number of times with a buffer view. If the callback returns a false value (such as None), the given buffer is [out-of-band](#pickle-oob); otherwise the buffer is serialized in-band, i.e. inside the pickle stream. It is an error if *buffer\_callback* is not None and *protocol* is None or smaller than 5. Changed in version 3.8: The *buffer\_callback* argument was added. `dump(obj)` Write the pickled representation of *obj* to the open file object given in the constructor. `persistent_id(obj)` Do nothing by default. This exists so a subclass can override it. If [`persistent_id()`](#pickle.Pickler.persistent_id "pickle.Pickler.persistent_id") returns `None`, *obj* is pickled as usual. Any other value causes [`Pickler`](#pickle.Pickler "pickle.Pickler") to emit the returned value as a persistent ID for *obj*. The meaning of this persistent ID should be defined by [`Unpickler.persistent_load()`](#pickle.Unpickler.persistent_load "pickle.Unpickler.persistent_load"). Note that the value returned by [`persistent_id()`](#pickle.Pickler.persistent_id "pickle.Pickler.persistent_id") cannot itself have a persistent ID. See [Persistence of External Objects](#pickle-persistent) for details and examples of uses. `dispatch_table` A pickler object’s dispatch table is a registry of *reduction functions* of the kind which can be declared using [`copyreg.pickle()`](copyreg#copyreg.pickle "copyreg.pickle"). It is a mapping whose keys are classes and whose values are reduction functions. A reduction function takes a single argument of the associated class and should conform to the same interface as a [`__reduce__()`](#object.__reduce__ "object.__reduce__") method. By default, a pickler object will not have a [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table") attribute, and it will instead use the global dispatch table managed by the [`copyreg`](copyreg#module-copyreg "copyreg: Register pickle support functions.") module. However, to customize the pickling for a specific pickler object one can set the [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table") attribute to a dict-like object. Alternatively, if a subclass of [`Pickler`](#pickle.Pickler "pickle.Pickler") has a [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table") attribute then this will be used as the default dispatch table for instances of that class. See [Dispatch Tables](#pickle-dispatch) for usage examples. New in version 3.3. `reducer_override(obj)` Special reducer that can be defined in [`Pickler`](#pickle.Pickler "pickle.Pickler") subclasses. This method has priority over any reducer in the [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table"). It should conform to the same interface as a [`__reduce__()`](#object.__reduce__ "object.__reduce__") method, and can optionally return `NotImplemented` to fallback on [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table")-registered reducers to pickle `obj`. For a detailed example, see [Custom Reduction for Types, Functions, and Other Objects](#reducer-override). New in version 3.8. `fast` Deprecated. Enable fast mode if set to a true value. The fast mode disables the usage of memo, therefore speeding the pickling process by not generating superfluous PUT opcodes. It should not be used with self-referential objects, doing otherwise will cause [`Pickler`](#pickle.Pickler "pickle.Pickler") to recurse infinitely. Use [`pickletools.optimize()`](pickletools#pickletools.optimize "pickletools.optimize") if you need more compact pickles. `class pickle.Unpickler(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)` This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no protocol argument is needed. The argument *file* must have three methods, a read() method that takes an integer argument, a readinto() method that takes a buffer argument and a readline() method that requires no arguments, as in the [`io.BufferedIOBase`](io#io.BufferedIOBase "io.BufferedIOBase") interface. Thus *file* can be an on-disk file opened for binary reading, an [`io.BytesIO`](io#io.BytesIO "io.BytesIO") object, or any other custom object that meets this interface. The optional arguments *fix\_imports*, *encoding* and *errors* are used to control compatibility support for pickle stream generated by Python 2. If *fix\_imports* is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The *encoding* can be ‘bytes’ to read these 8-bit string instances as bytes objects. Using `encoding='latin1'` is required for unpickling NumPy arrays and instances of [`datetime`](datetime#datetime.datetime "datetime.datetime"), [`date`](datetime#datetime.date "datetime.date") and [`time`](datetime#datetime.time "datetime.time") pickled by Python 2. If *buffers* is None (the default), then all data necessary for deserialization must be contained in the pickle stream. This means that the *buffer\_callback* argument was None when a [`Pickler`](#pickle.Pickler "pickle.Pickler") was instantiated (or when [`dump()`](#pickle.dump "pickle.dump") or [`dumps()`](#pickle.dumps "pickle.dumps") was called). If *buffers* is not None, it should be an iterable of buffer-enabled objects that is consumed each time the pickle stream references an [out-of-band](#pickle-oob) buffer view. Such buffers have been given in order to the *buffer\_callback* of a Pickler object. Changed in version 3.8: The *buffers* argument was added. `load()` Read the pickled representation of an object from the open file object given in the constructor, and return the reconstituted object hierarchy specified therein. Bytes past the pickled representation of the object are ignored. `persistent_load(pid)` Raise an [`UnpicklingError`](#pickle.UnpicklingError "pickle.UnpicklingError") by default. If defined, [`persistent_load()`](#pickle.Unpickler.persistent_load "pickle.Unpickler.persistent_load") should return the object specified by the persistent ID *pid*. If an invalid persistent ID is encountered, an [`UnpicklingError`](#pickle.UnpicklingError "pickle.UnpicklingError") should be raised. See [Persistence of External Objects](#pickle-persistent) for details and examples of uses. `find_class(module, name)` Import *module* if necessary and return the object called *name* from it, where the *module* and *name* arguments are [`str`](stdtypes#str "str") objects. Note, unlike its name suggests, [`find_class()`](#pickle.Unpickler.find_class "pickle.Unpickler.find_class") is also used for finding functions. Subclasses may override this to gain control over what type of objects and how they can be loaded, potentially reducing security risks. Refer to [Restricting Globals](#pickle-restrict) for details. Raises an [auditing event](sys#auditing) `pickle.find_class` with arguments `module`, `name`. `class pickle.PickleBuffer(buffer)` A wrapper for a buffer representing picklable data. *buffer* must be a [buffer-providing](../c-api/buffer#bufferobjects) object, such as a [bytes-like object](../glossary#term-bytes-like-object) or a N-dimensional array. [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") is itself a buffer provider, therefore it is possible to pass it to other APIs expecting a buffer-providing object, such as [`memoryview`](stdtypes#memoryview "memoryview"). [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") objects can only be serialized using pickle protocol 5 or higher. They are eligible for [out-of-band serialization](#pickle-oob). New in version 3.8. `raw()` Return a [`memoryview`](stdtypes#memoryview "memoryview") of the memory area underlying this buffer. The returned object is a one-dimensional, C-contiguous memoryview with format `B` (unsigned bytes). [`BufferError`](exceptions#BufferError "BufferError") is raised if the buffer is neither C- nor Fortran-contiguous. `release()` Release the underlying buffer exposed by the PickleBuffer object. What can be pickled and unpickled? ---------------------------------- The following types can be pickled: * `None`, `True`, and `False`; * integers, floating-point numbers, complex numbers; * strings, bytes, bytearrays; * tuples, lists, sets, and dictionaries containing only picklable objects; * functions (built-in and user-defined) defined at the top level of a module (using [`def`](../reference/compound_stmts#def), not [`lambda`](../reference/expressions#lambda)); * classes defined at the top level of a module; * instances of such classes whose [`__dict__`](stdtypes#object.__dict__ "object.__dict__") or the result of calling [`__getstate__()`](#object.__getstate__ "object.__getstate__") is picklable (see section [Pickling Class Instances](#pickle-inst) for details). Attempts to pickle unpicklable objects will raise the [`PicklingError`](#pickle.PicklingError "pickle.PicklingError") exception; when this happens, an unspecified number of bytes may have already been written to the underlying file. Trying to pickle a highly recursive data structure may exceed the maximum recursion depth, a [`RecursionError`](exceptions#RecursionError "RecursionError") will be raised in this case. You can carefully raise this limit with [`sys.setrecursionlimit()`](sys#sys.setrecursionlimit "sys.setrecursionlimit"). Note that functions (built-in and user-defined) are pickled by fully qualified name, not by value. [2](#id8) This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised. [3](#id9) Similarly, classes are pickled by fully qualified name, so the same restrictions in the unpickling environment apply. Note that none of the class’s code or data is pickled, so in the following example the class attribute `attr` is not restored in the unpickling environment: ``` class Foo: attr = 'A class attribute' picklestring = pickle.dumps(Foo) ``` These restrictions are why picklable functions and classes must be defined at the top level of a module. Similarly, when class instances are pickled, their class’s code and data are not pickled along with them. Only the instance data are pickled. This is done on purpose, so you can fix bugs in a class or add methods to the class and still load objects that were created with an earlier version of the class. If you plan to have long-lived objects that will see many versions of a class, it may be worthwhile to put a version number in the objects so that suitable conversions can be made by the class’s [`__setstate__()`](#object.__setstate__ "object.__setstate__") method. Pickling Class Instances ------------------------ In this section, we describe the general mechanisms available to you to define, customize, and control how class instances are pickled and unpickled. In most cases, no additional code is needed to make instances picklable. By default, pickle will retrieve the class and the attributes of an instance via introspection. When a class instance is unpickled, its [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") method is usually *not* invoked. The default behaviour first creates an uninitialized instance and then restores the saved attributes. The following code shows an implementation of this behaviour: ``` def save(obj): return (obj.__class__, obj.__dict__) def restore(cls, attributes): obj = cls.__new__(cls) obj.__dict__.update(attributes) return obj ``` Classes can alter the default behaviour by providing one or several special methods: `object.__getnewargs_ex__()` In protocols 2 and newer, classes that implements the [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__") method can dictate the values passed to the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method upon unpickling. The method must return a pair `(args, kwargs)` where *args* is a tuple of positional arguments and *kwargs* a dictionary of named arguments for constructing the object. Those will be passed to the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method upon unpickling. You should implement this method if the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method of your class requires keyword-only arguments. Otherwise, it is recommended for compatibility to implement [`__getnewargs__()`](#object.__getnewargs__ "object.__getnewargs__"). Changed in version 3.6: [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__") is now used in protocols 2 and 3. `object.__getnewargs__()` This method serves a similar purpose as [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__"), but supports only positional arguments. It must return a tuple of arguments `args` which will be passed to the [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") method upon unpickling. [`__getnewargs__()`](#object.__getnewargs__ "object.__getnewargs__") will not be called if [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__") is defined. Changed in version 3.6: Before Python 3.6, [`__getnewargs__()`](#object.__getnewargs__ "object.__getnewargs__") was called instead of [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__") in protocols 2 and 3. `object.__getstate__()` Classes can further influence how their instances are pickled; if the class defines the method [`__getstate__()`](#object.__getstate__ "object.__getstate__"), it is called and the returned object is pickled as the contents for the instance, instead of the contents of the instance’s dictionary. If the [`__getstate__()`](#object.__getstate__ "object.__getstate__") method is absent, the instance’s [`__dict__`](stdtypes#object.__dict__ "object.__dict__") is pickled as usual. `object.__setstate__(state)` Upon unpickling, if the class defines [`__setstate__()`](#object.__setstate__ "object.__setstate__"), it is called with the unpickled state. In that case, there is no requirement for the state object to be a dictionary. Otherwise, the pickled state must be a dictionary and its items are assigned to the new instance’s dictionary. Note If [`__getstate__()`](#object.__getstate__ "object.__getstate__") returns a false value, the [`__setstate__()`](#object.__setstate__ "object.__setstate__") method will not be called upon unpickling. Refer to the section [Handling Stateful Objects](#pickle-state) for more information about how to use the methods [`__getstate__()`](#object.__getstate__ "object.__getstate__") and [`__setstate__()`](#object.__setstate__ "object.__setstate__"). Note At unpickling time, some methods like [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__"), [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__"), or [`__setattr__()`](../reference/datamodel#object.__setattr__ "object.__setattr__") may be called upon the instance. In case those methods rely on some internal invariant being true, the type should implement [`__new__()`](../reference/datamodel#object.__new__ "object.__new__") to establish such an invariant, as [`__init__()`](../reference/datamodel#object.__init__ "object.__init__") is not called when unpickling an instance. As we shall see, pickle does not use directly the methods described above. In fact, these methods are part of the copy protocol which implements the [`__reduce__()`](#object.__reduce__ "object.__reduce__") special method. The copy protocol provides a unified interface for retrieving the data necessary for pickling and copying objects. [4](#id10) Although powerful, implementing [`__reduce__()`](#object.__reduce__ "object.__reduce__") directly in your classes is error prone. For this reason, class designers should use the high-level interface (i.e., [`__getnewargs_ex__()`](#object.__getnewargs_ex__ "object.__getnewargs_ex__"), [`__getstate__()`](#object.__getstate__ "object.__getstate__") and [`__setstate__()`](#object.__setstate__ "object.__setstate__")) whenever possible. We will show, however, cases where using [`__reduce__()`](#object.__reduce__ "object.__reduce__") is the only option or leads to more efficient pickling or both. `object.__reduce__()` The interface is currently defined as follows. The [`__reduce__()`](#object.__reduce__ "object.__reduce__") method takes no argument and shall return either a string or preferably a tuple (the returned object is often referred to as the “reduce value”). If a string is returned, the string should be interpreted as the name of a global variable. It should be the object’s local name relative to its module; the pickle module searches the module namespace to determine the object’s module. This behaviour is typically useful for singletons. When a tuple is returned, it must be between two and six items long. Optional items can either be omitted, or `None` can be provided as their value. The semantics of each item are in order: * A callable object that will be called to create the initial version of the object. * A tuple of arguments for the callable object. An empty tuple must be given if the callable does not accept any argument. * Optionally, the object’s state, which will be passed to the object’s [`__setstate__()`](#object.__setstate__ "object.__setstate__") method as previously described. If the object has no such method then, the value must be a dictionary and it will be added to the object’s [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute. * 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. (Whether `append()` or `extend()` is used depends on which pickle protocol version is used as well as the number of items to append, so both must be supported.) * Optionally, an iterator (not a sequence) yielding successive key-value pairs. These items will be stored to the object using `obj[key] = value`. This is primarily used for dictionary subclasses, but may be used by other classes as long as they implement [`__setitem__()`](../reference/datamodel#object.__setitem__ "object.__setitem__"). * Optionally, a callable with a `(obj, state)` signature. This callable allows the user to programmatically control the state-updating behavior of a specific object, instead of using `obj`’s static [`__setstate__()`](#object.__setstate__ "object.__setstate__") method. If not `None`, this callable will have priority over `obj`’s [`__setstate__()`](#object.__setstate__ "object.__setstate__"). New in version 3.8: The optional sixth tuple item, `(obj, state)`, was added. `object.__reduce_ex__(protocol)` Alternatively, a [`__reduce_ex__()`](#object.__reduce_ex__ "object.__reduce_ex__") method may be defined. The only difference is this method should take a single integer argument, the protocol version. When defined, pickle will prefer it over the [`__reduce__()`](#object.__reduce__ "object.__reduce__") method. In addition, [`__reduce__()`](#object.__reduce__ "object.__reduce__") automatically becomes a synonym for the extended version. The main use for this method is to provide backwards-compatible reduce values for older Python releases. ### Persistence of External Objects For the benefit of object persistence, the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module supports the notion of a reference to an object outside the pickled data stream. Such objects are referenced by a persistent ID, which should be either a string of alphanumeric characters (for protocol 0) [5](#id11) or just an arbitrary object (for any newer protocol). The resolution of such persistent IDs is not defined by the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module; it will delegate this resolution to the user-defined methods on the pickler and unpickler, [`persistent_id()`](#pickle.Pickler.persistent_id "pickle.Pickler.persistent_id") and [`persistent_load()`](#pickle.Unpickler.persistent_load "pickle.Unpickler.persistent_load") respectively. To pickle objects that have an external persistent ID, the pickler must have a custom [`persistent_id()`](#pickle.Pickler.persistent_id "pickle.Pickler.persistent_id") method that takes an object as an argument and returns either `None` or the persistent ID for that object. When `None` is returned, the pickler simply pickles the object as normal. When a persistent ID string is returned, the pickler will pickle that object, along with a marker so that the unpickler will recognize it as a persistent ID. To unpickle external objects, the unpickler must have a custom [`persistent_load()`](#pickle.Unpickler.persistent_load "pickle.Unpickler.persistent_load") method that takes a persistent ID object and returns the referenced object. Here is a comprehensive example presenting how persistent ID can be used to pickle external objects by reference. ``` # Simple example presenting how persistent ID can be used to pickle # external objects by reference. import pickle import sqlite3 from collections import namedtuple # Simple class representing a record in our database. MemoRecord = namedtuple("MemoRecord", "key, task") class DBPickler(pickle.Pickler): def persistent_id(self, obj): # Instead of pickling MemoRecord as a regular class instance, we emit a # persistent ID. if isinstance(obj, MemoRecord): # Here, our persistent ID is simply a tuple, containing a tag and a # key, which refers to a specific record in the database. return ("MemoRecord", obj.key) else: # If obj does not have a persistent ID, return None. This means obj # needs to be pickled as usual. return None class DBUnpickler(pickle.Unpickler): def __init__(self, file, connection): super().__init__(file) self.connection = connection def persistent_load(self, pid): # This method is invoked whenever a persistent ID is encountered. # Here, pid is the tuple returned by DBPickler. cursor = self.connection.cursor() type_tag, key_id = pid if type_tag == "MemoRecord": # Fetch the referenced record from the database and return it. cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),)) key, task = cursor.fetchone() return MemoRecord(key, task) else: # Always raises an error if you cannot return the correct object. # Otherwise, the unpickler will think None is the object referenced # by the persistent ID. raise pickle.UnpicklingError("unsupported persistent object") def main(): import io import pprint # Initialize and populate our database. conn = sqlite3.connect(":memory:") cursor = conn.cursor() cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)") tasks = ( 'give food to fish', 'prepare group meeting', 'fight with a zebra', ) for task in tasks: cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,)) # Fetch the records to be pickled. cursor.execute("SELECT * FROM memos") memos = [MemoRecord(key, task) for key, task in cursor] # Save the records using our custom DBPickler. file = io.BytesIO() DBPickler(file).dump(memos) print("Pickled records:") pprint.pprint(memos) # Update a record, just for good measure. cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1") # Load the records from the pickle data stream. file.seek(0) memos = DBUnpickler(file, conn).load() print("Unpickled records:") pprint.pprint(memos) if __name__ == '__main__': main() ``` ### Dispatch Tables If one wants to customize pickling of some classes without disturbing any other code which depends on pickling, then one can create a pickler with a private dispatch table. The global dispatch table managed by the [`copyreg`](copyreg#module-copyreg "copyreg: Register pickle support functions.") module is available as `copyreg.dispatch_table`. Therefore, one may choose to use a modified copy of `copyreg.dispatch_table` as a private dispatch table. For example ``` f = io.BytesIO() p = pickle.Pickler(f) p.dispatch_table = copyreg.dispatch_table.copy() p.dispatch_table[SomeClass] = reduce_SomeClass ``` creates an instance of [`pickle.Pickler`](#pickle.Pickler "pickle.Pickler") with a private dispatch table which handles the `SomeClass` class specially. Alternatively, the code ``` class MyPickler(pickle.Pickler): dispatch_table = copyreg.dispatch_table.copy() dispatch_table[SomeClass] = reduce_SomeClass f = io.BytesIO() p = MyPickler(f) ``` does the same but all instances of `MyPickler` will by default share the private dispatch table. On the other hand, the code ``` copyreg.pickle(SomeClass, reduce_SomeClass) f = io.BytesIO() p = pickle.Pickler(f) ``` modifies the global dispatch table shared by all users of the [`copyreg`](copyreg#module-copyreg "copyreg: Register pickle support functions.") module. ### Handling Stateful Objects Here’s an example that shows how to modify pickling behavior for a class. The `TextReader` class opens a text file, and returns the line number and line contents each time its `readline()` method is called. If a `TextReader` instance is pickled, all attributes *except* the file object member are saved. When the instance is unpickled, the file is reopened, and reading resumes from the last location. The [`__setstate__()`](#object.__setstate__ "object.__setstate__") and [`__getstate__()`](#object.__getstate__ "object.__getstate__") methods are used to implement this behavior. ``` class TextReader: """Print and number lines in a text file.""" def __init__(self, filename): self.filename = filename self.file = open(filename) self.lineno = 0 def readline(self): self.lineno += 1 line = self.file.readline() if not line: return None if line.endswith('\n'): line = line[:-1] return "%i: %s" % (self.lineno, line) def __getstate__(self): # Copy the object's state from self.__dict__ which contains # all our instance attributes. Always use the dict.copy() # method to avoid modifying the original state. state = self.__dict__.copy() # Remove the unpicklable entries. del state['file'] return state def __setstate__(self, state): # Restore instance attributes (i.e., filename and lineno). self.__dict__.update(state) # Restore the previously opened file's state. To do so, we need to # reopen it and read from it until the line count is restored. file = open(self.filename) for _ in range(self.lineno): file.readline() # Finally, save the file. self.file = file ``` A sample usage might be something like this: ``` >>> reader = TextReader("hello.txt") >>> reader.readline() '1: Hello world!' >>> reader.readline() '2: I am line number two.' >>> new_reader = pickle.loads(pickle.dumps(reader)) >>> new_reader.readline() '3: Goodbye!' ``` Custom Reduction for Types, Functions, and Other Objects -------------------------------------------------------- New in version 3.8. Sometimes, [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table") may not be flexible enough. In particular we may want to customize pickling based on another criterion than the object’s type, or we may want to customize the pickling of functions and classes. For those cases, it is possible to subclass from the [`Pickler`](#pickle.Pickler "pickle.Pickler") class and implement a [`reducer_override()`](#pickle.Pickler.reducer_override "pickle.Pickler.reducer_override") method. This method can return an arbitrary reduction tuple (see [`__reduce__()`](#object.__reduce__ "object.__reduce__")). It can alternatively return `NotImplemented` to fallback to the traditional behavior. If both the [`dispatch_table`](#pickle.Pickler.dispatch_table "pickle.Pickler.dispatch_table") and [`reducer_override()`](#pickle.Pickler.reducer_override "pickle.Pickler.reducer_override") are defined, then [`reducer_override()`](#pickle.Pickler.reducer_override "pickle.Pickler.reducer_override") method takes priority. Note For performance reasons, [`reducer_override()`](#pickle.Pickler.reducer_override "pickle.Pickler.reducer_override") may not be called for the following objects: `None`, `True`, `False`, and exact instances of [`int`](functions#int "int"), [`float`](functions#float "float"), [`bytes`](stdtypes#bytes "bytes"), [`str`](stdtypes#str "str"), [`dict`](stdtypes#dict "dict"), [`set`](stdtypes#set "set"), [`frozenset`](stdtypes#frozenset "frozenset"), [`list`](stdtypes#list "list") and [`tuple`](stdtypes#tuple "tuple"). Here is a simple example where we allow pickling and reconstructing a given class: ``` import io import pickle class MyClass: my_attribute = 1 class MyPickler(pickle.Pickler): def reducer_override(self, obj): """Custom reducer for MyClass.""" if getattr(obj, "__name__", None) == "MyClass": return type, (obj.__name__, obj.__bases__, {'my_attribute': obj.my_attribute}) else: # For any other object, fallback to usual reduction return NotImplemented f = io.BytesIO() p = MyPickler(f) p.dump(MyClass) del MyClass unpickled_class = pickle.loads(f.getvalue()) assert isinstance(unpickled_class, type) assert unpickled_class.__name__ == "MyClass" assert unpickled_class.my_attribute == 1 ``` Out-of-band Buffers ------------------- New in version 3.8. In some contexts, the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module is used to transfer massive amounts of data. Therefore, it can be important to minimize the number of memory copies, to preserve performance and resource consumption. However, normal operation of the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module, as it transforms a graph-like structure of objects into a sequential stream of bytes, intrinsically involves copying data to and from the pickle stream. This constraint can be eschewed if both the *provider* (the implementation of the object types to be transferred) and the *consumer* (the implementation of the communications system) support the out-of-band transfer facilities provided by pickle protocol 5 and higher. ### Provider API The large data objects to be pickled must implement a [`__reduce_ex__()`](#object.__reduce_ex__ "object.__reduce_ex__") method specialized for protocol 5 and higher, which returns a [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") instance (instead of e.g. a [`bytes`](stdtypes#bytes "bytes") object) for any large data. A [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") object *signals* that the underlying buffer is eligible for out-of-band data transfer. Those objects remain compatible with normal usage of the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module. However, consumers can also opt-in to tell [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") that they will handle those buffers by themselves. ### Consumer API A communications system can enable custom handling of the [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") objects generated when serializing an object graph. On the sending side, it needs to pass a *buffer\_callback* argument to [`Pickler`](#pickle.Pickler "pickle.Pickler") (or to the [`dump()`](#pickle.dump "pickle.dump") or [`dumps()`](#pickle.dumps "pickle.dumps") function), which will be called with each [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") generated while pickling the object graph. Buffers accumulated by the *buffer\_callback* will not see their data copied into the pickle stream, only a cheap marker will be inserted. On the receiving side, it needs to pass a *buffers* argument to [`Unpickler`](#pickle.Unpickler "pickle.Unpickler") (or to the [`load()`](#pickle.load "pickle.load") or [`loads()`](#pickle.loads "pickle.loads") function), which is an iterable of the buffers which were passed to *buffer\_callback*. That iterable should produce buffers in the same order as they were passed to *buffer\_callback*. Those buffers will provide the data expected by the reconstructors of the objects whose pickling produced the original [`PickleBuffer`](#pickle.PickleBuffer "pickle.PickleBuffer") objects. Between the sending side and the receiving side, the communications system is free to implement its own transfer mechanism for out-of-band buffers. Potential optimizations include the use of shared memory or datatype-dependent compression. ### Example Here is a trivial example where we implement a [`bytearray`](stdtypes#bytearray "bytearray") subclass able to participate in out-of-band buffer pickling: ``` class ZeroCopyByteArray(bytearray): def __reduce_ex__(self, protocol): if protocol >= 5: return type(self)._reconstruct, (PickleBuffer(self),), None else: # PickleBuffer is forbidden with pickle protocols <= 4. return type(self)._reconstruct, (bytearray(self),) @classmethod def _reconstruct(cls, obj): with memoryview(obj) as m: # Get a handle over the original buffer object obj = m.obj if type(obj) is cls: # Original buffer object is a ZeroCopyByteArray, return it # as-is. return obj else: return cls(obj) ``` The reconstructor (the `_reconstruct` class method) returns the buffer’s providing object if it has the right type. This is an easy way to simulate zero-copy behaviour on this toy example. On the consumer side, we can pickle those objects the usual way, which when unserialized will give us a copy of the original object: ``` b = ZeroCopyByteArray(b"abc") data = pickle.dumps(b, protocol=5) new_b = pickle.loads(data) print(b == new_b) # True print(b is new_b) # False: a copy was made ``` But if we pass a *buffer\_callback* and then give back the accumulated buffers when unserializing, we are able to get back the original object: ``` b = ZeroCopyByteArray(b"abc") buffers = [] data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append) new_b = pickle.loads(data, buffers=buffers) print(b == new_b) # True print(b is new_b) # True: no copy was made ``` This example is limited by the fact that [`bytearray`](stdtypes#bytearray "bytearray") allocates its own memory: you cannot create a [`bytearray`](stdtypes#bytearray "bytearray") instance that is backed by another object’s memory. However, third-party datatypes such as NumPy arrays do not have this limitation, and allow use of zero-copy pickling (or making as few copies as possible) when transferring between distinct processes or systems. See also [**PEP 574**](https://www.python.org/dev/peps/pep-0574) – Pickle protocol 5 with out-of-band data Restricting Globals ------------------- By default, unpickling will import any class or function that it finds in the pickle data. For many applications, this behaviour is unacceptable as it permits the unpickler to import and invoke arbitrary code. Just consider what this hand-crafted pickle data stream does when loaded: ``` >>> import pickle >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.") hello world 0 ``` In this example, the unpickler imports the [`os.system()`](os#os.system "os.system") function and then apply the string argument “echo hello world”. Although this example is inoffensive, it is not difficult to imagine one that could damage your system. For this reason, you may want to control what gets unpickled by customizing [`Unpickler.find_class()`](#pickle.Unpickler.find_class "pickle.Unpickler.find_class"). Unlike its name suggests, [`Unpickler.find_class()`](#pickle.Unpickler.find_class "pickle.Unpickler.find_class") is called whenever a global (i.e., a class or a function) is requested. Thus it is possible to either completely forbid globals or restrict them to a safe subset. Here is an example of an unpickler allowing only few safe classes from the [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") module to be loaded: ``` import builtins import io import pickle safe_builtins = { 'range', 'complex', 'set', 'frozenset', 'slice', } class RestrictedUnpickler(pickle.Unpickler): def find_class(self, module, name): # Only allow safe classes from builtins. if module == "builtins" and name in safe_builtins: return getattr(builtins, name) # Forbid everything else. raise pickle.UnpicklingError("global '%s.%s' is forbidden" % (module, name)) def restricted_loads(s): """Helper function analogous to pickle.loads().""" return RestrictedUnpickler(io.BytesIO(s)).load() ``` A sample usage of our unpickler working as intended: ``` >>> restricted_loads(pickle.dumps([1, 2, range(15)])) [1, 2, range(0, 15)] >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.") Traceback (most recent call last): ... pickle.UnpicklingError: global 'os.system' is forbidden >>> restricted_loads(b'cbuiltins\neval\n' ... b'(S\'getattr(__import__("os"), "system")' ... b'("echo hello world")\'\ntR.') Traceback (most recent call last): ... pickle.UnpicklingError: global 'builtins.eval' is forbidden ``` As our examples shows, you have to be careful with what you allow to be unpickled. Therefore if security is a concern, you may want to consider alternatives such as the marshalling API in [`xmlrpc.client`](xmlrpc.client#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") or third-party solutions. Performance ----------- Recent versions of the pickle protocol (from protocol 2 and upwards) feature efficient binary encodings for several common features and built-in types. Also, the [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module has a transparent optimizer written in C. Examples -------- For the simplest code, use the [`dump()`](#pickle.dump "pickle.dump") and [`load()`](#pickle.load "pickle.load") functions. ``` import pickle # An arbitrary collection of objects supported by pickle. data = { 'a': [1, 2.0, 3+4j], 'b': ("character string", b"byte string"), 'c': {None, True, False} } with open('data.pickle', 'wb') as f: # Pickle the 'data' dictionary using the highest protocol available. pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) ``` The following example reads the resulting pickled data. ``` import pickle with open('data.pickle', 'rb') as f: # The protocol version used is detected automatically, so we do not # have to specify it. data = pickle.load(f) ``` See also `Module` [`copyreg`](copyreg#module-copyreg "copyreg: Register pickle support functions.") Pickle interface constructor registration for extension types. `Module` [`pickletools`](pickletools#module-pickletools "pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.") Tools for working with and analyzing pickled data. `Module` [`shelve`](shelve#module-shelve "shelve: Python object persistence.") Indexed databases of objects; uses [`pickle`](#module-pickle "pickle: Convert Python objects to streams of bytes and back."). `Module` [`copy`](copy#module-copy "copy: Shallow and deep copy operations.") Shallow and deep object copying. `Module` [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") High-performance serialization of built-in types. #### Footnotes `1` Don’t confuse this with the [`marshal`](marshal#module-marshal "marshal: Convert Python objects to streams of bytes and back (with different constraints).") module `2` This is why [`lambda`](../reference/expressions#lambda) functions cannot be pickled: all `lambda` functions share the same name: `<lambda>`. `3` The exception raised will likely be an [`ImportError`](exceptions#ImportError "ImportError") or an [`AttributeError`](exceptions#AttributeError "AttributeError") but it could be something else. `4` The [`copy`](copy#module-copy "copy: Shallow and deep copy operations.") module uses this protocol for shallow and deep copying operations. `5` The limitation on alphanumeric characters is due to the fact that persistent IDs in protocol 0 are delimited by the newline character. Therefore if any kind of newline characters occurs in persistent IDs, the resulting pickled data will become unreadable.
programming_docs
python tkinter.scrolledtext — Scrolled Text Widget tkinter.scrolledtext — Scrolled Text Widget =========================================== **Source code:** [Lib/tkinter/scrolledtext.py](https://github.com/python/cpython/tree/3.9/Lib/tkinter/scrolledtext.py) The [`tkinter.scrolledtext`](#module-tkinter.scrolledtext "tkinter.scrolledtext: Text widget with a vertical scroll bar. (Tk)") module provides a class of the same name which implements a basic text widget which has a vertical scroll bar configured to do the “right thing.” Using the [`ScrolledText`](#tkinter.scrolledtext.ScrolledText "tkinter.scrolledtext.ScrolledText") class is a lot easier than setting up a text widget and scroll bar directly. The text widget and scrollbar are packed together in a `Frame`, and the methods of the `Grid` and `Pack` geometry managers are acquired from the `Frame` object. This allows the [`ScrolledText`](#tkinter.scrolledtext.ScrolledText "tkinter.scrolledtext.ScrolledText") widget to be used directly to achieve most normal geometry management behavior. Should more specific control be necessary, the following attributes are available: `class tkinter.scrolledtext.ScrolledText(master=None, **kw)` `frame` The frame which surrounds the text and scroll bar widgets. `vbar` The scroll bar widget. python urllib.error — Exception classes raised by urllib.request urllib.error — Exception classes raised by urllib.request ========================================================= **Source code:** [Lib/urllib/error.py](https://github.com/python/cpython/tree/3.9/Lib/urllib/error.py) The [`urllib.error`](#module-urllib.error "urllib.error: Exception classes raised by urllib.request.") module defines the exception classes for exceptions raised by [`urllib.request`](urllib.request#module-urllib.request "urllib.request: Extensible library for opening URLs."). The base exception class is [`URLError`](#urllib.error.URLError "urllib.error.URLError"). The following exceptions are raised by [`urllib.error`](#module-urllib.error "urllib.error: Exception classes raised by urllib.request.") as appropriate: `exception urllib.error.URLError` The handlers raise this exception (or derived exceptions) when they run into a problem. It is a subclass of [`OSError`](exceptions#OSError "OSError"). `reason` The reason for this error. It can be a message string or another exception instance. Changed in version 3.3: [`URLError`](#urllib.error.URLError "urllib.error.URLError") has been made a subclass of [`OSError`](exceptions#OSError "OSError") instead of [`IOError`](exceptions#IOError "IOError"). `exception urllib.error.HTTPError` Though being an exception (a subclass of [`URLError`](#urllib.error.URLError "urllib.error.URLError")), an [`HTTPError`](#urllib.error.HTTPError "urllib.error.HTTPError") can also function as a non-exceptional file-like return value (the same thing that [`urlopen()`](urllib.request#urllib.request.urlopen "urllib.request.urlopen") returns). This is useful when handling exotic HTTP errors, such as requests for authentication. `code` An HTTP status code as defined in [**RFC 2616**](https://tools.ietf.org/html/rfc2616.html). This numeric value corresponds to a value found in the dictionary of codes as found in [`http.server.BaseHTTPRequestHandler.responses`](http.server#http.server.BaseHTTPRequestHandler.responses "http.server.BaseHTTPRequestHandler.responses"). `reason` This is usually a string explaining the reason for this error. `headers` The HTTP response headers for the HTTP request that caused the [`HTTPError`](#urllib.error.HTTPError "urllib.error.HTTPError"). New in version 3.4. `exception urllib.error.ContentTooShortError(msg, content)` This exception is raised when the [`urlretrieve()`](urllib.request#urllib.request.urlretrieve "urllib.request.urlretrieve") function detects that the amount of the downloaded data is less than the expected amount (given by the *Content-Length* header). The `content` attribute stores the downloaded (and supposedly truncated) data. python re — Regular expression operations re — Regular expression operations ================================== **Source code:** [Lib/re.py](https://github.com/python/cpython/tree/3.9/Lib/re.py) This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings ([`str`](stdtypes#str "str")) as well as 8-bit strings ([`bytes`](stdtypes#bytes "bytes")). However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a byte pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string. Regular expressions use the backslash character (`'\'`) to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write `'\\\\'` as the pattern string, because the regular expression must be `\\`, and each backslash must be expressed as `\\` inside a regular Python string literal. Also, please note that any invalid escape sequences in Python’s usage of the backslash in string literals now generate a [`DeprecationWarning`](exceptions#DeprecationWarning "DeprecationWarning") and in the future this will become a [`SyntaxError`](exceptions#SyntaxError "SyntaxError"). This behaviour will happen even if it is a valid escape sequence for a regular expression. The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with `'r'`. So `r"\n"` is a two-character string containing `'\'` and `'n'`, while `"\n"` is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation. It is important to note that most regular expression operations are available as module-level functions and methods on [compiled regular expressions](#re-objects). The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters. See also The third-party [regex](https://pypi.org/project/regex/) module, which has an API compatible with the standard library [`re`](#module-re "re: Regular expression operations.") module, but offers additional functionality and a more thorough Unicode support. Regular Expression Syntax ------------------------- A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing). Regular expressions can be concatenated to form new regular expressions; if *A* and *B* are both regular expressions, then *AB* is also a regular expression. In general, if a string *p* matches *A* and another string *q* matches *B*, the string *pq* will match AB. This holds unless *A* or *B* contain low precedence operations; boundary conditions between *A* and *B*; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book [[Frie09]](#frie09), or almost any textbook about compiler construction. A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the [Regular Expression HOWTO](../howto/regex#regex-howto). Regular expressions can contain both special and ordinary characters. Most ordinary characters, like `'A'`, `'a'`, or `'0'`, are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so `last` matches the string `'last'`. (In the rest of this section, we’ll write RE’s in `this special style`, usually without quotes, and strings to be matched `'in single quotes'`.) Some characters, like `'|'` or `'('`, are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Repetition qualifiers (`*`, `+`, `?`, `{m,n}`, etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix `?`, and with other modifiers in other implementations. To apply a second repetition to an inner repetition, parentheses may be used. For example, the expression `(?:a{6})*` matches any multiple of six `'a'` characters. The special characters are: `.` (Dot.) In the default mode, this matches any character except a newline. If the [`DOTALL`](#re.DOTALL "re.DOTALL") flag has been specified, this matches any character including a newline. `^` (Caret.) Matches the start of the string, and in [`MULTILINE`](#re.MULTILINE "re.MULTILINE") mode also matches immediately after each newline. `$` Matches the end of the string or just before the newline at the end of the string, and in [`MULTILINE`](#re.MULTILINE "re.MULTILINE") mode also matches before a newline. `foo` matches both ‘foo’ and ‘foobar’, while the regular expression `foo$` matches only ‘foo’. More interestingly, searching for `foo.$` in `'foo1\nfoo2\n'` matches ‘foo2’ normally, but ‘foo1’ in [`MULTILINE`](#re.MULTILINE "re.MULTILINE") mode; searching for a single `$` in `'foo\n'` will find two (empty) matches: one just before the newline, and one at the end of the string. `*` Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. `ab*` will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s. `+` Causes the resulting RE to match 1 or more repetitions of the preceding RE. `ab+` will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’. `?` Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. `ab?` will match either ‘a’ or ‘ab’. `*?, +?, ??` The `'*'`, `'+'`, and `'?'` qualifiers are all *greedy*; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE `<.*>` is matched against `'<a> b <c>'`, it will match the entire string, and not just `'<a>'`. Adding `?` after the qualifier makes it perform the match in *non-greedy* or *minimal* fashion; as *few* characters as possible will be matched. Using the RE `<.*?>` will match only `'<a>'`. `{m}` Specifies that exactly *m* copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, `a{6}` will match exactly six `'a'` characters, but not five. `{m,n}` Causes the resulting RE to match from *m* to *n* repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, `a{3,5}` will match from 3 to 5 `'a'` characters. Omitting *m* specifies a lower bound of zero, and omitting *n* specifies an infinite upper bound. As an example, `a{4,}b` will match `'aaaab'` or a thousand `'a'` characters followed by a `'b'`, but not `'aaab'`. The comma may not be omitted or the modifier would be confused with the previously described form. `{m,n}?` Causes the resulting RE to match from *m* to *n* repetitions of the preceding RE, attempting to match as *few* repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string `'aaaaaa'`, `a{3,5}` will match 5 `'a'` characters, while `a{3,5}?` will only match 3 characters. `\` Either escapes special characters (permitting you to match characters like `'*'`, `'?'`, and so forth), or signals a special sequence; special sequences are discussed below. If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions. `[]` Used to indicate a set of characters. In a set: * Characters can be listed individually, e.g. `[amk]` will match `'a'`, `'m'`, or `'k'`. * Ranges of characters can be indicated by giving two characters and separating them by a `'-'`, for example `[a-z]` will match any lowercase ASCII letter, `[0-5][0-9]` will match all the two-digits numbers from `00` to `59`, and `[0-9A-Fa-f]` will match any hexadecimal digit. If `-` is escaped (e.g. `[a\-z]`) or if it’s placed as the first or last character (e.g. `[-a]` or `[a-]`), it will match a literal `'-'`. * Special characters lose their special meaning inside sets. For example, `[(+*)]` will match any of the literal characters `'('`, `'+'`, `'*'`, or `')'`. * Character classes such as `\w` or `\S` (defined below) are also accepted inside a set, although the characters they match depends on whether [`ASCII`](#re.ASCII "re.ASCII") or [`LOCALE`](#re.LOCALE "re.LOCALE") mode is in force. * Characters that are not within a range can be matched by *complementing* the set. If the first character of the set is `'^'`, all the characters that are *not* in the set will be matched. For example, `[^5]` will match any character except `'5'`, and `[^^]` will match any character except `'^'`. `^` has no special meaning if it’s not the first character in the set. * To match a literal `']'` inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both `[()[\]{}]` and `[]()[{}]` will both match a parenthesis. * Support of nested sets and set operations as in [Unicode Technical Standard #18](https://unicode.org/reports/tr18/) might be added in the future. This would change the syntax, so to facilitate this change a [`FutureWarning`](exceptions#FutureWarning "FutureWarning") will be raised in ambiguous cases for the time being. That includes sets starting with a literal `'['` or containing literal character sequences `'--'`, `'&&'`, `'~~'`, and `'||'`. To avoid a warning escape them with a backslash. Changed in version 3.7: [`FutureWarning`](exceptions#FutureWarning "FutureWarning") is raised if a character set contains constructs that will change semantically in the future. `|` `A|B`, where *A* and *B* can be arbitrary REs, creates a regular expression that will match either *A* or *B*. An arbitrary number of REs can be separated by the `'|'` in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by `'|'` are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once *A* matches, *B* will not be tested further, even if it would produce a longer overall match. In other words, the `'|'` operator is never greedy. To match a literal `'|'`, use `\|`, or enclose it inside a character class, as in `[|]`. `(...)` Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the `\number` special sequence, described below. To match the literals `'('` or `')'`, use `\(` or `\)`, or enclose them inside a character class: `[(]`, `[)]`. `(?...)` This is an extension notation (a `'?'` following a `'('` is not meaningful otherwise). The first character after the `'?'` determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; `(?P<name>...)` is the only exception to this rule. Following are the currently supported extensions. `(?aiLmsux)` (One or more letters from the set `'a'`, `'i'`, `'L'`, `'m'`, `'s'`, `'u'`, `'x'`.) The group matches the empty string; the letters set the corresponding flags: [`re.A`](#re.A "re.A") (ASCII-only matching), [`re.I`](#re.I "re.I") (ignore case), [`re.L`](#re.L "re.L") (locale dependent), [`re.M`](#re.M "re.M") (multi-line), [`re.S`](#re.S "re.S") (dot matches all), `re.U` (Unicode matching), and [`re.X`](#re.X "re.X") (verbose), for the entire regular expression. (The flags are described in [Module Contents](#contents-of-module-re).) This is useful if you wish to include the flags as part of the regular expression, instead of passing a *flag* argument to the [`re.compile()`](#re.compile "re.compile") function. Flags should be used first in the expression string. `(?:...)` A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group *cannot* be retrieved after performing a match or referenced later in the pattern. `(?aiLmsux-imsx:...)` (Zero or more letters from the set `'a'`, `'i'`, `'L'`, `'m'`, `'s'`, `'u'`, `'x'`, optionally followed by `'-'` followed by one or more letters from the `'i'`, `'m'`, `'s'`, `'x'`.) The letters set or remove the corresponding flags: [`re.A`](#re.A "re.A") (ASCII-only matching), [`re.I`](#re.I "re.I") (ignore case), [`re.L`](#re.L "re.L") (locale dependent), [`re.M`](#re.M "re.M") (multi-line), [`re.S`](#re.S "re.S") (dot matches all), `re.U` (Unicode matching), and [`re.X`](#re.X "re.X") (verbose), for the part of the expression. (The flags are described in [Module Contents](#contents-of-module-re).) The letters `'a'`, `'L'` and `'u'` are mutually exclusive when used as inline flags, so they can’t be combined or follow `'-'`. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns `(?a:...)` switches to ASCII-only matching, and `(?u:...)` switches to Unicode matching (default). In byte pattern `(?L:...)` switches to locale depending matching, and `(?a:...)` switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the original matching mode is restored outside of the group. New in version 3.6. Changed in version 3.7: The letters `'a'`, `'L'` and `'u'` also can be used in a group. `(?P<name>...)` Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name *name*. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. Named groups can be referenced in three contexts. If the pattern is `(?P<quote>['"]).*?(?P=quote)` (i.e. matching a string quoted with either single or double quotes): | Context of reference to group “quote” | Ways to reference it | | --- | --- | | in the same pattern itself | * `(?P=quote)` (as shown) * `\1` | | when processing match object *m* | * `m.group('quote')` * `m.end('quote')` (etc.) | | in a string passed to the *repl* argument of `re.sub()` | * `\g<quote>` * `\g<1>` * `\1` | `(?P=name)` A backreference to a named group; it matches whatever text was matched by the earlier group named *name*. `(?#...)` A comment; the contents of the parentheses are simply ignored. `(?=...)` Matches if `...` matches next, but doesn’t consume any of the string. This is called a *lookahead assertion*. For example, `Isaac (?=Asimov)` will match `'Isaac '` only if it’s followed by `'Asimov'`. `(?!...)` Matches if `...` doesn’t match next. This is a *negative lookahead assertion*. For example, `Isaac (?!Asimov)` will match `'Isaac '` only if it’s *not* followed by `'Asimov'`. `(?<=...)` Matches if the current position in the string is preceded by a match for `...` that ends at the current position. This is called a *positive lookbehind assertion*. `(?<=abc)def` will find a match in `'abcdef'`, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that `abc` or `a|b` are allowed, but `a*` and `a{3,4}` are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the [`search()`](#re.search "re.search") function rather than the [`match()`](#re.match "re.match") function: ``` >>> import re >>> m = re.search('(?<=abc)def', 'abcdef') >>> m.group(0) 'def' ``` This example looks for a word following a hyphen: ``` >>> m = re.search(r'(?<=-)\w+', 'spam-egg') >>> m.group(0) 'egg' ``` Changed in version 3.5: Added support for group references of fixed length. `(?<!...)` Matches if the current position in the string is not preceded by a match for `...`. This is called a *negative lookbehind assertion*. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched. `(?(id/name)yes-pattern|no-pattern)` Will try to match with `yes-pattern` if the group with given *id* or *name* exists, and with `no-pattern` if it doesn’t. `no-pattern` is optional and can be omitted. For example, `(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)` is a poor email matching pattern, which will match with `'<[email protected]>'` as well as `'[email protected]'`, but not with `'<[email protected]'` nor `'[email protected]>'`. The special sequences consist of `'\'` and a character from the list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resulting RE will match the second character. For example, `\$` matches the character `'$'`. `\number` Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, `(.+) \1` matches `'the the'` or `'55 55'`, but not `'thethe'` (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value *number*. Inside the `'['` and `']'` of a character class, all numeric escapes are treated as characters. `\A` Matches only at the start of the string. `\b` Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, `\b` is defined as the boundary between a `\w` and a `\W` character (or vice versa), or between `\w` and the beginning/end of the string. This means that `r'\bfoo\b'` matches `'foo'`, `'foo.'`, `'(foo)'`, `'bar foo baz'` but not `'foobar'` or `'foo3'`. By default Unicode alphanumerics are the ones used in Unicode patterns, but this can be changed by using the [`ASCII`](#re.ASCII "re.ASCII") flag. Word boundaries are determined by the current locale if the [`LOCALE`](#re.LOCALE "re.LOCALE") flag is used. Inside a character range, `\b` represents the backspace character, for compatibility with Python’s string literals. `\B` Matches the empty string, but only when it is *not* at the beginning or end of a word. This means that `r'py\B'` matches `'python'`, `'py3'`, `'py2'`, but not `'py'`, `'py.'`, or `'py!'`. `\B` is just the opposite of `\b`, so word characters in Unicode patterns are Unicode alphanumerics or the underscore, although this can be changed by using the [`ASCII`](#re.ASCII "re.ASCII") flag. Word boundaries are determined by the current locale if the [`LOCALE`](#re.LOCALE "re.LOCALE") flag is used. `\d` For Unicode (str) patterns: Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd]). This includes `[0-9]`, and also many other digit characters. If the [`ASCII`](#re.ASCII "re.ASCII") flag is used only `[0-9]` is matched. For 8-bit (bytes) patterns: Matches any decimal digit; this is equivalent to `[0-9]`. `\D` Matches any character which is not a decimal digit. This is the opposite of `\d`. If the [`ASCII`](#re.ASCII "re.ASCII") flag is used this becomes the equivalent of `[^0-9]`. `\s` For Unicode (str) patterns: Matches Unicode whitespace characters (which includes `[ \t\n\r\f\v]`, and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the [`ASCII`](#re.ASCII "re.ASCII") flag is used, only `[ \t\n\r\f\v]` is matched. For 8-bit (bytes) patterns: Matches characters considered whitespace in the ASCII character set; this is equivalent to `[ \t\n\r\f\v]`. `\S` Matches any character which is not a whitespace character. This is the opposite of `\s`. If the [`ASCII`](#re.ASCII "re.ASCII") flag is used this becomes the equivalent of `[^ \t\n\r\f\v]`. `\w` For Unicode (str) patterns: Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the [`ASCII`](#re.ASCII "re.ASCII") flag is used, only `[a-zA-Z0-9_]` is matched. For 8-bit (bytes) patterns: Matches characters considered alphanumeric in the ASCII character set; this is equivalent to `[a-zA-Z0-9_]`. If the [`LOCALE`](#re.LOCALE "re.LOCALE") flag is used, matches characters considered alphanumeric in the current locale and the underscore. `\W` Matches any character which is not a word character. This is the opposite of `\w`. If the [`ASCII`](#re.ASCII "re.ASCII") flag is used this becomes the equivalent of `[^a-zA-Z0-9_]`. If the [`LOCALE`](#re.LOCALE "re.LOCALE") flag is used, matches characters which are neither alphanumeric in the current locale nor the underscore. `\Z` Matches only at the end of the string. Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser: ``` \a \b \f \n \N \r \t \u \U \v \x \\ ``` (Note that `\b` is used to represent word boundaries, and means “backspace” only inside character classes.) `'\u'`, `'\U'`, and `'\N'` escape sequences are only recognized in Unicode patterns. In bytes patterns they are errors. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Octal escapes are included in a limited form. If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length. Changed in version 3.3: The `'\u'` and `'\U'` escape sequences have been added. Changed in version 3.6: Unknown escapes consisting of `'\'` and an ASCII letter now are errors. Changed in version 3.8: The `'\N{name}'` escape sequence has been added. As in string literals, it expands to the named Unicode character (e.g. `'\N{EM DASH}'`). Module Contents --------------- The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form. Changed in version 3.6: Flag constants are now instances of `RegexFlag`, which is a subclass of [`enum.IntFlag`](enum#enum.IntFlag "enum.IntFlag"). `re.compile(pattern, flags=0)` Compile a regular expression pattern into a [regular expression object](#re-objects), which can be used for matching using its [`match()`](#re.Pattern.match "re.Pattern.match"), [`search()`](#re.Pattern.search "re.Pattern.search") and other methods, described below. The expression’s behaviour can be modified by specifying a *flags* value. Values can be any of the following variables, combined using bitwise OR (the `|` operator). The sequence ``` prog = re.compile(pattern) result = prog.match(string) ``` is equivalent to ``` result = re.match(pattern, string) ``` but using [`re.compile()`](#re.compile "re.compile") and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program. Note The compiled versions of the most recent patterns passed to [`re.compile()`](#re.compile "re.compile") and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions. `re.A` `re.ASCII` Make `\w`, `\W`, `\b`, `\B`, `\d`, `\D`, `\s` and `\S` perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag `(?a)`. Note that for backward compatibility, the `re.U` flag still exists (as well as its synonym `re.UNICODE` and its embedded counterpart `(?u)`), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn’t allowed for bytes). `re.DEBUG` Display debug information about compiled expression. No corresponding inline flag. `re.I` `re.IGNORECASE` Perform case-insensitive matching; expressions like `[A-Z]` will also match lowercase letters. Full Unicode matching (such as `Ü` matching `ü`) also works unless the [`re.ASCII`](#re.ASCII "re.ASCII") flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the [`re.LOCALE`](#re.LOCALE "re.LOCALE") flag is also used. Corresponds to the inline flag `(?i)`. Note that when the Unicode patterns `[a-z]` or `[A-Z]` are used in combination with the [`IGNORECASE`](#re.IGNORECASE "re.IGNORECASE") flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). If the [`ASCII`](#re.ASCII "re.ASCII") flag is used, only letters ‘a’ to ‘z’ and ‘A’ to ‘Z’ are matched. `re.L` `re.LOCALE` Make `\w`, `\W`, `\b`, `\B` and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag `(?L)`. Changed in version 3.6: [`re.LOCALE`](#re.LOCALE "re.LOCALE") can be used only with bytes patterns and is not compatible with [`re.ASCII`](#re.ASCII "re.ASCII"). Changed in version 3.7: Compiled regular expression objects with the [`re.LOCALE`](#re.LOCALE "re.LOCALE") flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching. `re.M` `re.MULTILINE` When specified, the pattern character `'^'` matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character `'$'` matches at the end of the string and at the end of each line (immediately preceding each newline). By default, `'^'` matches only at the beginning of the string, and `'$'` only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag `(?m)`. `re.S` `re.DOTALL` Make the `'.'` special character match any character at all, including a newline; without this flag, `'.'` will match anything *except* a newline. Corresponds to the inline flag `(?s)`. `re.X` `re.VERBOSE` This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like `*?`, `(?:` or `(?P<...>`. When a line contains a `#` that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such `#` through the end of the line are ignored. This means that the two following regular expression objects that match a decimal number are functionally equal: ``` a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*") ``` Corresponds to the inline flag `(?x)`. `re.search(pattern, string, flags=0)` Scan through *string* looking for the first location where the regular expression *pattern* produces a match, and return a corresponding [match object](#match-objects). Return `None` if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. `re.match(pattern, string, flags=0)` If zero or more characters at the beginning of *string* match the regular expression *pattern*, return a corresponding [match object](#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match. Note that even in [`MULTILINE`](#re.MULTILINE "re.MULTILINE") mode, [`re.match()`](#re.match "re.match") will only match at the beginning of the string and not at the beginning of each line. If you want to locate a match anywhere in *string*, use [`search()`](#re.search "re.search") instead (see also [search() vs. match()](#search-vs-match)). `re.fullmatch(pattern, string, flags=0)` If the whole *string* matches the regular expression *pattern*, return a corresponding [match object](#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match. New in version 3.4. `re.split(pattern, string, maxsplit=0, flags=0)` Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list. ``` >>> re.split(r'\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split(r'(\W+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split(r'\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE) ['0', '3', '9'] ``` If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string: ``` >>> re.split(r'(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', ''] ``` That way, separator components are always found at the same relative indices within the result list. Empty matches for the pattern split the string only when not adjacent to a previous empty match. ``` >>> re.split(r'\b', 'Words, words, words.') ['', 'Words', ', ', 'words', ', ', 'words', '.'] >>> re.split(r'\W*', '...words...') ['', '', 'w', 'o', 'r', 'd', 's', '', ''] >>> re.split(r'(\W*)', '...words...') ['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', ''] ``` Changed in version 3.1: Added the optional flags argument. Changed in version 3.7: Added support of splitting on a pattern that could match an empty string. `re.findall(pattern, string, flags=0)` Return all non-overlapping matches of *pattern* in *string*, as a list of strings or tuples. The *string* is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. The result depends on the number of capturing groups in the pattern. If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result. ``` >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10') [('width', '20'), ('height', '10')] ``` Changed in version 3.7: Non-empty matches can now start just after a previous empty match. `re.finditer(pattern, string, flags=0)` Return an [iterator](../glossary#term-iterator) yielding [match objects](#match-objects) over all non-overlapping matches for the RE *pattern* in *string*. The *string* is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match. `re.sub(pattern, repl, string, count=0, flags=0)` Return the string obtained by replacing the leftmost non-overlapping occurrences of *pattern* in *string* by the replacement *repl*. If the pattern isn’t found, *string* is returned unchanged. *repl* can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, `\n` is converted to a single newline character, `\r` is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as `\&` are left alone. Backreferences, such as `\6`, are replaced with the substring matched by group 6 in the pattern. For example: ``` >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', ... r'static PyObject*\npy_\1(void)\n{', ... 'def myfunc():') 'static PyObject*\npy_myfunc(void)\n{' ``` If *repl* is a function, it is called for every non-overlapping occurrence of *pattern*. The function takes a single [match object](#match-objects) argument, and returns the replacement string. For example: ``` >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' ... else: return '-' >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') 'pro--gram files' >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) 'Baked Beans & Spam' ``` The pattern may be a string or a [pattern object](#re-objects). The optional argument *count* is the maximum number of pattern occurrences to be replaced; *count* must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous empty match, so `sub('x*', '-', 'abxd')` returns `'-a-b--d-'`. In string-type *repl* arguments, in addition to the character escapes and backreferences described above, `\g<name>` will use the substring matched by the group named `name`, as defined by the `(?P<name>...)` syntax. `\g<number>` uses the corresponding group number; `\g<2>` is therefore equivalent to `\2`, but isn’t ambiguous in a replacement such as `\g<2>0`. `\20` would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character `'0'`. The backreference `\g<0>` substitutes in the entire substring matched by the RE. Changed in version 3.1: Added the optional flags argument. Changed in version 3.5: Unmatched groups are replaced with an empty string. Changed in version 3.6: Unknown escapes in *pattern* consisting of `'\'` and an ASCII letter now are errors. Changed in version 3.7: Unknown escapes in *repl* consisting of `'\'` and an ASCII letter now are errors. Changed in version 3.7: Empty matches for the pattern are replaced when adjacent to a previous non-empty match. `re.subn(pattern, repl, string, count=0, flags=0)` Perform the same operation as [`sub()`](#re.sub "re.sub"), but return a tuple `(new_string, number_of_subs_made)`. Changed in version 3.1: Added the optional flags argument. Changed in version 3.5: Unmatched groups are replaced with an empty string. `re.escape(pattern)` Escape special characters in *pattern*. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. For example: ``` >>> print(re.escape('https://www.python.org')) https://www\.python\.org >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:" >>> print('[%s]+' % re.escape(legal_chars)) [abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+ >>> operators = ['+', '-', '*', '/', '**'] >>> print('|'.join(map(re.escape, sorted(operators, reverse=True)))) /|\-|\+|\*\*|\* ``` This function must not be used for the replacement string in [`sub()`](#re.sub "re.sub") and [`subn()`](#re.subn "re.subn"), only backslashes should be escaped. For example: ``` >>> digits_re = r'\d+' >>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings' >>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample)) /usr/sbin/sendmail - \d+ errors, \d+ warnings ``` Changed in version 3.3: The `'_'` character is no longer escaped. Changed in version 3.7: Only characters that can have special meaning in a regular expression are escaped. As a result, `'!'`, `'"'`, `'%'`, `"'"`, `','`, `'/'`, `':'`, `';'`, `'<'`, `'='`, `'>'`, `'@'`, and `"`"` are no longer escaped. `re.purge()` Clear the regular expression cache. `exception re.error(msg, pattern=None, pos=None)` Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. The error instance has the following additional attributes: `msg` The unformatted error message. `pattern` The regular expression pattern. `pos` The index in *pattern* where compilation failed (may be `None`). `lineno` The line corresponding to *pos* (may be `None`). `colno` The column corresponding to *pos* (may be `None`). Changed in version 3.5: Added additional attributes. Regular Expression Objects -------------------------- Compiled regular expression objects support the following methods and attributes: `Pattern.search(string[, pos[, endpos]])` Scan through *string* looking for the first location where this regular expression produces a match, and return a corresponding [match object](#match-objects). Return `None` if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. The optional second parameter *pos* gives an index in the string where the search is to start; it defaults to `0`. This is not completely equivalent to slicing the string; the `'^'` pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start. The optional parameter *endpos* limits how far the string will be searched; it will be as if the string is *endpos* characters long, so only the characters from *pos* to `endpos - 1` will be searched for a match. If *endpos* is less than *pos*, no match will be found; otherwise, if *rx* is a compiled regular expression object, `rx.search(string, 0, 50)` is equivalent to `rx.search(string[:50], 0)`. ``` >>> pattern = re.compile("d") >>> pattern.search("dog") # Match at index 0 <re.Match object; span=(0, 1), match='d'> >>> pattern.search("dog", 1) # No match; search doesn't include the "d" ``` `Pattern.match(string[, pos[, endpos]])` If zero or more characters at the *beginning* of *string* match this regular expression, return a corresponding [match object](#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match. The optional *pos* and *endpos* parameters have the same meaning as for the [`search()`](#re.Pattern.search "re.Pattern.search") method. ``` >>> pattern = re.compile("o") >>> pattern.match("dog") # No match as "o" is not at the start of "dog". >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog". <re.Match object; span=(1, 2), match='o'> ``` If you want to locate a match anywhere in *string*, use [`search()`](#re.Pattern.search "re.Pattern.search") instead (see also [search() vs. match()](#search-vs-match)). `Pattern.fullmatch(string[, pos[, endpos]])` If the whole *string* matches this regular expression, return a corresponding [match object](#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match. The optional *pos* and *endpos* parameters have the same meaning as for the [`search()`](#re.Pattern.search "re.Pattern.search") method. ``` >>> pattern = re.compile("o[gh]") >>> pattern.fullmatch("dog") # No match as "o" is not at the start of "dog". >>> pattern.fullmatch("ogre") # No match as not the full string matches. >>> pattern.fullmatch("doggie", 1, 3) # Matches within given limits. <re.Match object; span=(1, 3), match='og'> ``` New in version 3.4. `Pattern.split(string, maxsplit=0)` Identical to the [`split()`](#re.split "re.split") function, using the compiled pattern. `Pattern.findall(string[, pos[, endpos]])` Similar to the [`findall()`](#re.findall "re.findall") function, using the compiled pattern, but also accepts optional *pos* and *endpos* parameters that limit the search region like for [`search()`](#re.search "re.search"). `Pattern.finditer(string[, pos[, endpos]])` Similar to the [`finditer()`](#re.finditer "re.finditer") function, using the compiled pattern, but also accepts optional *pos* and *endpos* parameters that limit the search region like for [`search()`](#re.search "re.search"). `Pattern.sub(repl, string, count=0)` Identical to the [`sub()`](#re.sub "re.sub") function, using the compiled pattern. `Pattern.subn(repl, string, count=0)` Identical to the [`subn()`](#re.subn "re.subn") function, using the compiled pattern. `Pattern.flags` The regex matching flags. This is a combination of the flags given to [`compile()`](#re.compile "re.compile"), any `(?...)` inline flags in the pattern, and implicit flags such as `UNICODE` if the pattern is a Unicode string. `Pattern.groups` The number of capturing groups in the pattern. `Pattern.groupindex` A dictionary mapping any symbolic group names defined by `(?P<id>)` to group numbers. The dictionary is empty if no symbolic groups were used in the pattern. `Pattern.pattern` The pattern string from which the pattern object was compiled. Changed in version 3.7: Added support of [`copy.copy()`](copy#copy.copy "copy.copy") and [`copy.deepcopy()`](copy#copy.deepcopy "copy.deepcopy"). Compiled regular expression objects are considered atomic. Match Objects ------------- Match objects always have a boolean value of `True`. Since [`match()`](#re.Pattern.match "re.Pattern.match") and [`search()`](#re.Pattern.search "re.Pattern.search") return `None` when there is no match, you can test whether there was a match with a simple `if` statement: ``` match = re.search(pattern, string) if match: process(match) ``` Match objects support the following methods and attributes: `Match.expand(template)` Return the string obtained by doing backslash substitution on the template string *template*, as done by the [`sub()`](#re.Pattern.sub "re.Pattern.sub") method. Escapes such as `\n` are converted to the appropriate characters, and numeric backreferences (`\1`, `\2`) and named backreferences (`\g<1>`, `\g<name>`) are replaced by the contents of the corresponding group. Changed in version 3.5: Unmatched groups are replaced with an empty string. `Match.group([group1, ...])` Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, *group1* defaults to zero (the whole match is returned). If a *groupN* argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an [`IndexError`](exceptions#IndexError "IndexError") exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is `None`. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. ``` >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m.group(0) # The entire match 'Isaac Newton' >>> m.group(1) # The first parenthesized subgroup. 'Isaac' >>> m.group(2) # The second parenthesized subgroup. 'Newton' >>> m.group(1, 2) # Multiple arguments give us a tuple. ('Isaac', 'Newton') ``` If the regular expression uses the `(?P<name>...)` syntax, the *groupN* arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an [`IndexError`](exceptions#IndexError "IndexError") exception is raised. A moderately complicated example: ``` >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.group('first_name') 'Malcolm' >>> m.group('last_name') 'Reynolds' ``` Named groups can also be referred to by their index: ``` >>> m.group(1) 'Malcolm' >>> m.group(2) 'Reynolds' ``` If a group matches multiple times, only the last match is accessible: ``` >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. >>> m.group(1) # Returns only the last match. 'c3' ``` `Match.__getitem__(g)` This is identical to `m.group(g)`. This allows easier access to an individual group from a match: ``` >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m[0] # The entire match 'Isaac Newton' >>> m[1] # The first parenthesized subgroup. 'Isaac' >>> m[2] # The second parenthesized subgroup. 'Newton' ``` New in version 3.6. `Match.groups(default=None)` Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The *default* argument is used for groups that did not participate in the match; it defaults to `None`. For example: ``` >>> m = re.match(r"(\d+)\.(\d+)", "24.1632") >>> m.groups() ('24', '1632') ``` If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to `None` unless the *default* argument is given: ``` >>> m = re.match(r"(\d+)\.?(\d+)?", "24") >>> m.groups() # Second group defaults to None. ('24', None) >>> m.groups('0') # Now, the second group defaults to '0'. ('24', '0') ``` `Match.groupdict(default=None)` Return a dictionary containing all the *named* subgroups of the match, keyed by the subgroup name. The *default* argument is used for groups that did not participate in the match; it defaults to `None`. For example: ``` >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.groupdict() {'first_name': 'Malcolm', 'last_name': 'Reynolds'} ``` `Match.start([group])` `Match.end([group])` Return the indices of the start and end of the substring matched by *group*; *group* defaults to zero (meaning the whole matched substring). Return `-1` if *group* exists but did not contribute to the match. For a match object *m*, and a group *g* that did contribute to the match, the substring matched by group *g* (equivalent to `m.group(g)`) is ``` m.string[m.start(g):m.end(g)] ``` Note that `m.start(group)` will equal `m.end(group)` if *group* matched a null string. For example, after `m = re.search('b(c?)', 'cba')`, `m.start(0)` is 1, `m.end(0)` is 2, `m.start(1)` and `m.end(1)` are both 2, and `m.start(2)` raises an [`IndexError`](exceptions#IndexError "IndexError") exception. An example that will remove *remove\_this* from email addresses: ``` >>> email = "tony@tiremove_thisger.net" >>> m = re.search("remove_this", email) >>> email[:m.start()] + email[m.end():] '[email protected]' ``` `Match.span([group])` For a match *m*, return the 2-tuple `(m.start(group), m.end(group))`. Note that if *group* did not contribute to the match, this is `(-1, -1)`. *group* defaults to zero, the entire match. `Match.pos` The value of *pos* which was passed to the [`search()`](#re.Pattern.search "re.Pattern.search") or [`match()`](#re.Pattern.match "re.Pattern.match") method of a [regex object](#re-objects). This is the index into the string at which the RE engine started looking for a match. `Match.endpos` The value of *endpos* which was passed to the [`search()`](#re.Pattern.search "re.Pattern.search") or [`match()`](#re.Pattern.match "re.Pattern.match") method of a [regex object](#re-objects). This is the index into the string beyond which the RE engine will not go. `Match.lastindex` The integer index of the last matched capturing group, or `None` if no group was matched at all. For example, the expressions `(a)b`, `((a)(b))`, and `((ab))` will have `lastindex == 1` if applied to the string `'ab'`, while the expression `(a)(b)` will have `lastindex == 2`, if applied to the same string. `Match.lastgroup` The name of the last matched capturing group, or `None` if the group didn’t have a name, or if no group was matched at all. `Match.re` The [regular expression object](#re-objects) whose [`match()`](#re.Pattern.match "re.Pattern.match") or [`search()`](#re.Pattern.search "re.Pattern.search") method produced this match instance. `Match.string` The string passed to [`match()`](#re.Pattern.match "re.Pattern.match") or [`search()`](#re.Pattern.search "re.Pattern.search"). Changed in version 3.7: Added support of [`copy.copy()`](copy#copy.copy "copy.copy") and [`copy.deepcopy()`](copy#copy.deepcopy "copy.deepcopy"). Match objects are considered atomic. Regular Expression Examples --------------------------- ### Checking for a Pair In this example, we’ll use the following helper function to display match objects a little more gracefully: ``` def displaymatch(match): if match is None: return None return '<Match: %r, groups=%r>' % (match.group(), match.groups()) ``` Suppose you are writing a poker program where a player’s hand is represented as a 5-character string with each character representing a card, “a” for ace, “k” for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9” representing the card with that value. To see if a given string is a valid hand, one could do the following: ``` >>> valid = re.compile(r"^[a2-9tjqk]{5}$") >>> displaymatch(valid.match("akt5q")) # Valid. "<Match: 'akt5q', groups=()>" >>> displaymatch(valid.match("akt5e")) # Invalid. >>> displaymatch(valid.match("akt")) # Invalid. >>> displaymatch(valid.match("727ak")) # Valid. "<Match: '727ak', groups=()>" ``` That last hand, `"727ak"`, contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such: ``` >>> pair = re.compile(r".*(.).*\1") >>> displaymatch(pair.match("717ak")) # Pair of 7s. "<Match: '717', groups=('7',)>" >>> displaymatch(pair.match("718ak")) # No pairs. >>> displaymatch(pair.match("354aa")) # Pair of aces. "<Match: '354aa', groups=('a',)>" ``` To find out what card the pair consists of, one could use the [`group()`](#re.Match.group "re.Match.group") method of the match object in the following manner: ``` >>> pair = re.compile(r".*(.).*\1") >>> pair.match("717ak").group(1) '7' # Error because re.match() returns None, which doesn't have a group() method: >>> pair.match("718ak").group(1) Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> re.match(r".*(.).*\1", "718ak").group(1) AttributeError: 'NoneType' object has no attribute 'group' >>> pair.match("354aa").group(1) 'a' ``` ### Simulating scanf() Python does not currently have an equivalent to `scanf()`. Regular expressions are generally more powerful, though also more verbose, than `scanf()` format strings. The table below offers some more-or-less equivalent mappings between `scanf()` format tokens and regular expressions. | `scanf()` Token | Regular Expression | | --- | --- | | `%c` | `.` | | `%5c` | `.{5}` | | `%d` | `[-+]?\d+` | | `%e`, `%E`, `%f`, `%g` | `[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?` | | `%i` | `[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)` | | `%o` | `[-+]?[0-7]+` | | `%s` | `\S+` | | `%u` | `\d+` | | `%x`, `%X` | `[-+]?(0[xX])?[\dA-Fa-f]+` | To extract the filename and numbers from a string like ``` /usr/sbin/sendmail - 0 errors, 4 warnings ``` you would use a `scanf()` format like ``` %s - %d errors, %d warnings ``` The equivalent regular expression would be ``` (\S+) - (\d+) errors, (\d+) warnings ``` ### search() vs. match() Python offers two different primitive operations based on regular expressions: [`re.match()`](#re.match "re.match") checks for a match only at the beginning of the string, while [`re.search()`](#re.search "re.search") checks for a match anywhere in the string (this is what Perl does by default). For example: ``` >>> re.match("c", "abcdef") # No match >>> re.search("c", "abcdef") # Match <re.Match object; span=(2, 3), match='c'> ``` Regular expressions beginning with `'^'` can be used with [`search()`](#re.search "re.search") to restrict the match at the beginning of the string: ``` >>> re.match("c", "abcdef") # No match >>> re.search("^c", "abcdef") # No match >>> re.search("^a", "abcdef") # Match <re.Match object; span=(0, 1), match='a'> ``` Note however that in [`MULTILINE`](#re.MULTILINE "re.MULTILINE") mode [`match()`](#re.match "re.match") only matches at the beginning of the string, whereas using [`search()`](#re.search "re.search") with a regular expression beginning with `'^'` will match at the beginning of each line. ``` >>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match >>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match <re.Match object; span=(4, 5), match='X'> ``` ### Making a Phonebook [`split()`](#re.split "re.split") splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook. First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax ``` >>> text = """Ross McFluff: 834.345.1254 155 Elm Street ... ... Ronald Heathmore: 892.345.3428 436 Finley Avenue ... Frank Burger: 925.541.7625 662 South Dogwood Way ... ... ... Heather Albrecht: 548.326.4584 919 Park Place""" ``` The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry: ``` >>> entries = re.split("\n+", text) >>> entries ['Ross McFluff: 834.345.1254 155 Elm Street', 'Ronald Heathmore: 892.345.3428 436 Finley Avenue', 'Frank Burger: 925.541.7625 662 South Dogwood Way', 'Heather Albrecht: 548.326.4584 919 Park Place'] ``` Finally, split each entry into a list with first name, last name, telephone number, and address. We use the `maxsplit` parameter of [`split()`](#re.split "re.split") because the address has spaces, our splitting pattern, in it: ``` >>> [re.split(":? ", entry, 3) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'], ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'], ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'], ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']] ``` The `:?` pattern matches the colon after the last name, so that it does not occur in the result list. With a `maxsplit` of `4`, we could separate the house number from the street name: ``` >>> [re.split(":? ", entry, 4) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'], ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'], ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'], ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']] ``` ### Text Munging [`sub()`](#re.sub "re.sub") replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using [`sub()`](#re.sub "re.sub") with a function to “munge” text, or randomize the order of all the characters in each word of a sentence except for the first and last characters: ``` >>> def repl(m): ... inner_word = list(m.group(2)) ... random.shuffle(inner_word) ... return m.group(1) + "".join(inner_word) + m.group(3) >>> text = "Professor Abdolmalek, please report your absences promptly." >>> re.sub(r"(\w)(\w+)(\w)", repl, text) 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.' >>> re.sub(r"(\w)(\w+)(\w)", repl, text) 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.' ``` ### Finding all Adverbs [`findall()`](#re.findall "re.findall") matches *all* occurrences of a pattern, not just the first one as [`search()`](#re.search "re.search") does. For example, if a writer wanted to find all of the adverbs in some text, they might use [`findall()`](#re.findall "re.findall") in the following manner: ``` >>> text = "He was carefully disguised but captured quickly by police." >>> re.findall(r"\w+ly\b", text) ['carefully', 'quickly'] ``` ### Finding all Adverbs and their Positions If one wants more information about all matches of a pattern than the matched text, [`finditer()`](#re.finditer "re.finditer") is useful as it provides [match objects](#match-objects) instead of strings. Continuing with the previous example, if a writer wanted to find all of the adverbs *and their positions* in some text, they would use [`finditer()`](#re.finditer "re.finditer") in the following manner: ``` >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly\b", text): ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly ``` ### Raw String Notation Raw string notation (`r"text"`) keeps regular expressions sane. Without it, every backslash (`'\'`) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical: ``` >>> re.match(r"\W(.)\1\W", " ff ") <re.Match object; span=(0, 4), match=' ff '> >>> re.match("\\W(.)\\1\\W", " ff ") <re.Match object; span=(0, 4), match=' ff '> ``` When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means `r"\\"`. Without raw string notation, one must use `"\\\\"`, making the following lines of code functionally identical: ``` >>> re.match(r"\\", r"\\") <re.Match object; span=(0, 1), match='\\'> >>> re.match("\\\\", r"\\") <re.Match object; span=(0, 1), match='\\'> ``` ### Writing a Tokenizer A [tokenizer or scanner](https://en.wikipedia.org/wiki/Lexical_analysis) analyzes a string to categorize groups of characters. This is a useful first step in writing a compiler or interpreter. The text categories are specified with regular expressions. The technique is to combine those into a single master regular expression and to loop over successive matches: ``` from typing import NamedTuple import re class Token(NamedTuple): type: str value: str line: int column: int def tokenize(code): keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'} token_specification = [ ('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number ('ASSIGN', r':='), # Assignment operator ('END', r';'), # Statement terminator ('ID', r'[A-Za-z]+'), # Identifiers ('OP', r'[+\-*/]'), # Arithmetic operators ('NEWLINE', r'\n'), # Line endings ('SKIP', r'[ \t]+'), # Skip over spaces and tabs ('MISMATCH', r'.'), # Any other character ] tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification) line_num = 1 line_start = 0 for mo in re.finditer(tok_regex, code): kind = mo.lastgroup value = mo.group() column = mo.start() - line_start if kind == 'NUMBER': value = float(value) if '.' in value else int(value) elif kind == 'ID' and value in keywords: kind = value elif kind == 'NEWLINE': line_start = mo.end() line_num += 1 continue elif kind == 'SKIP': continue elif kind == 'MISMATCH': raise RuntimeError(f'{value!r} unexpected on line {line_num}') yield Token(kind, value, line_num, column) statements = ''' IF quantity THEN total := total + price * quantity; tax := price * 0.05; ENDIF; ''' for token in tokenize(statements): print(token) ``` The tokenizer produces the following output: ``` Token(type='IF', value='IF', line=2, column=4) Token(type='ID', value='quantity', line=2, column=7) Token(type='THEN', value='THEN', line=2, column=16) Token(type='ID', value='total', line=3, column=8) Token(type='ASSIGN', value=':=', line=3, column=14) Token(type='ID', value='total', line=3, column=17) Token(type='OP', value='+', line=3, column=23) Token(type='ID', value='price', line=3, column=25) Token(type='OP', value='*', line=3, column=31) Token(type='ID', value='quantity', line=3, column=33) Token(type='END', value=';', line=3, column=41) Token(type='ID', value='tax', line=4, column=8) Token(type='ASSIGN', value=':=', line=4, column=12) Token(type='ID', value='price', line=4, column=15) Token(type='OP', value='*', line=4, column=21) Token(type='NUMBER', value=0.05, line=4, column=23) Token(type='END', value=';', line=4, column=27) Token(type='ENDIF', value='ENDIF', line=5, column=4) Token(type='END', value=';', line=5, column=9) ``` `Frie09` Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O’Reilly Media, 2009. The third edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.
programming_docs
python Numeric and Mathematical Modules Numeric and Mathematical Modules ================================ The modules described in this chapter provide numeric and math-related functions and data types. The [`numbers`](numbers#module-numbers "numbers: Numeric abstract base classes (Complex, Real, Integral, etc.).") module defines an abstract hierarchy of numeric types. The [`math`](math#module-math "math: Mathematical functions (sin() etc.).") and [`cmath`](cmath#module-cmath "cmath: Mathematical functions for complex numbers.") modules contain various mathematical functions for floating-point and complex numbers. The [`decimal`](decimal#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") module supports exact representations of decimal numbers, using arbitrary precision arithmetic. The following modules are documented in this chapter: * [`numbers` — Numeric abstract base classes](numbers) + [The numeric tower](numbers#the-numeric-tower) + [Notes for type implementors](numbers#notes-for-type-implementors) - [Adding More Numeric ABCs](numbers#adding-more-numeric-abcs) - [Implementing the arithmetic operations](numbers#implementing-the-arithmetic-operations) * [`math` — Mathematical functions](math) + [Number-theoretic and representation functions](math#number-theoretic-and-representation-functions) + [Power and logarithmic functions](math#power-and-logarithmic-functions) + [Trigonometric functions](math#trigonometric-functions) + [Angular conversion](math#angular-conversion) + [Hyperbolic functions](math#hyperbolic-functions) + [Special functions](math#special-functions) + [Constants](math#constants) * [`cmath` — Mathematical functions for complex numbers](cmath) + [Conversions to and from polar coordinates](cmath#conversions-to-and-from-polar-coordinates) + [Power and logarithmic functions](cmath#power-and-logarithmic-functions) + [Trigonometric functions](cmath#trigonometric-functions) + [Hyperbolic functions](cmath#hyperbolic-functions) + [Classification functions](cmath#classification-functions) + [Constants](cmath#constants) * [`decimal` — Decimal fixed point and floating point arithmetic](decimal) + [Quick-start Tutorial](decimal#quick-start-tutorial) + [Decimal objects](decimal#decimal-objects) - [Logical operands](decimal#logical-operands) + [Context objects](decimal#context-objects) + [Constants](decimal#constants) + [Rounding modes](decimal#rounding-modes) + [Signals](decimal#signals) + [Floating Point Notes](decimal#floating-point-notes) - [Mitigating round-off error with increased precision](decimal#mitigating-round-off-error-with-increased-precision) - [Special values](decimal#special-values) + [Working with threads](decimal#working-with-threads) + [Recipes](decimal#recipes) + [Decimal FAQ](decimal#decimal-faq) * [`fractions` — Rational numbers](fractions) * [`random` — Generate pseudo-random numbers](random) + [Bookkeeping functions](random#bookkeeping-functions) + [Functions for bytes](random#functions-for-bytes) + [Functions for integers](random#functions-for-integers) + [Functions for sequences](random#functions-for-sequences) + [Real-valued distributions](random#real-valued-distributions) + [Alternative Generator](random#alternative-generator) + [Notes on Reproducibility](random#notes-on-reproducibility) + [Examples](random#examples) + [Recipes](random#recipes) * [`statistics` — Mathematical statistics functions](statistics) + [Averages and measures of central location](statistics#averages-and-measures-of-central-location) + [Measures of spread](statistics#measures-of-spread) + [Function details](statistics#function-details) + [Exceptions](statistics#exceptions) + [`NormalDist` objects](statistics#normaldist-objects) - [`NormalDist` Examples and Recipes](statistics#normaldist-examples-and-recipes) python filecmp — File and Directory Comparisons filecmp — File and Directory Comparisons ======================================== **Source code:** [Lib/filecmp.py](https://github.com/python/cpython/tree/3.9/Lib/filecmp.py) The [`filecmp`](#module-filecmp "filecmp: Compare files efficiently.") module defines functions to compare files and directories, with various optional time/correctness trade-offs. For comparing files, see also the [`difflib`](difflib#module-difflib "difflib: Helpers for computing differences between objects.") module. The [`filecmp`](#module-filecmp "filecmp: Compare files efficiently.") module defines the following functions: `filecmp.cmp(f1, f2, shallow=True)` Compare the files named *f1* and *f2*, returning `True` if they seem equal, `False` otherwise. If *shallow* is true and the [`os.stat()`](os#os.stat "os.stat") signatures (file type, size, and modification time) of both files are identical, the files are taken to be equal. Otherwise, the files are treated as different if their sizes or contents differ. Note that no external programs are called from this function, giving it portability and efficiency. This function uses a cache for past comparisons and the results, with cache entries invalidated if the [`os.stat()`](os#os.stat "os.stat") information for the file changes. The entire cache may be cleared using [`clear_cache()`](#filecmp.clear_cache "filecmp.clear_cache"). `filecmp.cmpfiles(dir1, dir2, common, shallow=True)` Compare the files in the two directories *dir1* and *dir2* whose names are given by *common*. Returns three lists of file names: *match*, *mismatch*, *errors*. *match* contains the list of files that match, *mismatch* contains the names of those that don’t, and *errors* lists the names of files which could not be compared. Files are listed in *errors* if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason. The *shallow* parameter has the same meaning and default value as for [`filecmp.cmp()`](#filecmp.cmp "filecmp.cmp"). For example, `cmpfiles('a', 'b', ['c', 'd/e'])` will compare `a/c` with `b/c` and `a/d/e` with `b/d/e`. `'c'` and `'d/e'` will each be in one of the three returned lists. `filecmp.clear_cache()` Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem. New in version 3.4. The dircmp class ---------------- `class filecmp.dircmp(a, b, ignore=None, hide=None)` Construct a new directory comparison object, to compare the directories *a* and *b*. *ignore* is a list of names to ignore, and defaults to [`filecmp.DEFAULT_IGNORES`](#filecmp.DEFAULT_IGNORES "filecmp.DEFAULT_IGNORES"). *hide* is a list of names to hide, and defaults to `[os.curdir, os.pardir]`. The [`dircmp`](#filecmp.dircmp "filecmp.dircmp") class compares files by doing *shallow* comparisons as described for [`filecmp.cmp()`](#filecmp.cmp "filecmp.cmp"). The [`dircmp`](#filecmp.dircmp "filecmp.dircmp") class provides the following methods: `report()` Print (to [`sys.stdout`](sys#sys.stdout "sys.stdout")) a comparison between *a* and *b*. `report_partial_closure()` Print a comparison between *a* and *b* and common immediate subdirectories. `report_full_closure()` Print a comparison between *a* and *b* and common subdirectories (recursively). The [`dircmp`](#filecmp.dircmp "filecmp.dircmp") class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared. Note that via [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used. `left` The directory *a*. `right` The directory *b*. `left_list` Files and subdirectories in *a*, filtered by *hide* and *ignore*. `right_list` Files and subdirectories in *b*, filtered by *hide* and *ignore*. `common` Files and subdirectories in both *a* and *b*. `left_only` Files and subdirectories only in *a*. `right_only` Files and subdirectories only in *b*. `common_dirs` Subdirectories in both *a* and *b*. `common_files` Files in both *a* and *b*. `common_funny` Names in both *a* and *b*, such that the type differs between the directories, or names for which [`os.stat()`](os#os.stat "os.stat") reports an error. `same_files` Files which are identical in both *a* and *b*, using the class’s file comparison operator. `diff_files` Files which are in both *a* and *b*, whose contents differ according to the class’s file comparison operator. `funny_files` Files which are in both *a* and *b*, but could not be compared. `subdirs` A dictionary mapping names in [`common_dirs`](#filecmp.dircmp.common_dirs "filecmp.dircmp.common_dirs") to [`dircmp`](#filecmp.dircmp "filecmp.dircmp") objects. `filecmp.DEFAULT_IGNORES` New in version 3.4. List of directories ignored by [`dircmp`](#filecmp.dircmp "filecmp.dircmp") by default. Here is a simplified example of using the `subdirs` attribute to search recursively through two directories to show common different files: ``` >>> from filecmp import dircmp >>> def print_diff_files(dcmp): ... for name in dcmp.diff_files: ... print("diff_file %s found in %s and %s" % (name, dcmp.left, ... dcmp.right)) ... for sub_dcmp in dcmp.subdirs.values(): ... print_diff_files(sub_dcmp) ... >>> dcmp = dircmp('dir1', 'dir2') >>> print_diff_files(dcmp) ``` python Python Runtime Services Python Runtime Services ======================= The modules described in this chapter provide a wide range of services related to the Python interpreter and its interaction with its environment. Here’s an overview: * [`sys` — System-specific parameters and functions](sys) * [`sysconfig` — Provide access to Python’s configuration information](sysconfig) + [Configuration variables](sysconfig#configuration-variables) + [Installation paths](sysconfig#installation-paths) + [Other functions](sysconfig#other-functions) + [Using `sysconfig` as a script](sysconfig#using-sysconfig-as-a-script) * [`builtins` — Built-in objects](builtins) * [`__main__` — Top-level script environment](__main__) * [`warnings` — Warning control](warnings) + [Warning Categories](warnings#warning-categories) + [The Warnings Filter](warnings#the-warnings-filter) - [Describing Warning Filters](warnings#describing-warning-filters) - [Default Warning Filter](warnings#default-warning-filter) - [Overriding the default filter](warnings#overriding-the-default-filter) + [Temporarily Suppressing Warnings](warnings#temporarily-suppressing-warnings) + [Testing Warnings](warnings#testing-warnings) + [Updating Code For New Versions of Dependencies](warnings#updating-code-for-new-versions-of-dependencies) + [Available Functions](warnings#available-functions) + [Available Context Managers](warnings#available-context-managers) * [`dataclasses` — Data Classes](dataclasses) + [Module-level decorators, classes, and functions](dataclasses#module-level-decorators-classes-and-functions) + [Post-init processing](dataclasses#post-init-processing) + [Class variables](dataclasses#class-variables) + [Init-only variables](dataclasses#init-only-variables) + [Frozen instances](dataclasses#frozen-instances) + [Inheritance](dataclasses#inheritance) + [Default factory functions](dataclasses#default-factory-functions) + [Mutable default values](dataclasses#mutable-default-values) + [Exceptions](dataclasses#exceptions) * [`contextlib` — Utilities for `with`-statement contexts](contextlib) + [Utilities](contextlib#utilities) + [Examples and Recipes](contextlib#examples-and-recipes) - [Supporting a variable number of context managers](contextlib#supporting-a-variable-number-of-context-managers) - [Catching exceptions from `__enter__` methods](contextlib#catching-exceptions-from-enter-methods) - [Cleaning up in an `__enter__` implementation](contextlib#cleaning-up-in-an-enter-implementation) - [Replacing any use of `try-finally` and flag variables](contextlib#replacing-any-use-of-try-finally-and-flag-variables) - [Using a context manager as a function decorator](contextlib#using-a-context-manager-as-a-function-decorator) + [Single use, reusable and reentrant context managers](contextlib#single-use-reusable-and-reentrant-context-managers) - [Reentrant context managers](contextlib#reentrant-context-managers) - [Reusable context managers](contextlib#reusable-context-managers) * [`abc` — Abstract Base Classes](abc) * [`atexit` — Exit handlers](atexit) + [`atexit` Example](atexit#atexit-example) * [`traceback` — Print or retrieve a stack traceback](traceback) + [`TracebackException` Objects](traceback#tracebackexception-objects) + [`StackSummary` Objects](traceback#stacksummary-objects) + [`FrameSummary` Objects](traceback#framesummary-objects) + [Traceback Examples](traceback#traceback-examples) * [`__future__` — Future statement definitions](__future__) * [`gc` — Garbage Collector interface](gc) * [`inspect` — Inspect live objects](inspect) + [Types and members](inspect#types-and-members) + [Retrieving source code](inspect#retrieving-source-code) + [Introspecting callables with the Signature object](inspect#introspecting-callables-with-the-signature-object) + [Classes and functions](inspect#classes-and-functions) + [The interpreter stack](inspect#the-interpreter-stack) + [Fetching attributes statically](inspect#fetching-attributes-statically) + [Current State of Generators and Coroutines](inspect#current-state-of-generators-and-coroutines) + [Code Objects Bit Flags](inspect#code-objects-bit-flags) + [Command Line Interface](inspect#command-line-interface) * [`site` — Site-specific configuration hook](site) + [Readline configuration](site#readline-configuration) + [Module contents](site#module-contents) + [Command Line Interface](site#command-line-interface) python binhex — Encode and decode binhex4 files binhex — Encode and decode binhex4 files ======================================== **Source code:** [Lib/binhex.py](https://github.com/python/cpython/tree/3.9/Lib/binhex.py) Deprecated since version 3.9. This module encodes and decodes files in binhex4 format, a format allowing representation of Macintosh files in ASCII. Only the data fork is handled. The [`binhex`](#module-binhex "binhex: Encode and decode files in binhex4 format.") module defines the following functions: `binhex.binhex(input, output)` Convert a binary file with filename *input* to binhex file *output*. The *output* parameter can either be a filename or a file-like object (any object supporting a `write()` and `close()` method). `binhex.hexbin(input, output)` Decode a binhex file *input*. *input* may be a filename or a file-like object supporting `read()` and `close()` methods. The resulting file is written to a file named *output*, unless the argument is `None` in which case the output filename is read from the binhex file. The following exception is also defined: `exception binhex.Error` Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data. See also `Module` [`binascii`](binascii#module-binascii "binascii: Tools for converting between binary and various ASCII-encoded binary representations.") Support module containing ASCII-to-binary and binary-to-ASCII conversions. Notes ----- There is an alternative, more powerful interface to the coder and decoder, see the source for details. If you code or decode textfiles on non-Macintosh platforms they will still use the old Macintosh newline convention (carriage-return as end of line). python getpass — Portable password input getpass — Portable password input ================================= **Source code:** [Lib/getpass.py](https://github.com/python/cpython/tree/3.9/Lib/getpass.py) The [`getpass`](#module-getpass "getpass: Portable reading of passwords and retrieval of the userid.") module provides two functions: `getpass.getpass(prompt='Password: ', stream=None)` Prompt the user for a password without echoing. The user is prompted using the string *prompt*, which defaults to `'Password: '`. On Unix, the prompt is written to the file-like object *stream* using the replace error handler if needed. *stream* defaults to the controlling terminal (`/dev/tty`) or if that is unavailable to `sys.stderr` (this argument is ignored on Windows). If echo free input is unavailable getpass() falls back to printing a warning message to *stream* and reading from `sys.stdin` and issuing a [`GetPassWarning`](#getpass.GetPassWarning "getpass.GetPassWarning"). Note If you call getpass from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself. `exception getpass.GetPassWarning` A [`UserWarning`](exceptions#UserWarning "UserWarning") subclass issued when password input may be echoed. `getpass.getuser()` Return the “login name” of the user. This function checks the environment variables `LOGNAME`, `USER`, `LNAME` and `USERNAME`, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the [`pwd`](pwd#module-pwd "pwd: The password database (getpwnam() and friends). (Unix)") module, otherwise, an exception is raised. In general, this function should be preferred over [`os.getlogin()`](os#os.getlogin "os.getlogin"). python pydoc — Documentation generator and online help system pydoc — Documentation generator and online help system ====================================================== **Source code:** [Lib/pydoc.py](https://github.com/python/cpython/tree/3.9/Lib/pydoc.py) The [`pydoc`](#module-pydoc "pydoc: Documentation generator and online help system.") module automatically generates documentation from Python modules. The documentation can be presented as pages of text on the console, served to a Web browser, or saved to HTML files. For modules, classes, functions and methods, the displayed documentation is derived from the docstring (i.e. the `__doc__` attribute) of the object, and recursively of its documentable members. If there is no docstring, [`pydoc`](#module-pydoc "pydoc: Documentation generator and online help system.") tries to obtain a description from the block of comment lines just above the definition of the class, function or method in the source file, or at the top of the module (see [`inspect.getcomments()`](inspect#inspect.getcomments "inspect.getcomments")). The built-in function [`help()`](functions#help "help") invokes the online help system in the interactive interpreter, which uses [`pydoc`](#module-pydoc "pydoc: Documentation generator and online help system.") to generate its documentation as text on the console. The same text documentation can also be viewed from outside the Python interpreter by running **pydoc** as a script at the operating system’s command prompt. For example, running ``` pydoc sys ``` at a shell prompt will display documentation on the [`sys`](sys#module-sys "sys: Access system-specific parameters and functions.") module, in a style similar to the manual pages shown by the Unix **man** command. The argument to **pydoc** can be the name of a function, module, or package, or a dotted reference to a class, method, or function within a module or module in a package. If the argument to **pydoc** looks like a path (that is, it contains the path separator for your operating system, such as a slash in Unix), and refers to an existing Python source file, then documentation is produced for that file. Note In order to find objects and their documentation, [`pydoc`](#module-pydoc "pydoc: Documentation generator and online help system.") imports the module(s) to be documented. Therefore, any code on module level will be executed on that occasion. Use an `if __name__ == '__main__':` guard to only execute code when a file is invoked as a script and not just imported. When printing output to the console, **pydoc** attempts to paginate the output for easier reading. If the `PAGER` environment variable is set, **pydoc** will use its value as a pagination program. Specifying a `-w` flag before the argument will cause HTML documentation to be written out to a file in the current directory, instead of displaying text on the console. Specifying a `-k` flag before the argument will search the synopsis lines of all available modules for the keyword given as the argument, again in a manner similar to the Unix **man** command. The synopsis line of a module is the first line of its documentation string. You can also use **pydoc** to start an HTTP server on the local machine that will serve documentation to visiting Web browsers. **pydoc -p 1234** will start a HTTP server on port 1234, allowing you to browse the documentation at `http://localhost:1234/` in your preferred Web browser. Specifying `0` as the port number will select an arbitrary unused port. **pydoc -n <hostname>** will start the server listening at the given hostname. By default the hostname is ‘localhost’ but if you want the server to be reached from other machines, you may want to change the host name that the server responds to. During development this is especially useful if you want to run pydoc from within a container. **pydoc -b** will start the server and additionally open a web browser to a module index page. Each served page has a navigation bar at the top where you can *Get* help on an individual item, *Search* all modules with a keyword in their synopsis line, and go to the *Module index*, *Topics* and *Keywords* pages. When **pydoc** generates documentation, it uses the current environment and path to locate modules. Thus, invoking **pydoc spam** documents precisely the version of the module you would get if you started the Python interpreter and typed `import spam`. Module docs for core modules are assumed to reside in `https://docs.python.org/X.Y/library/` where `X` and `Y` are the major and minor version numbers of the Python interpreter. This can be overridden by setting the `PYTHONDOCS` environment variable to a different URL or to a local directory containing the Library Reference Manual pages. Changed in version 3.2: Added the `-b` option. Changed in version 3.3: The `-g` command line option was removed. Changed in version 3.4: [`pydoc`](#module-pydoc "pydoc: Documentation generator and online help system.") now uses [`inspect.signature()`](inspect#inspect.signature "inspect.signature") rather than [`inspect.getfullargspec()`](inspect#inspect.getfullargspec "inspect.getfullargspec") to extract signature information from callables. Changed in version 3.7: Added the `-n` option.
programming_docs
python posix — The most common POSIX system calls posix — The most common POSIX system calls ========================================== This module provides access to operating system functionality that is standardized by the C Standard and the POSIX standard (a thinly disguised Unix interface). **Do not import this module directly.** Instead, import the module [`os`](os#module-os "os: Miscellaneous operating system interfaces."), which provides a *portable* version of this interface. On Unix, the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module provides a superset of the [`posix`](#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)") interface. On non-Unix operating systems the [`posix`](#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)") module is not available, but a subset is always available through the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") interface. Once [`os`](os#module-os "os: Miscellaneous operating system interfaces.") is imported, there is *no* performance penalty in using it instead of [`posix`](#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)"). In addition, [`os`](os#module-os "os: Miscellaneous operating system interfaces.") provides some additional functionality, such as automatically calling [`putenv()`](os#os.putenv "os.putenv") when an entry in `os.environ` is changed. Errors are reported as exceptions; the usual exceptions are given for type errors, while errors reported by the system calls raise [`OSError`](exceptions#OSError "OSError"). Large File Support ------------------ Several operating systems (including AIX, HP-UX, Irix and Solaris) provide support for files that are larger than 2 GiB from a C programming model where `int` and `long` are 32-bit values. This is typically accomplished by defining the relevant size and offset types as 64-bit values. Such files are sometimes referred to as *large files*. Large file support is enabled in Python when the size of an `off_t` is larger than a `long` and the `long long` is at least as large as an `off_t`. It may be necessary to configure and compile Python with certain compiler flags to enable this mode. For example, it is enabled by default with recent versions of Irix, but with Solaris 2.6 and 2.7 you need to do something like: ``` CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \ ./configure ``` On large-file-capable Linux systems, this might work: ``` CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \ ./configure ``` Notable Module Contents ----------------------- In addition to many functions described in the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module documentation, [`posix`](#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)") defines the following data item: `posix.environ` A dictionary representing the string environment at the time the interpreter was started. Keys and values are bytes on Unix and str on Windows. For example, `environ[b'HOME']` (`environ['HOME']` on Windows) is the pathname of your home directory, equivalent to `getenv("HOME")` in C. Modifying this dictionary does not affect the string environment passed on by [`execv()`](os#os.execv "os.execv"), [`popen()`](os#os.popen "os.popen") or [`system()`](os#os.system "os.system"); if you need to change the environment, pass `environ` to [`execve()`](os#os.execve "os.execve") or add variable assignments and export statements to the command string for [`system()`](os#os.system "os.system") or [`popen()`](os#os.popen "os.popen"). Changed in version 3.2: On Unix, keys and values are bytes. Note The [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module provides an alternate implementation of `environ` which updates the environment on modification. Note also that updating [`os.environ`](os#os.environ "os.environ") will render this dictionary obsolete. Use of the [`os`](os#module-os "os: Miscellaneous operating system interfaces.") module version of this is recommended over direct access to the [`posix`](#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)") module. python curses — Terminal handling for character-cell displays curses — Terminal handling for character-cell displays ====================================================== The [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. While curses is most widely used in the Unix environment, versions are available for Windows, DOS, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open-source curses library hosted on Linux and the BSD variants of Unix. Note Whenever the documentation mentions a *character* it can be specified as an integer, a one-character Unicode string or a one-byte byte string. Whenever the documentation mentions a *character string* it can be specified as a Unicode string or a byte string. Note Since version 5.4, the ncurses library decides how to interpret non-ASCII data using the `nl_langinfo` function. That means that you have to call [`locale.setlocale()`](locale#locale.setlocale "locale.setlocale") in the application and encode Unicode strings using one of the system’s available encodings. This example uses the system’s default encoding: ``` import locale locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() ``` Then use *code* as the encoding for [`str.encode()`](stdtypes#str.encode "str.encode") calls. See also `Module` [`curses.ascii`](curses.ascii#module-curses.ascii "curses.ascii: Constants and set-membership functions for ASCII characters.") Utilities for working with ASCII characters, regardless of your locale settings. `Module` [`curses.panel`](curses.panel#module-curses.panel "curses.panel: A panel stack extension that adds depth to curses windows.") A panel stack extension that adds depth to curses windows. `Module` [`curses.textpad`](#module-curses.textpad "curses.textpad: Emacs-like input editing in a curses window.") Editable text widget for curses supporting **Emacs**-like bindings. [Curses Programming with Python](../howto/curses#curses-howto) Tutorial material on using curses with Python, by Andrew Kuchling and Eric Raymond. The [Tools/demo/](https://github.com/python/cpython/tree/3.9/Tools/demo/) directory in the Python source distribution contains some example programs using the curses bindings provided by this module. Functions --------- The module [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") defines the following exception: `exception curses.error` Exception raised when a curses library function returns an error. Note Whenever *x* or *y* arguments to a function or a method are optional, they default to the current cursor location. Whenever *attr* is optional, it defaults to `A_NORMAL`. The module [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") defines the following functions: `curses.baudrate()` Return the output speed of the terminal in bits per second. On software terminal emulators it will have a fixed high value. Included for historical reasons; in former times, it was used to write output loops for time delays and occasionally to change interfaces depending on the line speed. `curses.beep()` Emit a short attention sound. `curses.can_change_color()` Return `True` or `False`, depending on whether the programmer can change the colors displayed by the terminal. `curses.cbreak()` Enter cbreak mode. In cbreak mode (sometimes called “rare” mode) normal tty line buffering is turned off and characters are available to be read one by one. However, unlike raw mode, special characters (interrupt, quit, suspend, and flow control) retain their effects on the tty driver and calling program. Calling first [`raw()`](#curses.raw "curses.raw") then [`cbreak()`](#curses.cbreak "curses.cbreak") leaves the terminal in cbreak mode. `curses.color_content(color_number)` Return the intensity of the red, green, and blue (RGB) components in the color *color\_number*, which must be between `0` and `COLORS - 1`. Return a 3-tuple, containing the R,G,B values for the given color, which will be between `0` (no component) and `1000` (maximum amount of component). `curses.color_pair(pair_number)` Return the attribute value for displaying text in the specified color pair. Only the first 256 color pairs are supported. This attribute value can be combined with `A_STANDOUT`, `A_REVERSE`, and the other `A_*` attributes. [`pair_number()`](#curses.pair_number "curses.pair_number") is the counterpart to this function. `curses.curs_set(visibility)` Set the cursor state. *visibility* can be set to `0`, `1`, or `2`, for invisible, normal, or very visible. If the terminal supports the visibility requested, return the previous cursor state; otherwise raise an exception. On many terminals, the “visible” mode is an underline cursor and the “very visible” mode is a block cursor. `curses.def_prog_mode()` Save the current terminal mode as the “program” mode, the mode when the running program is using curses. (Its counterpart is the “shell” mode, for when the program is not in curses.) Subsequent calls to [`reset_prog_mode()`](#curses.reset_prog_mode "curses.reset_prog_mode") will restore this mode. `curses.def_shell_mode()` Save the current terminal mode as the “shell” mode, the mode when the running program is not using curses. (Its counterpart is the “program” mode, when the program is using curses capabilities.) Subsequent calls to [`reset_shell_mode()`](#curses.reset_shell_mode "curses.reset_shell_mode") will restore this mode. `curses.delay_output(ms)` Insert an *ms* millisecond pause in output. `curses.doupdate()` Update the physical screen. The curses library keeps two data structures, one representing the current physical screen contents and a virtual screen representing the desired next state. The [`doupdate()`](#curses.doupdate "curses.doupdate") ground updates the physical screen to match the virtual screen. The virtual screen may be updated by a [`noutrefresh()`](#curses.window.noutrefresh "curses.window.noutrefresh") call after write operations such as [`addstr()`](#curses.window.addstr "curses.window.addstr") have been performed on a window. The normal [`refresh()`](#curses.window.refresh "curses.window.refresh") call is simply `noutrefresh()` followed by `doupdate()`; if you have to update multiple windows, you can speed performance and perhaps reduce screen flicker by issuing `noutrefresh()` calls on all windows, followed by a single `doupdate()`. `curses.echo()` Enter echo mode. In echo mode, each character input is echoed to the screen as it is entered. `curses.endwin()` De-initialize the library, and return terminal to normal status. `curses.erasechar()` Return the user’s current erase character as a one-byte bytes object. Under Unix operating systems this is a property of the controlling tty of the curses program, and is not set by the curses library itself. `curses.filter()` The [`filter()`](#curses.filter "curses.filter") routine, if used, must be called before [`initscr()`](#curses.initscr "curses.initscr") is called. The effect is that, during those calls, `LINES` is set to `1`; the capabilities `clear`, `cup`, `cud`, `cud1`, `cuu1`, `cuu`, `vpa` are disabled; and the `home` string is set to the value of `cr`. The effect is that the cursor is confined to the current line, and so are screen updates. This may be used for enabling character-at-a-time line editing without touching the rest of the screen. `curses.flash()` Flash the screen. That is, change it to reverse-video and then change it back in a short interval. Some people prefer such as ‘visible bell’ to the audible attention signal produced by [`beep()`](#curses.beep "curses.beep"). `curses.flushinp()` Flush all input buffers. This throws away any typeahead that has been typed by the user and has not yet been processed by the program. `curses.getmouse()` After [`getch()`](#curses.window.getch "curses.window.getch") returns `KEY_MOUSE` to signal a mouse event, this method should be called to retrieve the queued mouse event, represented as a 5-tuple `(id, x, y, z, bstate)`. *id* is an ID value used to distinguish multiple devices, and *x*, *y*, *z* are the event’s coordinates. (*z* is currently unused.) *bstate* is an integer value whose bits will be set to indicate the type of event, and will be the bitwise OR of one or more of the following constants, where *n* is the button number from 1 to 4: `BUTTONn_PRESSED`, `BUTTONn_RELEASED`, `BUTTONn_CLICKED`, `BUTTONn_DOUBLE_CLICKED`, `BUTTONn_TRIPLE_CLICKED`, `BUTTON_SHIFT`, `BUTTON_CTRL`, `BUTTON_ALT`. `curses.getsyx()` Return the current coordinates of the virtual screen cursor as a tuple `(y, x)`. If [`leaveok`](#curses.window.leaveok "curses.window.leaveok") is currently `True`, then return `(-1, -1)`. `curses.getwin(file)` Read window related data stored in the file by an earlier `putwin()` call. The routine then creates and initializes a new window using that data, returning the new window object. `curses.has_colors()` Return `True` if the terminal can display colors; otherwise, return `False`. `curses.has_ic()` Return `True` if the terminal has insert- and delete-character capabilities. This function is included for historical reasons only, as all modern software terminal emulators have such capabilities. `curses.has_il()` Return `True` if the terminal has insert- and delete-line capabilities, or can simulate them using scrolling regions. This function is included for historical reasons only, as all modern software terminal emulators have such capabilities. `curses.has_key(ch)` Take a key value *ch*, and return `True` if the current terminal type recognizes a key with that value. `curses.halfdelay(tenths)` Used for half-delay mode, which is similar to cbreak mode in that characters typed by the user are immediately available to the program. However, after blocking for *tenths* tenths of seconds, raise an exception if nothing has been typed. The value of *tenths* must be a number between `1` and `255`. Use [`nocbreak()`](#curses.nocbreak "curses.nocbreak") to leave half-delay mode. `curses.init_color(color_number, r, g, b)` Change the definition of a color, taking the number of the color to be changed followed by three RGB values (for the amounts of red, green, and blue components). The value of *color\_number* must be between `0` and `COLORS - 1`. Each of *r*, *g*, *b*, must be a value between `0` and `1000`. When [`init_color()`](#curses.init_color "curses.init_color") is used, all occurrences of that color on the screen immediately change to the new definition. This function is a no-op on most terminals; it is active only if [`can_change_color()`](#curses.can_change_color "curses.can_change_color") returns `True`. `curses.init_pair(pair_number, fg, bg)` Change the definition of a color-pair. It takes three arguments: the number of the color-pair to be changed, the foreground color number, and the background color number. The value of *pair\_number* must be between `1` and `COLOR_PAIRS - 1` (the `0` color pair is wired to white on black and cannot be changed). The value of *fg* and *bg* arguments must be between `0` and `COLORS - 1`, or, after calling [`use_default_colors()`](#curses.use_default_colors "curses.use_default_colors"), `-1`. If the color-pair was previously initialized, the screen is refreshed and all occurrences of that color-pair are changed to the new definition. `curses.initscr()` Initialize the library. Return a [window](#curses-window-objects) object which represents the whole screen. Note If there is an error opening the terminal, the underlying curses library may cause the interpreter to exit. `curses.is_term_resized(nlines, ncols)` Return `True` if [`resize_term()`](#curses.resize_term "curses.resize_term") would modify the window structure, `False` otherwise. `curses.isendwin()` Return `True` if [`endwin()`](#curses.endwin "curses.endwin") has been called (that is, the curses library has been deinitialized). `curses.keyname(k)` Return the name of the key numbered *k* as a bytes object. The name of a key generating printable ASCII character is the key’s character. The name of a control-key combination is a two-byte bytes object consisting of a caret (`b'^'`) followed by the corresponding printable ASCII character. The name of an alt-key combination (128–255) is a bytes object consisting of the prefix `b'M-'` followed by the name of the corresponding ASCII character. `curses.killchar()` Return the user’s current line kill character as a one-byte bytes object. Under Unix operating systems this is a property of the controlling tty of the curses program, and is not set by the curses library itself. `curses.longname()` Return a bytes object containing the terminfo long name field describing the current terminal. The maximum length of a verbose description is 128 characters. It is defined only after the call to [`initscr()`](#curses.initscr "curses.initscr"). `curses.meta(flag)` If *flag* is `True`, allow 8-bit characters to be input. If *flag* is `False`, allow only 7-bit chars. `curses.mouseinterval(interval)` Set the maximum time in milliseconds that can elapse between press and release events in order for them to be recognized as a click, and return the previous interval value. The default value is 200 msec, or one fifth of a second. `curses.mousemask(mousemask)` Set the mouse events to be reported, and return a tuple `(availmask, oldmask)`. *availmask* indicates which of the specified mouse events can be reported; on complete failure it returns `0`. *oldmask* is the previous value of the given window’s mouse event mask. If this function is never called, no mouse events are ever reported. `curses.napms(ms)` Sleep for *ms* milliseconds. `curses.newpad(nlines, ncols)` Create and return a pointer to a new pad data structure with the given number of lines and columns. Return a pad as a window object. A pad is like a window, except that it is not restricted by the screen size, and is not necessarily associated with a particular part of the screen. Pads can be used when a large window is needed, and only a part of the window will be on the screen at one time. Automatic refreshes of pads (such as from scrolling or echoing of input) do not occur. The [`refresh()`](#curses.window.refresh "curses.window.refresh") and [`noutrefresh()`](#curses.window.noutrefresh "curses.window.noutrefresh") methods of a pad require 6 arguments to specify the part of the pad to be displayed and the location on the screen to be used for the display. The arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p* arguments refer to the upper left corner of the pad region to be displayed and the *s* arguments define a clipping box on the screen within which the pad region is to be displayed. `curses.newwin(nlines, ncols)` `curses.newwin(nlines, ncols, begin_y, begin_x)` Return a new [window](#curses-window-objects), whose left-upper corner is at `(begin_y, begin_x)`, and whose height/width is *nlines*/*ncols*. By default, the window will extend from the specified position to the lower right corner of the screen. `curses.nl()` Enter newline mode. This mode translates the return key into newline on input, and translates newline into return and line-feed on output. Newline mode is initially on. `curses.nocbreak()` Leave cbreak mode. Return to normal “cooked” mode with line buffering. `curses.noecho()` Leave echo mode. Echoing of input characters is turned off. `curses.nonl()` Leave newline mode. Disable translation of return into newline on input, and disable low-level translation of newline into newline/return on output (but this does not change the behavior of `addch('\n')`, which always does the equivalent of return and line feed on the virtual screen). With translation off, curses can sometimes speed up vertical motion a little; also, it will be able to detect the return key on input. `curses.noqiflush()` When the `noqiflush()` routine is used, normal flush of input and output queues associated with the `INTR`, `QUIT` and `SUSP` characters will not be done. You may want to call `noqiflush()` in a signal handler if you want output to continue as though the interrupt had not occurred, after the handler exits. `curses.noraw()` Leave raw mode. Return to normal “cooked” mode with line buffering. `curses.pair_content(pair_number)` Return a tuple `(fg, bg)` containing the colors for the requested color pair. The value of *pair\_number* must be between `0` and `COLOR_PAIRS - 1`. `curses.pair_number(attr)` Return the number of the color-pair set by the attribute value *attr*. [`color_pair()`](#curses.color_pair "curses.color_pair") is the counterpart to this function. `curses.putp(str)` Equivalent to `tputs(str, 1, putchar)`; emit the value of a specified terminfo capability for the current terminal. Note that the output of [`putp()`](#curses.putp "curses.putp") always goes to standard output. `curses.qiflush([flag])` If *flag* is `False`, the effect is the same as calling [`noqiflush()`](#curses.noqiflush "curses.noqiflush"). If *flag* is `True`, or no argument is provided, the queues will be flushed when these control characters are read. `curses.raw()` Enter raw mode. In raw mode, normal line buffering and processing of interrupt, quit, suspend, and flow control keys are turned off; characters are presented to curses input functions one by one. `curses.reset_prog_mode()` Restore the terminal to “program” mode, as previously saved by [`def_prog_mode()`](#curses.def_prog_mode "curses.def_prog_mode"). `curses.reset_shell_mode()` Restore the terminal to “shell” mode, as previously saved by [`def_shell_mode()`](#curses.def_shell_mode "curses.def_shell_mode"). `curses.resetty()` Restore the state of the terminal modes to what it was at the last call to [`savetty()`](#curses.savetty "curses.savetty"). `curses.resize_term(nlines, ncols)` Backend function used by [`resizeterm()`](#curses.resizeterm "curses.resizeterm"), performing most of the work; when resizing the windows, [`resize_term()`](#curses.resize_term "curses.resize_term") blank-fills the areas that are extended. The calling application should fill in these areas with appropriate data. The `resize_term()` function attempts to resize all windows. However, due to the calling convention of pads, it is not possible to resize these without additional interaction with the application. `curses.resizeterm(nlines, ncols)` Resize the standard and current windows to the specified dimensions, and adjusts other bookkeeping data used by the curses library that record the window dimensions (in particular the SIGWINCH handler). `curses.savetty()` Save the current state of the terminal modes in a buffer, usable by [`resetty()`](#curses.resetty "curses.resetty"). `curses.get_escdelay()` Retrieves the value set by [`set_escdelay()`](#curses.set_escdelay "curses.set_escdelay"). New in version 3.9. `curses.set_escdelay(ms)` Sets the number of milliseconds to wait after reading an escape character, to distinguish between an individual escape character entered on the keyboard from escape sequences sent by cursor and function keys. New in version 3.9. `curses.get_tabsize()` Retrieves the value set by [`set_tabsize()`](#curses.set_tabsize "curses.set_tabsize"). New in version 3.9. `curses.set_tabsize(size)` Sets the number of columns used by the curses library when converting a tab character to spaces as it adds the tab to a window. New in version 3.9. `curses.setsyx(y, x)` Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both `-1`, then [`leaveok`](#curses.window.leaveok "curses.window.leaveok") is set `True`. `curses.setupterm(term=None, fd=-1)` Initialize the terminal. *term* is a string giving the terminal name, or `None`; if omitted or `None`, the value of the `TERM` environment variable will be used. *fd* is the file descriptor to which any initialization sequences will be sent; if not supplied or `-1`, the file descriptor for `sys.stdout` will be used. `curses.start_color()` Must be called if the programmer wants to use colors, and before any other color manipulation routine is called. It is good practice to call this routine right after [`initscr()`](#curses.initscr "curses.initscr"). [`start_color()`](#curses.start_color "curses.start_color") initializes eight basic colors (black, red, green, yellow, blue, magenta, cyan, and white), and two global variables in the [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module, `COLORS` and `COLOR_PAIRS`, containing the maximum number of colors and color-pairs the terminal can support. It also restores the colors on the terminal to the values they had when the terminal was just turned on. `curses.termattrs()` Return a logical OR of all video attributes supported by the terminal. This information is useful when a curses program needs complete control over the appearance of the screen. `curses.termname()` Return the value of the environment variable `TERM`, as a bytes object, truncated to 14 characters. `curses.tigetflag(capname)` Return the value of the Boolean capability corresponding to the terminfo capability name *capname* as an integer. Return the value `-1` if *capname* is not a Boolean capability, or `0` if it is canceled or absent from the terminal description. `curses.tigetnum(capname)` Return the value of the numeric capability corresponding to the terminfo capability name *capname* as an integer. Return the value `-2` if *capname* is not a numeric capability, or `-1` if it is canceled or absent from the terminal description. `curses.tigetstr(capname)` Return the value of the string capability corresponding to the terminfo capability name *capname* as a bytes object. Return `None` if *capname* is not a terminfo “string capability”, or is canceled or absent from the terminal description. `curses.tparm(str[, ...])` Instantiate the bytes object *str* with the supplied parameters, where *str* should be a parameterized string obtained from the terminfo database. E.g. `tparm(tigetstr("cup"), 5, 3)` could result in `b'\033[6;4H'`, the exact result depending on terminal type. `curses.typeahead(fd)` Specify that the file descriptor *fd* be used for typeahead checking. If *fd* is `-1`, then no typeahead checking is done. The curses library does “line-breakout optimization” by looking for typeahead periodically while updating the screen. If input is found, and it is coming from a tty, the current update is postponed until refresh or doupdate is called again, allowing faster response to commands typed in advance. This function allows specifying a different file descriptor for typeahead checking. `curses.unctrl(ch)` Return a bytes object which is a printable representation of the character *ch*. Control characters are represented as a caret followed by the character, for example as `b'^C'`. Printing characters are left as they are. `curses.ungetch(ch)` Push *ch* so the next [`getch()`](#curses.window.getch "curses.window.getch") will return it. Note Only one *ch* can be pushed before `getch()` is called. `curses.update_lines_cols()` Update `LINES` and `COLS`. Useful for detecting manual screen resize. New in version 3.5. `curses.unget_wch(ch)` Push *ch* so the next [`get_wch()`](#curses.window.get_wch "curses.window.get_wch") will return it. Note Only one *ch* can be pushed before `get_wch()` is called. New in version 3.3. `curses.ungetmouse(id, x, y, z, bstate)` Push a `KEY_MOUSE` event onto the input queue, associating the given state data with it. `curses.use_env(flag)` If used, this function should be called before [`initscr()`](#curses.initscr "curses.initscr") or newterm are called. When *flag* is `False`, the values of lines and columns specified in the terminfo database will be used, even if environment variables `LINES` and `COLUMNS` (used by default) are set, or if curses is running in a window (in which case default behavior would be to use the window size if `LINES` and `COLUMNS` are not set). `curses.use_default_colors()` Allow use of default values for colors on terminals supporting this feature. Use this to support transparency in your application. The default color is assigned to the color number `-1`. After calling this function, `init_pair(x, curses.COLOR_RED, -1)` initializes, for instance, color pair *x* to a red foreground color on the default background. `curses.wrapper(func, /, *args, **kwargs)` Initialize curses and call another callable object, *func*, which should be the rest of your curses-using application. If the application raises an exception, this function will restore the terminal to a sane state before re-raising the exception and generating a traceback. The callable object *func* is then passed the main window ‘stdscr’ as its first argument, followed by any other arguments passed to `wrapper()`. Before calling *func*, `wrapper()` turns on cbreak mode, turns off echo, enables the terminal keypad, and initializes colors if the terminal has color support. On exit (whether normally or by exception) it restores cooked mode, turns on echo, and disables the terminal keypad. Window Objects -------------- Window objects, as returned by [`initscr()`](#curses.initscr "curses.initscr") and [`newwin()`](#curses.newwin "curses.newwin") above, have the following methods and attributes: `window.addch(ch[, attr])` `window.addch(y, x, ch[, attr])` Paint character *ch* at `(y, x)` with attributes *attr*, overwriting any character previously painted at that location. By default, the character position and attributes are the current settings for the window object. Note Writing outside the window, subwindow, or pad raises a [`curses.error`](#curses.error "curses.error"). Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the character is printed. `window.addnstr(str, n[, attr])` `window.addnstr(y, x, str, n[, attr])` Paint at most *n* characters of the character string *str* at `(y, x)` with attributes *attr*, overwriting anything previously on the display. `window.addstr(str[, attr])` `window.addstr(y, x, str[, attr])` Paint the character string *str* at `(y, x)` with attributes *attr*, overwriting anything previously on the display. Note * Writing outside the window, subwindow, or pad raises [`curses.error`](#curses.error "curses.error"). Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the string is printed. * A [bug in ncurses](https://bugs.python.org/issue35924), the backend for this Python module, can cause SegFaults when resizing windows. This is fixed in ncurses-6.1-20190511. If you are stuck with an earlier ncurses, you can avoid triggering this if you do not call [`addstr()`](#curses.window.addstr "curses.window.addstr") with a *str* that has embedded newlines. Instead, call [`addstr()`](#curses.window.addstr "curses.window.addstr") separately for each line. `window.attroff(attr)` Remove attribute *attr* from the “background” set applied to all writes to the current window. `window.attron(attr)` Add attribute *attr* from the “background” set applied to all writes to the current window. `window.attrset(attr)` Set the “background” set of attributes to *attr*. This set is initially `0` (no attributes). `window.bkgd(ch[, attr])` Set the background property of the window to the character *ch*, with attributes *attr*. The change is then applied to every character position in that window: * The attribute of every character in the window is changed to the new background attribute. * Wherever the former background character appears, it is changed to the new background character. `window.bkgdset(ch[, attr])` Set the window’s background. A window’s background consists of a character and any combination of attributes. The attribute part of the background is combined (OR’ed) with all non-blank characters that are written into the window. Both the character and attribute parts of the background are combined with the blank characters. The background becomes a property of the character and moves with the character through any scrolling and insert/delete line/character operations. `window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])` Draw a border around the edges of the window. Each parameter specifies the character to use for a specific part of the border; see the table below for more details. Note A `0` value for any parameter will cause the default character to be used for that parameter. Keyword parameters can *not* be used. The defaults are listed in this table: | Parameter | Description | Default value | | --- | --- | --- | | *ls* | Left side | `ACS_VLINE` | | *rs* | Right side | `ACS_VLINE` | | *ts* | Top | `ACS_HLINE` | | *bs* | Bottom | `ACS_HLINE` | | *tl* | Upper-left corner | `ACS_ULCORNER` | | *tr* | Upper-right corner | `ACS_URCORNER` | | *bl* | Bottom-left corner | `ACS_LLCORNER` | | *br* | Bottom-right corner | `ACS_LRCORNER` | `window.box([vertch, horch])` Similar to [`border()`](#curses.window.border "curses.window.border"), but both *ls* and *rs* are *vertch* and both *ts* and *bs* are *horch*. The default corner characters are always used by this function. `window.chgat(attr)` `window.chgat(num, attr)` `window.chgat(y, x, attr)` `window.chgat(y, x, num, attr)` Set the attributes of *num* characters at the current cursor position, or at position `(y, x)` if supplied. If *num* is not given or is `-1`, the attribute will be set on all the characters to the end of the line. This function moves cursor to position `(y, x)` if supplied. The changed line will be touched using the [`touchline()`](#curses.window.touchline "curses.window.touchline") method so that the contents will be redisplayed by the next window refresh. `window.clear()` Like [`erase()`](#curses.window.erase "curses.window.erase"), but also cause the whole window to be repainted upon next call to [`refresh()`](#curses.window.refresh "curses.window.refresh"). `window.clearok(flag)` If *flag* is `True`, the next call to [`refresh()`](#curses.window.refresh "curses.window.refresh") will clear the window completely. `window.clrtobot()` Erase from cursor to the end of the window: all lines below the cursor are deleted, and then the equivalent of [`clrtoeol()`](#curses.window.clrtoeol "curses.window.clrtoeol") is performed. `window.clrtoeol()` Erase from cursor to the end of the line. `window.cursyncup()` Update the current cursor position of all the ancestors of the window to reflect the current cursor position of the window. `window.delch([y, x])` Delete any character at `(y, x)`. `window.deleteln()` Delete the line under the cursor. All following lines are moved up by one line. `window.derwin(begin_y, begin_x)` `window.derwin(nlines, ncols, begin_y, begin_x)` An abbreviation for “derive window”, [`derwin()`](#curses.window.derwin "curses.window.derwin") is the same as calling [`subwin()`](#curses.window.subwin "curses.window.subwin"), except that *begin\_y* and *begin\_x* are relative to the origin of the window, rather than relative to the entire screen. Return a window object for the derived window. `window.echochar(ch[, attr])` Add character *ch* with attribute *attr*, and immediately call [`refresh()`](#curses.window.refresh "curses.window.refresh") on the window. `window.enclose(y, x)` Test whether the given pair of screen-relative character-cell coordinates are enclosed by the given window, returning `True` or `False`. It is useful for determining what subset of the screen windows enclose the location of a mouse event. `window.encoding` Encoding used to encode method arguments (Unicode strings and characters). The encoding attribute is inherited from the parent window when a subwindow is created, for example with [`window.subwin()`](#curses.window.subwin "curses.window.subwin"). By default, the locale encoding is used (see [`locale.getpreferredencoding()`](locale#locale.getpreferredencoding "locale.getpreferredencoding")). New in version 3.3. `window.erase()` Clear the window. `window.getbegyx()` Return a tuple `(y, x)` of co-ordinates of upper-left corner. `window.getbkgd()` Return the given window’s current background character/attribute pair. `window.getch([y, x])` Get a character. Note that the integer returned does *not* have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return `-1` if there is no input, otherwise wait until a key is pressed. `window.get_wch([y, x])` Get a wide character. Return a character for most keys, or an integer for function keys, keypad keys, and other special keys. In no-delay mode, raise an exception if there is no input. New in version 3.3. `window.getkey([y, x])` Get a character, returning a string instead of an integer, as [`getch()`](#curses.window.getch "curses.window.getch") does. Function keys, keypad keys and other special keys return a multibyte string containing the key name. In no-delay mode, raise an exception if there is no input. `window.getmaxyx()` Return a tuple `(y, x)` of the height and width of the window. `window.getparyx()` Return the beginning coordinates of this window relative to its parent window as a tuple `(y, x)`. Return `(-1, -1)` if this window has no parent. `window.getstr()` `window.getstr(n)` `window.getstr(y, x)` `window.getstr(y, x, n)` Read a bytes object from the user, with primitive line editing capacity. `window.getyx()` Return a tuple `(y, x)` of current cursor position relative to the window’s upper-left corner. `window.hline(ch, n)` `window.hline(y, x, ch, n)` Display a horizontal line starting at `(y, x)` with length *n* consisting of the character *ch*. `window.idcok(flag)` If *flag* is `False`, curses no longer considers using the hardware insert/delete character feature of the terminal; if *flag* is `True`, use of character insertion and deletion is enabled. When curses is first initialized, use of character insert/delete is enabled by default. `window.idlok(flag)` If *flag* is `True`, [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") will try and use hardware line editing facilities. Otherwise, line insertion/deletion are disabled. `window.immedok(flag)` If *flag* is `True`, any change in the window image automatically causes the window to be refreshed; you no longer have to call [`refresh()`](#curses.window.refresh "curses.window.refresh") yourself. However, it may degrade performance considerably, due to repeated calls to wrefresh. This option is disabled by default. `window.inch([y, x])` Return the character at the given position in the window. The bottom 8 bits are the character proper, and upper bits are the attributes. `window.insch(ch[, attr])` `window.insch(y, x, ch[, attr])` Paint character *ch* at `(y, x)` with attributes *attr*, moving the line from position *x* right by one character. `window.insdelln(nlines)` Insert *nlines* lines into the specified window above the current line. The *nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines starting with the one under the cursor, and move the remaining lines up. The bottom *nlines* lines are cleared. The current cursor position remains the same. `window.insertln()` Insert a blank line under the cursor. All following lines are moved down by one line. `window.insnstr(str, n[, attr])` `window.insnstr(y, x, str, n[, attr])` Insert a character string (as many characters as will fit on the line) before the character under the cursor, up to *n* characters. If *n* is zero or negative, the entire string is inserted. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to *y*, *x*, if specified). `window.insstr(str[, attr])` `window.insstr(y, x, str[, attr])` Insert a character string (as many characters as will fit on the line) before the character under the cursor. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to *y*, *x*, if specified). `window.instr([n])` `window.instr(y, x[, n])` Return a bytes object of characters, extracted from the window starting at the current cursor position, or at *y*, *x* if specified. Attributes are stripped from the characters. If *n* is specified, [`instr()`](#curses.window.instr "curses.window.instr") returns a string at most *n* characters long (exclusive of the trailing NUL). `window.is_linetouched(line)` Return `True` if the specified line was modified since the last call to [`refresh()`](#curses.window.refresh "curses.window.refresh"); otherwise return `False`. Raise a [`curses.error`](#curses.error "curses.error") exception if *line* is not valid for the given window. `window.is_wintouched()` Return `True` if the specified window was modified since the last call to [`refresh()`](#curses.window.refresh "curses.window.refresh"); otherwise return `False`. `window.keypad(flag)` If *flag* is `True`, escape sequences generated by some keys (keypad, function keys) will be interpreted by [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)"). If *flag* is `False`, escape sequences will be left as is in the input stream. `window.leaveok(flag)` If *flag* is `True`, cursor is left where it is on update, instead of being at “cursor position.” This reduces cursor movement where possible. If possible the cursor will be made invisible. If *flag* is `False`, cursor will always be at “cursor position” after an update. `window.move(new_y, new_x)` Move cursor to `(new_y, new_x)`. `window.mvderwin(y, x)` Move the window inside its parent window. The screen-relative parameters of the window are not changed. This routine is used to display different parts of the parent window at the same physical position on the screen. `window.mvwin(new_y, new_x)` Move the window so its upper-left corner is at `(new_y, new_x)`. `window.nodelay(flag)` If *flag* is `True`, [`getch()`](#curses.window.getch "curses.window.getch") will be non-blocking. `window.notimeout(flag)` If *flag* is `True`, escape sequences will not be timed out. If *flag* is `False`, after a few milliseconds, an escape sequence will not be interpreted, and will be left in the input stream as is. `window.noutrefresh()` Mark for refresh but wait. This function updates the data structure representing the desired state of the window, but does not force an update of the physical screen. To accomplish that, call [`doupdate()`](#curses.doupdate "curses.doupdate"). `window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])` Overlay the window on top of *destwin*. The windows need not be the same size, only the overlapping region is copied. This copy is non-destructive, which means that the current background character does not overwrite the old contents of *destwin*. To get fine-grained control over the copied region, the second form of [`overlay()`](#curses.window.overlay "curses.window.overlay") can be used. *sminrow* and *smincol* are the upper-left coordinates of the source window, and the other variables mark a rectangle in the destination window. `window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])` Overwrite the window on top of *destwin*. The windows need not be the same size, in which case only the overlapping region is copied. This copy is destructive, which means that the current background character overwrites the old contents of *destwin*. To get fine-grained control over the copied region, the second form of [`overwrite()`](#curses.window.overwrite "curses.window.overwrite") can be used. *sminrow* and *smincol* are the upper-left coordinates of the source window, the other variables mark a rectangle in the destination window. `window.putwin(file)` Write all data associated with the window into the provided file object. This information can be later retrieved using the [`getwin()`](#curses.getwin "curses.getwin") function. `window.redrawln(beg, num)` Indicate that the *num* screen lines, starting at line *beg*, are corrupted and should be completely redrawn on the next [`refresh()`](#curses.window.refresh "curses.window.refresh") call. `window.redrawwin()` Touch the entire window, causing it to be completely redrawn on the next [`refresh()`](#curses.window.refresh "curses.window.refresh") call. `window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])` Update the display immediately (sync actual screen with previous drawing/deleting methods). The 6 optional arguments can only be specified when the window is a pad created with [`newpad()`](#curses.newpad "curses.newpad"). The additional parameters are needed to indicate what part of the pad and screen are involved. *pminrow* and *pmincol* specify the upper left-hand corner of the rectangle to be displayed in the pad. *sminrow*, *smincol*, *smaxrow*, and *smaxcol* specify the edges of the rectangle to be displayed on the screen. The lower right-hand corner of the rectangle to be displayed in the pad is calculated from the screen coordinates, since the rectangles must be the same size. Both rectangles must be entirely contained within their respective structures. Negative values of *pminrow*, *pmincol*, *sminrow*, or *smincol* are treated as if they were zero. `window.resize(nlines, ncols)` Reallocate storage for a curses window to adjust its dimensions to the specified values. If either dimension is larger than the current values, the window’s data is filled with blanks that have the current background rendition (as set by [`bkgdset()`](#curses.window.bkgdset "curses.window.bkgdset")) merged into them. `window.scroll([lines=1])` Scroll the screen or scrolling region upward by *lines* lines. `window.scrollok(flag)` Control what happens when the cursor of a window is moved off the edge of the window or scrolling region, either as a result of a newline action on the bottom line, or typing the last character of the last line. If *flag* is `False`, the cursor is left on the bottom line. If *flag* is `True`, the window is scrolled up one line. Note that in order to get the physical scrolling effect on the terminal, it is also necessary to call [`idlok()`](#curses.window.idlok "curses.window.idlok"). `window.setscrreg(top, bottom)` Set the scrolling region from line *top* to line *bottom*. All scrolling actions will take place in this region. `window.standend()` Turn off the standout attribute. On some terminals this has the side effect of turning off all attributes. `window.standout()` Turn on attribute *A\_STANDOUT*. `window.subpad(begin_y, begin_x)` `window.subpad(nlines, ncols, begin_y, begin_x)` Return a sub-window, whose upper-left corner is at `(begin_y, begin_x)`, and whose width/height is *ncols*/*nlines*. `window.subwin(begin_y, begin_x)` `window.subwin(nlines, ncols, begin_y, begin_x)` Return a sub-window, whose upper-left corner is at `(begin_y, begin_x)`, and whose width/height is *ncols*/*nlines*. By default, the sub-window will extend from the specified position to the lower right corner of the window. `window.syncdown()` Touch each location in the window that has been touched in any of its ancestor windows. This routine is called by [`refresh()`](#curses.window.refresh "curses.window.refresh"), so it should almost never be necessary to call it manually. `window.syncok(flag)` If *flag* is `True`, then [`syncup()`](#curses.window.syncup "curses.window.syncup") is called automatically whenever there is a change in the window. `window.syncup()` Touch all locations in ancestors of the window that have been changed in the window. `window.timeout(delay)` Set blocking or non-blocking read behavior for the window. If *delay* is negative, blocking read is used (which will wait indefinitely for input). If *delay* is zero, then non-blocking read is used, and [`getch()`](#curses.window.getch "curses.window.getch") will return `-1` if no input is waiting. If *delay* is positive, then [`getch()`](#curses.window.getch "curses.window.getch") will block for *delay* milliseconds, and return `-1` if there is still no input at the end of that time. `window.touchline(start, count[, changed])` Pretend *count* lines have been changed, starting with line *start*. If *changed* is supplied, it specifies whether the affected lines are marked as having been changed (*changed*`=True`) or unchanged (*changed*`=False`). `window.touchwin()` Pretend the whole window has been changed, for purposes of drawing optimizations. `window.untouchwin()` Mark all lines in the window as unchanged since the last call to [`refresh()`](#curses.window.refresh "curses.window.refresh"). `window.vline(ch, n)` `window.vline(y, x, ch, n)` Display a vertical line starting at `(y, x)` with length *n* consisting of the character *ch*. Constants --------- The [`curses`](#module-curses "curses: An interface to the curses library, providing portable terminal handling. (Unix)") module defines the following data members: `curses.ERR` Some curses routines that return an integer, such as [`getch()`](#curses.window.getch "curses.window.getch"), return [`ERR`](#curses.ERR "curses.ERR") upon failure. `curses.OK` Some curses routines that return an integer, such as [`napms()`](#curses.napms "curses.napms"), return [`OK`](#curses.OK "curses.OK") upon success. `curses.version` A bytes object representing the current version of the module. Also available as `__version__`. `curses.ncurses_version` A named tuple containing the three components of the ncurses library version: *major*, *minor*, and *patch*. All values are integers. The components can also be accessed by name, so `curses.ncurses_version[0]` is equivalent to `curses.ncurses_version.major` and so on. Availability: if the ncurses library is used. New in version 3.8. Some constants are available to specify character cell attributes. The exact constants available are system dependent. | Attribute | Meaning | | --- | --- | | `A_ALTCHARSET` | Alternate character set mode | | `A_BLINK` | Blink mode | | `A_BOLD` | Bold mode | | `A_DIM` | Dim mode | | `A_INVIS` | Invisible or blank mode | | `A_ITALIC` | Italic mode | | `A_NORMAL` | Normal attribute | | `A_PROTECT` | Protected mode | | `A_REVERSE` | Reverse background and foreground colors | | `A_STANDOUT` | Standout mode | | `A_UNDERLINE` | Underline mode | | `A_HORIZONTAL` | Horizontal highlight | | `A_LEFT` | Left highlight | | `A_LOW` | Low highlight | | `A_RIGHT` | Right highlight | | `A_TOP` | Top highlight | | `A_VERTICAL` | Vertical highlight | | `A_CHARTEXT` | Bit-mask to extract a character | New in version 3.7: `A_ITALIC` was added. Several constants are available to extract corresponding attributes returned by some methods. | Bit-mask | Meaning | | --- | --- | | `A_ATTRIBUTES` | Bit-mask to extract attributes | | `A_CHARTEXT` | Bit-mask to extract a character | | `A_COLOR` | Bit-mask to extract color-pair field information | Keys are referred to by integer constants with names starting with `KEY_`. The exact keycaps available are system dependent. | Key constant | Key | | --- | --- | | `KEY_MIN` | Minimum key value | | `KEY_BREAK` | Break key (unreliable) | | `KEY_DOWN` | Down-arrow | | `KEY_UP` | Up-arrow | | `KEY_LEFT` | Left-arrow | | `KEY_RIGHT` | Right-arrow | | `KEY_HOME` | Home key (upward+left arrow) | | `KEY_BACKSPACE` | Backspace (unreliable) | | `KEY_F0` | Function keys. Up to 64 function keys are supported. | | `KEY_Fn` | Value of function key *n* | | `KEY_DL` | Delete line | | `KEY_IL` | Insert line | | `KEY_DC` | Delete character | | `KEY_IC` | Insert char or enter insert mode | | `KEY_EIC` | Exit insert char mode | | `KEY_CLEAR` | Clear screen | | `KEY_EOS` | Clear to end of screen | | `KEY_EOL` | Clear to end of line | | `KEY_SF` | Scroll 1 line forward | | `KEY_SR` | Scroll 1 line backward (reverse) | | `KEY_NPAGE` | Next page | | `KEY_PPAGE` | Previous page | | `KEY_STAB` | Set tab | | `KEY_CTAB` | Clear tab | | `KEY_CATAB` | Clear all tabs | | `KEY_ENTER` | Enter or send (unreliable) | | `KEY_SRESET` | Soft (partial) reset (unreliable) | | `KEY_RESET` | Reset or hard reset (unreliable) | | `KEY_PRINT` | Print | | `KEY_LL` | Home down or bottom (lower left) | | `KEY_A1` | Upper left of keypad | | `KEY_A3` | Upper right of keypad | | `KEY_B2` | Center of keypad | | `KEY_C1` | Lower left of keypad | | `KEY_C3` | Lower right of keypad | | `KEY_BTAB` | Back tab | | `KEY_BEG` | Beg (beginning) | | `KEY_CANCEL` | Cancel | | `KEY_CLOSE` | Close | | `KEY_COMMAND` | Cmd (command) | | `KEY_COPY` | Copy | | `KEY_CREATE` | Create | | `KEY_END` | End | | `KEY_EXIT` | Exit | | `KEY_FIND` | Find | | `KEY_HELP` | Help | | `KEY_MARK` | Mark | | `KEY_MESSAGE` | Message | | `KEY_MOVE` | Move | | `KEY_NEXT` | Next | | `KEY_OPEN` | Open | | `KEY_OPTIONS` | Options | | `KEY_PREVIOUS` | Prev (previous) | | `KEY_REDO` | Redo | | `KEY_REFERENCE` | Ref (reference) | | `KEY_REFRESH` | Refresh | | `KEY_REPLACE` | Replace | | `KEY_RESTART` | Restart | | `KEY_RESUME` | Resume | | `KEY_SAVE` | Save | | `KEY_SBEG` | Shifted Beg (beginning) | | `KEY_SCANCEL` | Shifted Cancel | | `KEY_SCOMMAND` | Shifted Command | | `KEY_SCOPY` | Shifted Copy | | `KEY_SCREATE` | Shifted Create | | `KEY_SDC` | Shifted Delete char | | `KEY_SDL` | Shifted Delete line | | `KEY_SELECT` | Select | | `KEY_SEND` | Shifted End | | `KEY_SEOL` | Shifted Clear line | | `KEY_SEXIT` | Shifted Exit | | `KEY_SFIND` | Shifted Find | | `KEY_SHELP` | Shifted Help | | `KEY_SHOME` | Shifted Home | | `KEY_SIC` | Shifted Input | | `KEY_SLEFT` | Shifted Left arrow | | `KEY_SMESSAGE` | Shifted Message | | `KEY_SMOVE` | Shifted Move | | `KEY_SNEXT` | Shifted Next | | `KEY_SOPTIONS` | Shifted Options | | `KEY_SPREVIOUS` | Shifted Prev | | `KEY_SPRINT` | Shifted Print | | `KEY_SREDO` | Shifted Redo | | `KEY_SREPLACE` | Shifted Replace | | `KEY_SRIGHT` | Shifted Right arrow | | `KEY_SRSUME` | Shifted Resume | | `KEY_SSAVE` | Shifted Save | | `KEY_SSUSPEND` | Shifted Suspend | | `KEY_SUNDO` | Shifted Undo | | `KEY_SUSPEND` | Suspend | | `KEY_UNDO` | Undo | | `KEY_MOUSE` | Mouse event has occurred | | `KEY_RESIZE` | Terminal resize event | | `KEY_MAX` | Maximum key value | On VT100s and their software emulations, such as X terminal emulators, there are normally at least four function keys (`KEY_F1`, `KEY_F2`, `KEY_F3`, `KEY_F4`) available, and the arrow keys mapped to `KEY_UP`, `KEY_DOWN`, `KEY_LEFT` and `KEY_RIGHT` in the obvious way. If your machine has a PC keyboard, it is safe to expect arrow keys and twelve function keys (older PC keyboards may have only ten function keys); also, the following keypad mappings are standard: | Keycap | Constant | | --- | --- | | `Insert` | KEY\_IC | | `Delete` | KEY\_DC | | `Home` | KEY\_HOME | | `End` | KEY\_END | | `Page Up` | KEY\_PPAGE | | `Page Down` | KEY\_NPAGE | The following table lists characters from the alternate character set. These are inherited from the VT100 terminal, and will generally be available on software emulations such as X terminals. When there is no graphic available, curses falls back on a crude printable ASCII approximation. Note These are available only after [`initscr()`](#curses.initscr "curses.initscr") has been called. | ACS code | Meaning | | --- | --- | | `ACS_BBSS` | alternate name for upper right corner | | `ACS_BLOCK` | solid square block | | `ACS_BOARD` | board of squares | | `ACS_BSBS` | alternate name for horizontal line | | `ACS_BSSB` | alternate name for upper left corner | | `ACS_BSSS` | alternate name for top tee | | `ACS_BTEE` | bottom tee | | `ACS_BULLET` | bullet | | `ACS_CKBOARD` | checker board (stipple) | | `ACS_DARROW` | arrow pointing down | | `ACS_DEGREE` | degree symbol | | `ACS_DIAMOND` | diamond | | `ACS_GEQUAL` | greater-than-or-equal-to | | `ACS_HLINE` | horizontal line | | `ACS_LANTERN` | lantern symbol | | `ACS_LARROW` | left arrow | | `ACS_LEQUAL` | less-than-or-equal-to | | `ACS_LLCORNER` | lower left-hand corner | | `ACS_LRCORNER` | lower right-hand corner | | `ACS_LTEE` | left tee | | `ACS_NEQUAL` | not-equal sign | | `ACS_PI` | letter pi | | `ACS_PLMINUS` | plus-or-minus sign | | `ACS_PLUS` | big plus sign | | `ACS_RARROW` | right arrow | | `ACS_RTEE` | right tee | | `ACS_S1` | scan line 1 | | `ACS_S3` | scan line 3 | | `ACS_S7` | scan line 7 | | `ACS_S9` | scan line 9 | | `ACS_SBBS` | alternate name for lower right corner | | `ACS_SBSB` | alternate name for vertical line | | `ACS_SBSS` | alternate name for right tee | | `ACS_SSBB` | alternate name for lower left corner | | `ACS_SSBS` | alternate name for bottom tee | | `ACS_SSSB` | alternate name for left tee | | `ACS_SSSS` | alternate name for crossover or big plus | | `ACS_STERLING` | pound sterling | | `ACS_TTEE` | top tee | | `ACS_UARROW` | up arrow | | `ACS_ULCORNER` | upper left corner | | `ACS_URCORNER` | upper right corner | | `ACS_VLINE` | vertical line | The following table lists the predefined colors: | Constant | Color | | --- | --- | | `COLOR_BLACK` | Black | | `COLOR_BLUE` | Blue | | `COLOR_CYAN` | Cyan (light greenish blue) | | `COLOR_GREEN` | Green | | `COLOR_MAGENTA` | Magenta (purplish red) | | `COLOR_RED` | Red | | `COLOR_WHITE` | White | | `COLOR_YELLOW` | Yellow |
programming_docs
python importlib — The implementation of import importlib — The implementation of import ======================================== New in version 3.1. **Source code:** [Lib/importlib/\_\_init\_\_.py](https://github.com/python/cpython/tree/3.9/Lib/importlib/__init__.py) Introduction ------------ The purpose of the [`importlib`](#module-importlib "importlib: The implementation of the import machinery.") package is two-fold. One is to provide the implementation of the [`import`](../reference/simple_stmts#import) statement (and thus, by extension, the [`__import__()`](functions#__import__ "__import__") function) in Python source code. This provides an implementation of `import` which is portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python. Two, the components to implement [`import`](../reference/simple_stmts#import) are exposed in this package, making it easier for users to create their own custom objects (known generically as an [importer](../glossary#term-importer)) to participate in the import process. See also [The import statement](../reference/simple_stmts#import) The language reference for the [`import`](../reference/simple_stmts#import) statement. [Packages specification](https://www.python.org/doc/essays/packages/) Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on `None` in [`sys.modules`](sys#sys.modules "sys.modules")). `The __import__() function` The [`import`](../reference/simple_stmts#import) statement is syntactic sugar for this function. [**PEP 235**](https://www.python.org/dev/peps/pep-0235) Import on Case-Insensitive Platforms [**PEP 263**](https://www.python.org/dev/peps/pep-0263) Defining Python Source Code Encodings [**PEP 302**](https://www.python.org/dev/peps/pep-0302) New Import Hooks [**PEP 328**](https://www.python.org/dev/peps/pep-0328) Imports: Multi-Line and Absolute/Relative [**PEP 366**](https://www.python.org/dev/peps/pep-0366) Main module explicit relative imports [**PEP 420**](https://www.python.org/dev/peps/pep-0420) Implicit namespace packages [**PEP 451**](https://www.python.org/dev/peps/pep-0451) A ModuleSpec Type for the Import System [**PEP 488**](https://www.python.org/dev/peps/pep-0488) Elimination of PYO files [**PEP 489**](https://www.python.org/dev/peps/pep-0489) Multi-phase extension module initialization [**PEP 552**](https://www.python.org/dev/peps/pep-0552) Deterministic pycs [**PEP 3120**](https://www.python.org/dev/peps/pep-3120) Using UTF-8 as the Default Source Encoding [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) PYC Repository Directories Functions --------- `importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)` An implementation of the built-in [`__import__()`](functions#__import__ "__import__") function. Note Programmatic importing of modules should use [`import_module()`](#importlib.import_module "importlib.import_module") instead of this function. `importlib.import_module(name, package=None)` Import a module. The *name* argument specifies what module to import in absolute or relative terms (e.g. either `pkg.mod` or `..mod`). If the name is specified in relative terms, then the *package* argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. `import_module('..mod', 'pkg.subpkg')` will import `pkg.mod`). The [`import_module()`](#importlib.import_module "importlib.import_module") function acts as a simplifying wrapper around [`importlib.__import__()`](#importlib.__import__ "importlib.__import__"). This means all semantics of the function are derived from [`importlib.__import__()`](#importlib.__import__ "importlib.__import__"). The most important difference between these two functions is that [`import_module()`](#importlib.import_module "importlib.import_module") returns the specified package or module (e.g. `pkg.mod`), while [`__import__()`](functions#__import__ "__import__") returns the top-level package or module (e.g. `pkg`). If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call [`invalidate_caches()`](#importlib.invalidate_caches "importlib.invalidate_caches") in order for the new module to be noticed by the import system. Changed in version 3.3: Parent packages are automatically imported. `importlib.find_loader(name, path=None)` Find the loader for a module, optionally within the specified *path*. If the module is in [`sys.modules`](sys#sys.modules "sys.modules"), then `sys.modules[name].__loader__` is returned (unless the loader would be `None` or is not set, in which case [`ValueError`](exceptions#ValueError "ValueError") is raised). Otherwise a search using [`sys.meta_path`](sys#sys.meta_path "sys.meta_path") is done. `None` is returned if no loader is found. A dotted name does not have its parents implicitly imported as that requires loading them and that may not be desired. To properly import a submodule you will need to import all parent packages of the submodule and use the correct argument to *path*. New in version 3.3. Changed in version 3.4: If `__loader__` is not set, raise [`ValueError`](exceptions#ValueError "ValueError"), just like when the attribute is set to `None`. Deprecated since version 3.4: Use [`importlib.util.find_spec()`](#importlib.util.find_spec "importlib.util.find_spec") instead. `importlib.invalidate_caches()` Invalidate the internal caches of finders stored at [`sys.meta_path`](sys#sys.meta_path "sys.meta_path"). If a finder implements `invalidate_caches()` then it will be called to perform the invalidation. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence. New in version 3.3. `importlib.reload(module)` Reload a previously imported *module*. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in [`sys.modules`](sys#sys.modules "sys.modules")). When [`reload()`](#importlib.reload "importlib.reload") is executed: * Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the [loader](../glossary#term-loader) which originally loaded the module. The `init` function of extension modules is not called a second time. * As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. * The names in the module namespace are updated to point to any new or changed objects. * Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired. There are a number of other caveats: When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a [`try`](../reference/compound_stmts#try) statement it can test for the table’s presence and skip its initialization if desired: ``` try: cache except NameError: cache = {} ``` It is generally not very useful to reload built-in or dynamically loaded modules. Reloading [`sys`](sys#module-sys "sys: Access system-specific parameters and functions."), [`__main__`](__main__#module-__main__ "__main__: The environment where the top-level script is run."), [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") and other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded. If a module imports objects from another module using [`from`](../reference/simple_stmts#from) … [`import`](../reference/simple_stmts#import) …, calling [`reload()`](#importlib.reload "importlib.reload") for the other module does not redefine the objects imported from it — one way around this is to re-execute the `from` statement, another is to use `import` and qualified names (*module.name*) instead. If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes. New in version 3.4. Changed in version 3.7: [`ModuleNotFoundError`](exceptions#ModuleNotFoundError "ModuleNotFoundError") is raised when the module being reloaded lacks a `ModuleSpec`. importlib.abc – Abstract base classes related to import ------------------------------------------------------- **Source code:** [Lib/importlib/abc.py](https://github.com/python/cpython/tree/3.9/Lib/importlib/abc.py) The [`importlib.abc`](#module-importlib.abc "importlib.abc: Abstract base classes related to import") module contains all of the core abstract base classes used by [`import`](../reference/simple_stmts#import). Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs. ABC hierarchy: ``` object +-- Finder (deprecated) | +-- MetaPathFinder | +-- PathEntryFinder +-- Loader +-- ResourceLoader --------+ +-- InspectLoader | +-- ExecutionLoader --+ +-- FileLoader +-- SourceLoader ``` `class importlib.abc.Finder` An abstract base class representing a [finder](../glossary#term-finder). Deprecated since version 3.3: Use [`MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") or [`PathEntryFinder`](#importlib.abc.PathEntryFinder "importlib.abc.PathEntryFinder") instead. `abstractmethod find_module(fullname, path=None)` An abstract method for finding a [loader](../glossary#term-loader) for the specified module. Originally specified in [**PEP 302**](https://www.python.org/dev/peps/pep-0302), this method was meant for use in [`sys.meta_path`](sys#sys.meta_path "sys.meta_path") and in the path-based import subsystem. Changed in version 3.4: Returns `None` when called instead of raising [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `class importlib.abc.MetaPathFinder` An abstract base class representing a [meta path finder](../glossary#term-meta-path-finder). For compatibility, this is a subclass of [`Finder`](#importlib.abc.Finder "importlib.abc.Finder"). New in version 3.3. `find_spec(fullname, path, target=None)` An abstract method for finding a [spec](../glossary#term-module-spec) for the specified module. If this is a top-level import, *path* will be `None`. Otherwise, this is a search for a subpackage or module and *path* will be the value of [`__path__`](../reference/import#__path__ "__path__") from the parent package. If a spec cannot be found, `None` is returned. When passed in, `target` is a module object that the finder may use to make a more educated guess about what spec to return. [`importlib.util.spec_from_loader()`](#importlib.util.spec_from_loader "importlib.util.spec_from_loader") may be useful for implementing concrete `MetaPathFinders`. New in version 3.4. `find_module(fullname, path)` A legacy method for finding a [loader](../glossary#term-loader) for the specified module. If this is a top-level import, *path* will be `None`. Otherwise, this is a search for a subpackage or module and *path* will be the value of [`__path__`](../reference/import#__path__ "__path__") from the parent package. If a loader cannot be found, `None` is returned. If [`find_spec()`](#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") is defined, backwards-compatible functionality is provided. Changed in version 3.4: Returns `None` when called instead of raising [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). Can use [`find_spec()`](#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") to provide functionality. Deprecated since version 3.4: Use [`find_spec()`](#importlib.abc.MetaPathFinder.find_spec "importlib.abc.MetaPathFinder.find_spec") instead. `invalidate_caches()` An optional method which, when called, should invalidate any internal cache used by the finder. Used by [`importlib.invalidate_caches()`](#importlib.invalidate_caches "importlib.invalidate_caches") when invalidating the caches of all finders on [`sys.meta_path`](sys#sys.meta_path "sys.meta_path"). Changed in version 3.4: Returns `None` when called instead of `NotImplemented`. `class importlib.abc.PathEntryFinder` An abstract base class representing a [path entry finder](../glossary#term-path-entry-finder). Though it bears some similarities to [`MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder"), `PathEntryFinder` is meant for use only within the path-based import subsystem provided by `PathFinder`. This ABC is a subclass of [`Finder`](#importlib.abc.Finder "importlib.abc.Finder") for compatibility reasons only. New in version 3.3. `find_spec(fullname, target=None)` An abstract method for finding a [spec](../glossary#term-module-spec) for the specified module. The finder will search for the module only within the [path entry](../glossary#term-path-entry) to which it is assigned. If a spec cannot be found, `None` is returned. When passed in, `target` is a module object that the finder may use to make a more educated guess about what spec to return. [`importlib.util.spec_from_loader()`](#importlib.util.spec_from_loader "importlib.util.spec_from_loader") may be useful for implementing concrete `PathEntryFinders`. New in version 3.4. `find_loader(fullname)` A legacy method for finding a [loader](../glossary#term-loader) for the specified module. Returns a 2-tuple of `(loader, portion)` where `portion` is a sequence of file system locations contributing to part of a namespace package. The loader may be `None` while specifying `portion` to signify the contribution of the file system locations to a namespace package. An empty list can be used for `portion` to signify the loader is not part of a namespace package. If `loader` is `None` and `portion` is the empty list then no loader or location for a namespace package were found (i.e. failure to find anything for the module). If [`find_spec()`](#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") is defined then backwards-compatible functionality is provided. Changed in version 3.4: Returns `(None, [])` instead of raising [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). Uses [`find_spec()`](#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") when available to provide functionality. Deprecated since version 3.4: Use [`find_spec()`](#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") instead. `find_module(fullname)` A concrete implementation of [`Finder.find_module()`](#importlib.abc.Finder.find_module "importlib.abc.Finder.find_module") which is equivalent to `self.find_loader(fullname)[0]`. Deprecated since version 3.4: Use [`find_spec()`](#importlib.abc.PathEntryFinder.find_spec "importlib.abc.PathEntryFinder.find_spec") instead. `invalidate_caches()` An optional method which, when called, should invalidate any internal cache used by the finder. Used by `PathFinder.invalidate_caches()` when invalidating the caches of all cached finders. `class importlib.abc.Loader` An abstract base class for a [loader](../glossary#term-loader). See [**PEP 302**](https://www.python.org/dev/peps/pep-0302) for the exact definition for a loader. Loaders that wish to support resource reading should implement a `get_resource_reader(fullname)` method as specified by [`importlib.abc.ResourceReader`](#importlib.abc.ResourceReader "importlib.abc.ResourceReader"). Changed in version 3.7: Introduced the optional `get_resource_reader()` method. `create_module(spec)` A method that returns the module object to use when importing a module. This method may return `None`, indicating that default module creation semantics should take place. New in version 3.4. Changed in version 3.5: Starting in Python 3.6, this method will not be optional when [`exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") is defined. `exec_module(module)` An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when `exec_module()` is called. When this method exists, [`create_module()`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") must be defined. New in version 3.4. Changed in version 3.6: [`create_module()`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") must also be defined. `load_module(fullname)` A legacy method for loading a module. If the module cannot be loaded, [`ImportError`](exceptions#ImportError "ImportError") is raised, otherwise the loaded module is returned. If the requested module already exists in [`sys.modules`](sys#sys.modules "sys.modules"), that module should be used and reloaded. Otherwise the loader should create a new module and insert it into [`sys.modules`](sys#sys.modules "sys.modules") before any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader from [`sys.modules`](sys#sys.modules "sys.modules"); modules already in [`sys.modules`](sys#sys.modules "sys.modules") before the loader began execution should be left alone (see [`importlib.util.module_for_loader()`](#importlib.util.module_for_loader "importlib.util.module_for_loader")). The loader should set several attributes on the module. (Note that some of these attributes can change when a module is reloaded): * [`__name__`](../reference/import#__name__ "__name__") The name of the module. * [`__file__`](../reference/import#__file__ "__file__") The path to where the module data is stored (not set for built-in modules). * [`__cached__`](../reference/import#__cached__ "__cached__") The path to where a compiled version of the module is/should be stored (not set when the attribute would be inappropriate). * [`__path__`](../reference/import#__path__ "__path__") A list of strings specifying the search path within a package. This attribute is not set on modules. * [`__package__`](../reference/import#__package__ "__package__") The fully-qualified name of the package under which the module was loaded as a submodule (or the empty string for top-level modules). For packages, it is the same as [`__name__`](../reference/import#__name__ "__name__"). The [`importlib.util.module_for_loader()`](#importlib.util.module_for_loader "importlib.util.module_for_loader") decorator can handle the details for [`__package__`](../reference/import#__package__ "__package__"). * [`__loader__`](../reference/import#__loader__ "__loader__") The loader used to load the module. The [`importlib.util.module_for_loader()`](#importlib.util.module_for_loader "importlib.util.module_for_loader") decorator can handle the details for [`__package__`](../reference/import#__package__ "__package__"). When [`exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") is available then backwards-compatible functionality is provided. Changed in version 3.4: Raise [`ImportError`](exceptions#ImportError "ImportError") when called instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). Functionality provided when [`exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") is available. Deprecated since version 3.4: The recommended API for loading a module is [`exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") (and [`create_module()`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module")). Loaders should implement it instead of load\_module(). The import machinery takes care of all the other responsibilities of load\_module() when exec\_module() is implemented. `module_repr(module)` A legacy method which when implemented calculates and returns the given module’s repr, as a string. The module type’s default repr() will use the result of this method as appropriate. New in version 3.3. Changed in version 3.4: Made optional instead of an abstractmethod. Deprecated since version 3.4: The import machinery now takes care of this automatically. `class importlib.abc.ResourceReader` *Superseded by TraversableResources* An [abstract base class](../glossary#term-abstract-base-class) to provide the ability to read *resources*. From the perspective of this ABC, a *resource* is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the `__init__.py` file of the package. The purpose of this class is to help abstract out the accessing of such data files so that it does not matter if the package and its data file(s) are stored in a e.g. zip file versus on the file system. For any of methods of this class, a *resource* argument is expected to be a [path-like object](../glossary#term-path-like-object) which represents conceptually just a file name. This means that no subdirectory paths should be included in the *resource* argument. This is because the location of the package the reader is for, acts as the “directory”. Hence the metaphor for directories and file names is packages and resources, respectively. This is also why instances of this class are expected to directly correlate to a specific package (instead of potentially representing multiple packages or a module). Loaders that wish to support resource reading are expected to provide a method called `get_resource_reader(fullname)` which returns an object implementing this ABC’s interface. If the module specified by fullname is not a package, this method should return [`None`](constants#None "None"). An object compatible with this ABC should only be returned when the specified module is a package. New in version 3.7. `abstractmethod open_resource(resource)` Returns an opened, [file-like object](../glossary#term-file-like-object) for binary reading of the *resource*. If the resource cannot be found, [`FileNotFoundError`](exceptions#FileNotFoundError "FileNotFoundError") is raised. `abstractmethod resource_path(resource)` Returns the file system path to the *resource*. If the resource does not concretely exist on the file system, raise [`FileNotFoundError`](exceptions#FileNotFoundError "FileNotFoundError"). `abstractmethod is_resource(name)` Returns `True` if the named *name* is considered a resource. [`FileNotFoundError`](exceptions#FileNotFoundError "FileNotFoundError") is raised if *name* does not exist. `abstractmethod contents()` Returns an [iterable](../glossary#term-iterable) of strings over the contents of the package. Do note that it is not required that all names returned by the iterator be actual resources, e.g. it is acceptable to return names for which [`is_resource()`](#importlib.abc.ResourceReader.is_resource "importlib.abc.ResourceReader.is_resource") would be false. Allowing non-resource names to be returned is to allow for situations where how a package and its resources are stored are known a priori and the non-resource names would be useful. For instance, returning subdirectory names is allowed so that when it is known that the package and resources are stored on the file system then those subdirectory names can be used directly. The abstract method returns an iterable of no items. `class importlib.abc.ResourceLoader` An abstract base class for a [loader](../glossary#term-loader) which implements the optional [**PEP 302**](https://www.python.org/dev/peps/pep-0302) protocol for loading arbitrary resources from the storage back-end. Deprecated since version 3.7: This ABC is deprecated in favour of supporting resource loading through [`importlib.abc.ResourceReader`](#importlib.abc.ResourceReader "importlib.abc.ResourceReader"). `abstractmethod get_data(path)` An abstract method to return the bytes for the data located at *path*. Loaders that have a file-like storage back-end that allows storing arbitrary data can implement this abstract method to give direct access to the data stored. [`OSError`](exceptions#OSError "OSError") is to be raised if the *path* cannot be found. The *path* is expected to be constructed using a module’s [`__file__`](../reference/import#__file__ "__file__") attribute or an item from a package’s [`__path__`](../reference/import#__path__ "__path__"). Changed in version 3.4: Raises [`OSError`](exceptions#OSError "OSError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `class importlib.abc.InspectLoader` An abstract base class for a [loader](../glossary#term-loader) which implements the optional [**PEP 302**](https://www.python.org/dev/peps/pep-0302) protocol for loaders that inspect modules. `get_code(fullname)` Return the code object for a module, or `None` if the module does not have a code object (as would be the case, for example, for a built-in module). Raise an [`ImportError`](exceptions#ImportError "ImportError") if loader cannot find the requested module. Note While the method has a default implementation, it is suggested that it be overridden if possible for performance. Changed in version 3.4: No longer abstract and a concrete implementation is provided. `abstractmethod get_source(fullname)` An abstract method to return the source of a module. It is returned as a text string using [universal newlines](../glossary#term-universal-newlines), translating all recognized line separators into `'\n'` characters. Returns `None` if no source is available (e.g. a built-in module). Raises [`ImportError`](exceptions#ImportError "ImportError") if the loader cannot find the module specified. Changed in version 3.4: Raises [`ImportError`](exceptions#ImportError "ImportError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `is_package(fullname)` An optional method to return a true value if the module is a package, a false value otherwise. [`ImportError`](exceptions#ImportError "ImportError") is raised if the [loader](../glossary#term-loader) cannot find the module. Changed in version 3.4: Raises [`ImportError`](exceptions#ImportError "ImportError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `static source_to_code(data, path='<string>')` Create a code object from Python source. The *data* argument can be whatever the [`compile()`](functions#compile "compile") function supports (i.e. string or bytes). The *path* argument should be the “path” to where the source code originated from, which can be an abstract concept (e.g. location in a zip file). With the subsequent code object one can execute it in a module by running `exec(code, module.__dict__)`. New in version 3.4. Changed in version 3.5: Made the method static. `exec_module(module)` Implementation of [`Loader.exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module"). New in version 3.4. `load_module(fullname)` Implementation of [`Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module"). Deprecated since version 3.4: use [`exec_module()`](#importlib.abc.InspectLoader.exec_module "importlib.abc.InspectLoader.exec_module") instead. `class importlib.abc.ExecutionLoader` An abstract base class which inherits from [`InspectLoader`](#importlib.abc.InspectLoader "importlib.abc.InspectLoader") that, when implemented, helps a module to be executed as a script. The ABC represents an optional [**PEP 302**](https://www.python.org/dev/peps/pep-0302) protocol. `abstractmethod get_filename(fullname)` An abstract method that is to return the value of [`__file__`](../reference/import#__file__ "__file__") for the specified module. If no path is available, [`ImportError`](exceptions#ImportError "ImportError") is raised. If source code is available, then the method should return the path to the source file, regardless of whether a bytecode was used to load the module. Changed in version 3.4: Raises [`ImportError`](exceptions#ImportError "ImportError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `class importlib.abc.FileLoader(fullname, path)` An abstract base class which inherits from [`ResourceLoader`](#importlib.abc.ResourceLoader "importlib.abc.ResourceLoader") and [`ExecutionLoader`](#importlib.abc.ExecutionLoader "importlib.abc.ExecutionLoader"), providing concrete implementations of [`ResourceLoader.get_data()`](#importlib.abc.ResourceLoader.get_data "importlib.abc.ResourceLoader.get_data") and [`ExecutionLoader.get_filename()`](#importlib.abc.ExecutionLoader.get_filename "importlib.abc.ExecutionLoader.get_filename"). The *fullname* argument is a fully resolved name of the module the loader is to handle. The *path* argument is the path to the file for the module. New in version 3.3. `name` The name of the module the loader can handle. `path` Path to the file of the module. `load_module(fullname)` Calls super’s `load_module()`. Deprecated since version 3.4: Use [`Loader.exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") instead. `abstractmethod get_filename(fullname)` Returns [`path`](#importlib.abc.FileLoader.path "importlib.abc.FileLoader.path"). `abstractmethod get_data(path)` Reads *path* as a binary file and returns the bytes from it. `class importlib.abc.SourceLoader` An abstract base class for implementing source (and optionally bytecode) file loading. The class inherits from both [`ResourceLoader`](#importlib.abc.ResourceLoader "importlib.abc.ResourceLoader") and [`ExecutionLoader`](#importlib.abc.ExecutionLoader "importlib.abc.ExecutionLoader"), requiring the implementation of: * [`ResourceLoader.get_data()`](#importlib.abc.ResourceLoader.get_data "importlib.abc.ResourceLoader.get_data") * [`ExecutionLoader.get_filename()`](#importlib.abc.ExecutionLoader.get_filename "importlib.abc.ExecutionLoader.get_filename") Should only return the path to the source file; sourceless loading is not supported. The abstract methods defined by this class are to add optional bytecode file support. Not implementing these optional methods (or causing them to raise [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError")) causes the loader to only work with source code. Implementing the methods allows the loader to work with source *and* bytecode files; it does not allow for *sourceless* loading where only bytecode is provided. Bytecode files are an optimization to speed up loading by removing the parsing step of Python’s compiler, and so no bytecode-specific API is exposed. `path_stats(path)` Optional abstract method which returns a [`dict`](stdtypes#dict "dict") containing metadata about the specified path. Supported dictionary keys are: * `'mtime'` (mandatory): an integer or floating-point number representing the modification time of the source code; * `'size'` (optional): the size in bytes of the source code. Any other keys in the dictionary are ignored, to allow for future extensions. If the path cannot be handled, [`OSError`](exceptions#OSError "OSError") is raised. New in version 3.3. Changed in version 3.4: Raise [`OSError`](exceptions#OSError "OSError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `path_mtime(path)` Optional abstract method which returns the modification time for the specified path. Deprecated since version 3.3: This method is deprecated in favour of [`path_stats()`](#importlib.abc.SourceLoader.path_stats "importlib.abc.SourceLoader.path_stats"). You don’t have to implement it, but it is still available for compatibility purposes. Raise [`OSError`](exceptions#OSError "OSError") if the path cannot be handled. Changed in version 3.4: Raise [`OSError`](exceptions#OSError "OSError") instead of [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError"). `set_data(path, data)` Optional abstract method which writes the specified bytes to a file path. Any intermediate directories which do not exist are to be created automatically. When writing to the path fails because the path is read-only ([`errno.EACCES`](errno#errno.EACCES "errno.EACCES")/[`PermissionError`](exceptions#PermissionError "PermissionError")), do not propagate the exception. Changed in version 3.4: No longer raises [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") when called. `get_code(fullname)` Concrete implementation of [`InspectLoader.get_code()`](#importlib.abc.InspectLoader.get_code "importlib.abc.InspectLoader.get_code"). `exec_module(module)` Concrete implementation of [`Loader.exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module"). New in version 3.4. `load_module(fullname)` Concrete implementation of [`Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module"). Deprecated since version 3.4: Use [`exec_module()`](#importlib.abc.SourceLoader.exec_module "importlib.abc.SourceLoader.exec_module") instead. `get_source(fullname)` Concrete implementation of [`InspectLoader.get_source()`](#importlib.abc.InspectLoader.get_source "importlib.abc.InspectLoader.get_source"). `is_package(fullname)` Concrete implementation of [`InspectLoader.is_package()`](#importlib.abc.InspectLoader.is_package "importlib.abc.InspectLoader.is_package"). A module is determined to be a package if its file path (as provided by [`ExecutionLoader.get_filename()`](#importlib.abc.ExecutionLoader.get_filename "importlib.abc.ExecutionLoader.get_filename")) is a file named `__init__` when the file extension is removed **and** the module name itself does not end in `__init__`. `class importlib.abc.Traversable` An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. New in version 3.9. `abstractmethod name()` The base name of this object without any parent references. `abstractmethod iterdir()` Yield Traversable objects in self. `abstractmethod is_dir()` Return True if self is a directory. `abstractmethod is_file()` Return True if self is a file. `abstractmethod joinpath(child)` Return Traversable child in self. `abstractmethod __truediv__(child)` Return Traversable child in self. `abstractmethod open(mode='r', *args, **kwargs)` *mode* may be ‘r’ or ‘rb’ to open as text or binary. Return a handle suitable for reading (same as [`pathlib.Path.open`](pathlib#pathlib.Path.open "pathlib.Path.open")). When opening as text, accepts encoding parameters such as those accepted by [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper"). `read_bytes()` Read contents of self as bytes. `read_text(encoding=None)` Read contents of self as text. `class importlib.abc.TraversableResources` An abstract base class for resource readers capable of serving the `files` interface. Subclasses ResourceReader and provides concrete implementations of the ResourceReader’s abstract methods. Therefore, any loader supplying TraversableReader also supplies ResourceReader. New in version 3.9. importlib.resources – Resources ------------------------------- **Source code:** [Lib/importlib/resources.py](https://github.com/python/cpython/tree/3.9/Lib/importlib/resources.py) New in version 3.7. This module leverages Python’s import system to provide access to *resources* within *packages*. If you can import a package, you can access resources within that package. Resources can be opened or read, in either binary or text mode. Resources are roughly akin to files inside directories, though it’s important to keep in mind that this is just a metaphor. Resources and packages **do not** have to exist as physical files and directories on the file system. Note This module provides functionality similar to [pkg\_resources](https://setuptools.readthedocs.io/en/latest/pkg_resources.html) [Basic Resource Access](http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access) without the performance overhead of that package. This makes reading resources included in packages easier, with more stable and consistent semantics. The standalone backport of this module provides more information on [using importlib.resources](http://importlib-resources.readthedocs.io/en/latest/using.html) and [migrating from pkg\_resources to importlib.resources](http://importlib-resources.readthedocs.io/en/latest/migration.html). Loaders that wish to support resource reading should implement a `get_resource_reader(fullname)` method as specified by [`importlib.abc.ResourceReader`](#importlib.abc.ResourceReader "importlib.abc.ResourceReader"). The following types are defined. `importlib.resources.Package` The `Package` type is defined as `Union[str, ModuleType]`. This means that where the function describes accepting a `Package`, you can pass in either a string or a module. Module objects must have a resolvable `__spec__.submodule_search_locations` that is not `None`. `importlib.resources.Resource` This type describes the resource names passed into the various functions in this package. This is defined as `Union[str, os.PathLike]`. The following functions are available. `importlib.resources.files(package)` Returns an `importlib.resources.abc.Traversable` object representing the resource container for the package (think directory) and its resources (think files). A Traversable may contain other containers (think subdirectories). *package* is either a name or a module object which conforms to the `Package` requirements. New in version 3.9. `importlib.resources.as_file(traversable)` Given a `importlib.resources.abc.Traversable` object representing a file, typically from [`importlib.resources.files()`](#importlib.resources.files "importlib.resources.files"), return a context manager for use in a [`with`](../reference/compound_stmts#with) statement. The context manager provides a [`pathlib.Path`](pathlib#pathlib.Path "pathlib.Path") object. Exiting the context manager cleans up any temporary file created when the resource was extracted from e.g. a zip file. Use `as_file` when the Traversable methods (`read_text`, etc) are insufficient and an actual file on the file system is required. New in version 3.9. `importlib.resources.open_binary(package, resource)` Open for binary reading the *resource* within *package*. *package* is either a name or a module object which conforms to the `Package` requirements. *resource* is the name of the resource to open within *package*; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns a `typing.BinaryIO` instance, a binary I/O stream open for reading. `importlib.resources.open_text(package, resource, encoding='utf-8', errors='strict')` Open for text reading the *resource* within *package*. By default, the resource is opened for reading as UTF-8. *package* is either a name or a module object which conforms to the `Package` requirements. *resource* is the name of the resource to open within *package*; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). *encoding* and *errors* have the same meaning as with built-in [`open()`](functions#open "open"). This function returns a `typing.TextIO` instance, a text I/O stream open for reading. `importlib.resources.read_binary(package, resource)` Read and return the contents of the *resource* within *package* as `bytes`. *package* is either a name or a module object which conforms to the `Package` requirements. *resource* is the name of the resource to open within *package*; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns the contents of the resource as [`bytes`](stdtypes#bytes "bytes"). `importlib.resources.read_text(package, resource, encoding='utf-8', errors='strict')` Read and return the contents of *resource* within *package* as a `str`. By default, the contents are read as strict UTF-8. *package* is either a name or a module object which conforms to the `Package` requirements. *resource* is the name of the resource to open within *package*; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). *encoding* and *errors* have the same meaning as with built-in [`open()`](functions#open "open"). This function returns the contents of the resource as [`str`](stdtypes#str "str"). `importlib.resources.path(package, resource)` Return the path to the *resource* as an actual file system path. This function returns a context manager for use in a [`with`](../reference/compound_stmts#with) statement. The context manager provides a [`pathlib.Path`](pathlib#pathlib.Path "pathlib.Path") object. Exiting the context manager cleans up any temporary file created when the resource needs to be extracted from e.g. a zip file. *package* is either a name or a module object which conforms to the `Package` requirements. *resource* is the name of the resource to open within *package*; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). `importlib.resources.is_resource(package, name)` Return `True` if there is a resource named *name* in the package, otherwise `False`. Remember that directories are *not* resources! *package* is either a name or a module object which conforms to the `Package` requirements. `importlib.resources.contents(package)` Return an iterable over the named items within the package. The iterable returns [`str`](stdtypes#str "str") resources (e.g. files) and non-resources (e.g. directories). The iterable does not recurse into subdirectories. *package* is either a name or a module object which conforms to the `Package` requirements. importlib.machinery – Importers and path hooks ---------------------------------------------- **Source code:** [Lib/importlib/machinery.py](https://github.com/python/cpython/tree/3.9/Lib/importlib/machinery.py) This module contains the various objects that help [`import`](../reference/simple_stmts#import) find and load modules. `importlib.machinery.SOURCE_SUFFIXES` A list of strings representing the recognized file suffixes for source modules. New in version 3.3. `importlib.machinery.DEBUG_BYTECODE_SUFFIXES` A list of strings representing the file suffixes for non-optimized bytecode modules. New in version 3.3. Deprecated since version 3.5: Use [`BYTECODE_SUFFIXES`](#importlib.machinery.BYTECODE_SUFFIXES "importlib.machinery.BYTECODE_SUFFIXES") instead. `importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES` A list of strings representing the file suffixes for optimized bytecode modules. New in version 3.3. Deprecated since version 3.5: Use [`BYTECODE_SUFFIXES`](#importlib.machinery.BYTECODE_SUFFIXES "importlib.machinery.BYTECODE_SUFFIXES") instead. `importlib.machinery.BYTECODE_SUFFIXES` A list of strings representing the recognized file suffixes for bytecode modules (including the leading dot). New in version 3.3. Changed in version 3.5: The value is no longer dependent on `__debug__`. `importlib.machinery.EXTENSION_SUFFIXES` A list of strings representing the recognized file suffixes for extension modules. New in version 3.3. `importlib.machinery.all_suffixes()` Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any details on the kind of module (for example, [`inspect.getmodulename()`](inspect#inspect.getmodulename "inspect.getmodulename")). New in version 3.3. `class importlib.machinery.BuiltinImporter` An [importer](../glossary#term-importer) for built-in modules. All known built-in modules are listed in [`sys.builtin_module_names`](sys#sys.builtin_module_names "sys.builtin_module_names"). This class implements the [`importlib.abc.MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") and [`importlib.abc.InspectLoader`](#importlib.abc.InspectLoader "importlib.abc.InspectLoader") ABCs. Only class methods are defined by this class to alleviate the need for instantiation. Changed in version 3.5: As part of [**PEP 489**](https://www.python.org/dev/peps/pep-0489), the builtin importer now implements `Loader.create_module()` and `Loader.exec_module()` `class importlib.machinery.FrozenImporter` An [importer](../glossary#term-importer) for frozen modules. This class implements the [`importlib.abc.MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") and [`importlib.abc.InspectLoader`](#importlib.abc.InspectLoader "importlib.abc.InspectLoader") ABCs. Only class methods are defined by this class to alleviate the need for instantiation. Changed in version 3.4: Gained `create_module()` and `exec_module()` methods. `class importlib.machinery.WindowsRegistryFinder` [Finder](../glossary#term-finder) for modules declared in the Windows registry. This class implements the [`importlib.abc.MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") ABC. Only class methods are defined by this class to alleviate the need for instantiation. New in version 3.3. Deprecated since version 3.6: Use [`site`](site#module-site "site: Module responsible for site-specific configuration.") configuration instead. Future versions of Python may not enable this finder by default. `class importlib.machinery.PathFinder` A [Finder](../glossary#term-finder) for [`sys.path`](sys#sys.path "sys.path") and package `__path__` attributes. This class implements the [`importlib.abc.MetaPathFinder`](#importlib.abc.MetaPathFinder "importlib.abc.MetaPathFinder") ABC. Only class methods are defined by this class to alleviate the need for instantiation. `classmethod find_spec(fullname, path=None, target=None)` Class method that attempts to find a [spec](../glossary#term-module-spec) for the module specified by *fullname* on [`sys.path`](sys#sys.path "sys.path") or, if defined, on *path*. For each path entry that is searched, [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache") is checked. If a non-false object is found then it is used as the [path entry finder](../glossary#term-path-entry-finder) to look for the module being searched for. If no entry is found in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache"), then [`sys.path_hooks`](sys#sys.path_hooks "sys.path_hooks") is searched for a finder for the path entry and, if found, is stored in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache") along with being queried about the module. If no finder is ever found then `None` is both stored in the cache and returned. New in version 3.4. Changed in version 3.5: If the current working directory – represented by an empty string – is no longer valid then `None` is returned but no value is cached in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache"). `classmethod find_module(fullname, path=None)` A legacy wrapper around [`find_spec()`](#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec"). Deprecated since version 3.4: Use [`find_spec()`](#importlib.machinery.PathFinder.find_spec "importlib.machinery.PathFinder.find_spec") instead. `classmethod invalidate_caches()` Calls [`importlib.abc.PathEntryFinder.invalidate_caches()`](#importlib.abc.PathEntryFinder.invalidate_caches "importlib.abc.PathEntryFinder.invalidate_caches") on all finders stored in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache") that define the method. Otherwise entries in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache") set to `None` are deleted. Changed in version 3.7: Entries of `None` in [`sys.path_importer_cache`](sys#sys.path_importer_cache "sys.path_importer_cache") are deleted. Changed in version 3.4: Calls objects in [`sys.path_hooks`](sys#sys.path_hooks "sys.path_hooks") with the current working directory for `''` (i.e. the empty string). `class importlib.machinery.FileFinder(path, *loader_details)` A concrete implementation of [`importlib.abc.PathEntryFinder`](#importlib.abc.PathEntryFinder "importlib.abc.PathEntryFinder") which caches results from the file system. The *path* argument is the directory for which the finder is in charge of searching. The *loader\_details* argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module’s name and the path to the file found. The finder will cache the directory contents as necessary, making stat calls for each module search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system’s state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure to call [`importlib.invalidate_caches()`](#importlib.invalidate_caches "importlib.invalidate_caches"). New in version 3.3. `path` The path the finder will search in. `find_spec(fullname, target=None)` Attempt to find the spec to handle *fullname* within [`path`](#importlib.machinery.FileFinder.path "importlib.machinery.FileFinder.path"). New in version 3.4. `find_loader(fullname)` Attempt to find the loader to handle *fullname* within [`path`](#importlib.machinery.FileFinder.path "importlib.machinery.FileFinder.path"). `invalidate_caches()` Clear out the internal cache. `classmethod path_hook(*loader_details)` A class method which returns a closure for use on [`sys.path_hooks`](sys#sys.path_hooks "sys.path_hooks"). An instance of [`FileFinder`](#importlib.machinery.FileFinder "importlib.machinery.FileFinder") is returned by the closure using the path argument given to the closure directly and *loader\_details* indirectly. If the argument to the closure is not an existing directory, [`ImportError`](exceptions#ImportError "ImportError") is raised. `class importlib.machinery.SourceFileLoader(fullname, path)` A concrete implementation of [`importlib.abc.SourceLoader`](#importlib.abc.SourceLoader "importlib.abc.SourceLoader") by subclassing [`importlib.abc.FileLoader`](#importlib.abc.FileLoader "importlib.abc.FileLoader") and providing some concrete implementations of other methods. New in version 3.3. `name` The name of the module that this loader will handle. `path` The path to the source file. `is_package(fullname)` Return `True` if [`path`](#importlib.machinery.SourceFileLoader.path "importlib.machinery.SourceFileLoader.path") appears to be for a package. `path_stats(path)` Concrete implementation of [`importlib.abc.SourceLoader.path_stats()`](#importlib.abc.SourceLoader.path_stats "importlib.abc.SourceLoader.path_stats"). `set_data(path, data)` Concrete implementation of [`importlib.abc.SourceLoader.set_data()`](#importlib.abc.SourceLoader.set_data "importlib.abc.SourceLoader.set_data"). `load_module(name=None)` Concrete implementation of [`importlib.abc.Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") where specifying the name of the module to load is optional. Deprecated since version 3.6: Use [`importlib.abc.Loader.exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") instead. `class importlib.machinery.SourcelessFileLoader(fullname, path)` A concrete implementation of [`importlib.abc.FileLoader`](#importlib.abc.FileLoader "importlib.abc.FileLoader") which can import bytecode files (i.e. no source code files exist). Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format. New in version 3.3. `name` The name of the module the loader will handle. `path` The path to the bytecode file. `is_package(fullname)` Determines if the module is a package based on [`path`](#importlib.machinery.SourcelessFileLoader.path "importlib.machinery.SourcelessFileLoader.path"). `get_code(fullname)` Returns the code object for [`name`](#importlib.machinery.SourcelessFileLoader.name "importlib.machinery.SourcelessFileLoader.name") created from [`path`](#importlib.machinery.SourcelessFileLoader.path "importlib.machinery.SourcelessFileLoader.path"). `get_source(fullname)` Returns `None` as bytecode files have no source when this loader is used. `load_module(name=None)` Concrete implementation of [`importlib.abc.Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") where specifying the name of the module to load is optional. Deprecated since version 3.6: Use [`importlib.abc.Loader.exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") instead. `class importlib.machinery.ExtensionFileLoader(fullname, path)` A concrete implementation of [`importlib.abc.ExecutionLoader`](#importlib.abc.ExecutionLoader "importlib.abc.ExecutionLoader") for extension modules. The *fullname* argument specifies the name of the module the loader is to support. The *path* argument is the path to the extension module’s file. New in version 3.3. `name` Name of the module the loader supports. `path` Path to the extension module. `create_module(spec)` Creates the module object from the given specification in accordance with [**PEP 489**](https://www.python.org/dev/peps/pep-0489). New in version 3.5. `exec_module(module)` Initializes the given module object in accordance with [**PEP 489**](https://www.python.org/dev/peps/pep-0489). New in version 3.5. `is_package(fullname)` Returns `True` if the file path points to a package’s `__init__` module based on [`EXTENSION_SUFFIXES`](#importlib.machinery.EXTENSION_SUFFIXES "importlib.machinery.EXTENSION_SUFFIXES"). `get_code(fullname)` Returns `None` as extension modules lack a code object. `get_source(fullname)` Returns `None` as extension modules do not have source code. `get_filename(fullname)` Returns [`path`](#importlib.machinery.ExtensionFileLoader.path "importlib.machinery.ExtensionFileLoader.path"). New in version 3.4. `class importlib.machinery.ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)` A specification for a module’s import-system-related state. This is typically exposed as the module’s `__spec__` attribute. In the descriptions below, the names in parentheses give the corresponding attribute available directly on the module object. E.g. `module.__spec__.origin == module.__file__`. Note however that while the *values* are usually equivalent, they can differ since there is no synchronization between the two objects. Thus it is possible to update the module’s `__path__` at runtime, and this will not be automatically reflected in `__spec__.submodule_search_locations`. New in version 3.4. `name` (`__name__`) A string for the fully-qualified name of the module. `loader` (`__loader__`) The [Loader](../glossary#term-loader) that should be used when loading the module. [Finders](../glossary#term-finder) should always set this. `origin` (`__file__`) Name of the place from which the module is loaded, e.g. “builtin” for built-in modules and the filename for modules loaded from source. Normally “origin” should be set, but it may be `None` (the default) which indicates it is unspecified (e.g. for namespace packages). `submodule_search_locations` (`__path__`) List of strings for where to find submodules, if a package (`None` otherwise). `loader_state` Container of extra module-specific data for use during loading (or `None`). `cached` (`__cached__`) String for where the compiled module should be stored (or `None`). `parent` (`__package__`) (Read-only) The fully-qualified name of the package under which the module should be loaded as a submodule (or the empty string for top-level modules). For packages, it is the same as [`__name__`](../reference/import#__name__ "__name__"). `has_location` Boolean indicating whether or not the module’s “origin” attribute refers to a loadable location. importlib.util – Utility code for importers ------------------------------------------- **Source code:** [Lib/importlib/util.py](https://github.com/python/cpython/tree/3.9/Lib/importlib/util.py) This module contains the various objects that help in the construction of an [importer](../glossary#term-importer). `importlib.util.MAGIC_NUMBER` The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider [`importlib.abc.SourceLoader`](#importlib.abc.SourceLoader "importlib.abc.SourceLoader"). New in version 3.4. `importlib.util.cache_from_source(path, debug_override=None, *, optimization=None)` Return the [**PEP 3147**](https://www.python.org/dev/peps/pep-3147)/[**PEP 488**](https://www.python.org/dev/peps/pep-0488) path to the byte-compiled file associated with the source *path*. For example, if *path* is `/foo/bar/baz.py` the return value would be `/foo/bar/__pycache__/baz.cpython-32.pyc` for Python 3.2. The `cpython-32` string comes from the current magic tag (see `get_tag()`; if `sys.implementation.cache_tag` is not defined then [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") will be raised). The *optimization* parameter is used to specify the optimization level of the bytecode file. An empty string represents no optimization, so `/foo/bar/baz.py` with an *optimization* of `''` will result in a bytecode path of `/foo/bar/__pycache__/baz.cpython-32.pyc`. `None` causes the interpreter’s optimization level to be used. Any other value’s string representation is used, so `/foo/bar/baz.py` with an *optimization* of `2` will lead to the bytecode path of `/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc`. The string representation of *optimization* can only be alphanumeric, else [`ValueError`](exceptions#ValueError "ValueError") is raised. The *debug\_override* parameter is deprecated and can be used to override the system’s value for `__debug__`. A `True` value is the equivalent of setting *optimization* to the empty string. A `False` value is the same as setting *optimization* to `1`. If both *debug\_override* an *optimization* are not `None` then [`TypeError`](exceptions#TypeError "TypeError") is raised. New in version 3.4. Changed in version 3.5: The *optimization* parameter was added and the *debug\_override* parameter was deprecated. Changed in version 3.6: Accepts a [path-like object](../glossary#term-path-like-object). `importlib.util.source_from_cache(path)` Given the *path* to a [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) file name, return the associated source code file path. For example, if *path* is `/foo/bar/__pycache__/baz.cpython-32.pyc` the returned path would be `/foo/bar/baz.py`. *path* need not exist, however if it does not conform to [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) or [**PEP 488**](https://www.python.org/dev/peps/pep-0488) format, a [`ValueError`](exceptions#ValueError "ValueError") is raised. If `sys.implementation.cache_tag` is not defined, [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") is raised. New in version 3.4. Changed in version 3.6: Accepts a [path-like object](../glossary#term-path-like-object). `importlib.util.decode_source(source_bytes)` Decode the given bytes representing source code and return it as a string with universal newlines (as required by [`importlib.abc.InspectLoader.get_source()`](#importlib.abc.InspectLoader.get_source "importlib.abc.InspectLoader.get_source")). New in version 3.4. `importlib.util.resolve_name(name, package)` Resolve a relative module name to an absolute one. If **name** has no leading dots, then **name** is simply returned. This allows for usage such as `importlib.util.resolve_name('sys', __spec__.parent)` without doing a check to see if the **package** argument is needed. [`ImportError`](exceptions#ImportError "ImportError") is raised if **name** is a relative module name but **package** is a false value (e.g. `None` or the empty string). [`ImportError`](exceptions#ImportError "ImportError") is also raised a relative name would escape its containing package (e.g. requesting `..bacon` from within the `spam` package). New in version 3.3. Changed in version 3.9: To improve consistency with import statements, raise [`ImportError`](exceptions#ImportError "ImportError") instead of [`ValueError`](exceptions#ValueError "ValueError") for invalid relative import attempts. `importlib.util.find_spec(name, package=None)` Find the [spec](../glossary#term-module-spec) for a module, optionally relative to the specified **package** name. If the module is in [`sys.modules`](sys#sys.modules "sys.modules"), then `sys.modules[name].__spec__` is returned (unless the spec would be `None` or is not set, in which case [`ValueError`](exceptions#ValueError "ValueError") is raised). Otherwise a search using [`sys.meta_path`](sys#sys.meta_path "sys.meta_path") is done. `None` is returned if no spec is found. If **name** is for a submodule (contains a dot), the parent module is automatically imported. **name** and **package** work the same as for `import_module()`. New in version 3.4. Changed in version 3.7: Raises [`ModuleNotFoundError`](exceptions#ModuleNotFoundError "ModuleNotFoundError") instead of [`AttributeError`](exceptions#AttributeError "AttributeError") if **package** is in fact not a package (i.e. lacks a [`__path__`](../reference/import#__path__ "__path__") attribute). `importlib.util.module_from_spec(spec)` Create a new module based on **spec** and [`spec.loader.create_module`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module"). If [`spec.loader.create_module`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") does not return `None`, then any pre-existing attributes will not be reset. Also, no [`AttributeError`](exceptions#AttributeError "AttributeError") will be raised if triggered while accessing **spec** or setting an attribute on the module. This function is preferred over using [`types.ModuleType`](types#types.ModuleType "types.ModuleType") to create a new module as **spec** is used to set as many import-controlled attributes on the module as possible. New in version 3.5. `@importlib.util.module_for_loader` A [decorator](../glossary#term-decorator) for [`importlib.abc.Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") to handle selecting the proper module object to load with. The decorated method is expected to have a call signature taking two positional arguments (e.g. `load_module(self, module)`) for which the second argument will be the module **object** to be used by the loader. Note that the decorator will not work on static methods because of the assumption of two arguments. The decorated method will take in the **name** of the module to be loaded as expected for a [loader](../glossary#term-loader). If the module is not found in [`sys.modules`](sys#sys.modules "sys.modules") then a new one is constructed. Regardless of where the module came from, [`__loader__`](../reference/import#__loader__ "__loader__") set to **self** and [`__package__`](../reference/import#__package__ "__package__") is set based on what [`importlib.abc.InspectLoader.is_package()`](#importlib.abc.InspectLoader.is_package "importlib.abc.InspectLoader.is_package") returns (if available). These attributes are set unconditionally to support reloading. If an exception is raised by the decorated method and a module was added to [`sys.modules`](sys#sys.modules "sys.modules"), then the module will be removed to prevent a partially initialized module from being in left in [`sys.modules`](sys#sys.modules "sys.modules"). If the module was already in [`sys.modules`](sys#sys.modules "sys.modules") then it is left alone. Changed in version 3.3: [`__loader__`](../reference/import#__loader__ "__loader__") and [`__package__`](../reference/import#__package__ "__package__") are automatically set (when possible). Changed in version 3.4: Set [`__name__`](../reference/import#__name__ "__name__"), [`__loader__`](../reference/import#__loader__ "__loader__") [`__package__`](../reference/import#__package__ "__package__") unconditionally to support reloading. Deprecated since version 3.4: The import machinery now directly performs all the functionality provided by this function. `@importlib.util.set_loader` A [decorator](../glossary#term-decorator) for [`importlib.abc.Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") to set the [`__loader__`](../reference/import#__loader__ "__loader__") attribute on the returned module. If the attribute is already set the decorator does nothing. It is assumed that the first positional argument to the wrapped method (i.e. `self`) is what [`__loader__`](../reference/import#__loader__ "__loader__") should be set to. Changed in version 3.4: Set `__loader__` if set to `None`, as if the attribute does not exist. Deprecated since version 3.4: The import machinery takes care of this automatically. `@importlib.util.set_package` A [decorator](../glossary#term-decorator) for [`importlib.abc.Loader.load_module()`](#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") to set the [`__package__`](../reference/import#__package__ "__package__") attribute on the returned module. If [`__package__`](../reference/import#__package__ "__package__") is set and has a value other than `None` it will not be changed. Deprecated since version 3.4: The import machinery takes care of this automatically. `importlib.util.spec_from_loader(name, loader, *, origin=None, is_package=None)` A factory function for creating a `ModuleSpec` instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available [loader](../glossary#term-loader) APIs, such as `InspectLoader.is_package()`, to fill in any missing information on the spec. New in version 3.4. `importlib.util.spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)` A factory function for creating a `ModuleSpec` instance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based. New in version 3.4. Changed in version 3.6: Accepts a [path-like object](../glossary#term-path-like-object). `importlib.util.source_hash(source_bytes)` Return the hash of *source\_bytes* as bytes. A hash-based `.pyc` file embeds the [`source_hash()`](#importlib.util.source_hash "importlib.util.source_hash") of the corresponding source file’s contents in its header. New in version 3.7. `class importlib.util.LazyLoader(loader)` A class which postpones the execution of the loader of a module until the module has an attribute accessed. This class **only** works with loaders that define [`exec_module()`](#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") as control over what module type is used for the module is required. For those same reasons, the loader’s [`create_module()`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") method must return `None` or a type for which its `__class__` attribute can be mutated along with not using [slots](../glossary#term-slots). Finally, modules which substitute the object placed into [`sys.modules`](sys#sys.modules "sys.modules") will not work as there is no way to properly replace the module references throughout the interpreter safely; [`ValueError`](exceptions#ValueError "ValueError") is raised if such a substitution is detected. Note For projects where startup time is critical, this class allows for potentially minimizing the cost of loading a module if it is never used. For projects where startup time is not essential then use of this class is **heavily** discouraged due to error messages created during loading being postponed and thus occurring out of context. New in version 3.5. Changed in version 3.6: Began calling [`create_module()`](#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module"), removing the compatibility warning for [`importlib.machinery.BuiltinImporter`](#importlib.machinery.BuiltinImporter "importlib.machinery.BuiltinImporter") and [`importlib.machinery.ExtensionFileLoader`](#importlib.machinery.ExtensionFileLoader "importlib.machinery.ExtensionFileLoader"). `classmethod factory(loader)` A static method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance. ``` suffixes = importlib.machinery.SOURCE_SUFFIXES loader = importlib.machinery.SourceFileLoader lazy_loader = importlib.util.LazyLoader.factory(loader) finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes)) ``` Examples -------- ### Importing programmatically To programmatically import a module, use [`importlib.import_module()`](#importlib.import_module "importlib.import_module"). ``` import importlib itertools = importlib.import_module('itertools') ``` ### Checking if a module can be imported If you need to find out if a module can be imported without actually doing the import, then you should use [`importlib.util.find_spec()`](#importlib.util.find_spec "importlib.util.find_spec"). ``` import importlib.util import sys # For illustrative purposes. name = 'itertools' if name in sys.modules: print(f"{name!r} already in sys.modules") elif (spec := importlib.util.find_spec(name)) is not None: # If you chose to perform the actual import ... module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) print(f"{name!r} has been imported") else: print(f"can't find the {name!r} module") ``` ### Importing a source file directly To import a Python source file directly, use the following recipe (Python 3.5 and newer only): ``` import importlib.util import sys # For illustrative purposes. import tokenize file_path = tokenize.__file__ module_name = tokenize.__name__ spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) ``` ### Setting up an importer For deep customizations of import, you typically want to implement an [importer](../glossary#term-importer). This means managing both the [finder](../glossary#term-finder) and [loader](../glossary#term-loader) side of things. For finders there are two flavours to choose from depending on your needs: a [meta path finder](../glossary#term-meta-path-finder) or a [path entry finder](../glossary#term-path-entry-finder). The former is what you would put on [`sys.meta_path`](sys#sys.meta_path "sys.meta_path") while the latter is what you create using a [path entry hook](../glossary#term-path-entry-hook) on [`sys.path_hooks`](sys#sys.path_hooks "sys.path_hooks") which works with [`sys.path`](sys#sys.path "sys.path") entries to potentially create a finder. This example will show you how to register your own importers so that import will use them (for creating an importer for yourself, read the documentation for the appropriate classes defined within this package): ``` import importlib.machinery import sys # For illustrative purposes only. SpamMetaPathFinder = importlib.machinery.PathFinder SpamPathEntryFinder = importlib.machinery.FileFinder loader_details = (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES) # Setting up a meta path finder. # Make sure to put the finder in the proper location in the list in terms of # priority. sys.meta_path.append(SpamMetaPathFinder) # Setting up a path entry finder. # Make sure to put the path hook in the proper location in the list in terms # of priority. sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details)) ``` ### Approximating [`importlib.import_module()`](#importlib.import_module "importlib.import_module") Import itself is implemented in Python code, making it possible to expose most of the import machinery through importlib. The following helps illustrate the various APIs that importlib exposes by providing an approximate implementation of [`importlib.import_module()`](#importlib.import_module "importlib.import_module") (Python 3.4 and newer for the importlib usage, Python 3.6 and newer for other parts of the code). ``` import importlib.util import sys def import_module(name, package=None): """An approximate implementation of import.""" absolute_name = importlib.util.resolve_name(name, package) try: return sys.modules[absolute_name] except KeyError: pass path = None if '.' in absolute_name: parent_name, _, child_name = absolute_name.rpartition('.') parent_module = import_module(parent_name) path = parent_module.__spec__.submodule_search_locations for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: break else: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) module = importlib.util.module_from_spec(spec) sys.modules[absolute_name] = module spec.loader.exec_module(module) if path is not None: setattr(parent_module, child_name, module) return module ```
programming_docs
python Policies Policies ======== An event loop policy is a global per-process object that controls the management of the event loop. Each event loop has a default policy, which can be changed and customized using the policy API. A policy defines the notion of *context* and manages a separate event loop per context. The default policy defines *context* to be the current thread. By using a custom event loop policy, the behavior of [`get_event_loop()`](asyncio-eventloop#asyncio.get_event_loop "asyncio.get_event_loop"), [`set_event_loop()`](asyncio-eventloop#asyncio.set_event_loop "asyncio.set_event_loop"), and [`new_event_loop()`](asyncio-eventloop#asyncio.new_event_loop "asyncio.new_event_loop") functions can be customized. Policy objects should implement the APIs defined in the [`AbstractEventLoopPolicy`](#asyncio.AbstractEventLoopPolicy "asyncio.AbstractEventLoopPolicy") abstract base class. Getting and Setting the Policy ------------------------------ The following functions can be used to get and set the policy for the current process: `asyncio.get_event_loop_policy()` Return the current process-wide policy. `asyncio.set_event_loop_policy(policy)` Set the current process-wide policy to *policy*. If *policy* is set to `None`, the default policy is restored. Policy Objects -------------- The abstract event loop policy base class is defined as follows: `class asyncio.AbstractEventLoopPolicy` An abstract base class for asyncio policies. `get_event_loop()` Get the event loop for the current context. Return an event loop object implementing the [`AbstractEventLoop`](asyncio-eventloop#asyncio.AbstractEventLoop "asyncio.AbstractEventLoop") interface. This method should never return `None`. Changed in version 3.6. `set_event_loop(loop)` Set the event loop for the current context to *loop*. `new_event_loop()` Create and return a new event loop object. This method should never return `None`. `get_child_watcher()` Get a child process watcher object. Return a watcher object implementing the [`AbstractChildWatcher`](#asyncio.AbstractChildWatcher "asyncio.AbstractChildWatcher") interface. This function is Unix specific. `set_child_watcher(watcher)` Set the current child process watcher to *watcher*. This function is Unix specific. asyncio ships with the following built-in policies: `class asyncio.DefaultEventLoopPolicy` The default asyncio policy. Uses [`SelectorEventLoop`](asyncio-eventloop#asyncio.SelectorEventLoop "asyncio.SelectorEventLoop") on Unix and [`ProactorEventLoop`](asyncio-eventloop#asyncio.ProactorEventLoop "asyncio.ProactorEventLoop") on Windows. There is no need to install the default policy manually. asyncio is configured to use the default policy automatically. Changed in version 3.8: On Windows, [`ProactorEventLoop`](asyncio-eventloop#asyncio.ProactorEventLoop "asyncio.ProactorEventLoop") is now used by default. `class asyncio.WindowsSelectorEventLoopPolicy` An alternative event loop policy that uses the [`SelectorEventLoop`](asyncio-eventloop#asyncio.SelectorEventLoop "asyncio.SelectorEventLoop") event loop implementation. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. `class asyncio.WindowsProactorEventLoopPolicy` An alternative event loop policy that uses the [`ProactorEventLoop`](asyncio-eventloop#asyncio.ProactorEventLoop "asyncio.ProactorEventLoop") event loop implementation. [Availability](https://docs.python.org/3.9/library/intro.html#availability): Windows. Process Watchers ---------------- A process watcher allows customization of how an event loop monitors child processes on Unix. Specifically, the event loop needs to know when a child process has exited. In asyncio, child processes are created with [`create_subprocess_exec()`](asyncio-subprocess#asyncio.create_subprocess_exec "asyncio.create_subprocess_exec") and [`loop.subprocess_exec()`](asyncio-eventloop#asyncio.loop.subprocess_exec "asyncio.loop.subprocess_exec") functions. asyncio defines the [`AbstractChildWatcher`](#asyncio.AbstractChildWatcher "asyncio.AbstractChildWatcher") abstract base class, which child watchers should implement, and has four different implementations: [`ThreadedChildWatcher`](#asyncio.ThreadedChildWatcher "asyncio.ThreadedChildWatcher") (configured to be used by default), [`MultiLoopChildWatcher`](#asyncio.MultiLoopChildWatcher "asyncio.MultiLoopChildWatcher"), [`SafeChildWatcher`](#asyncio.SafeChildWatcher "asyncio.SafeChildWatcher"), and [`FastChildWatcher`](#asyncio.FastChildWatcher "asyncio.FastChildWatcher"). See also the [Subprocess and Threads](asyncio-subprocess#asyncio-subprocess-threads) section. The following two functions can be used to customize the child process watcher implementation used by the asyncio event loop: `asyncio.get_child_watcher()` Return the current child watcher for the current policy. `asyncio.set_child_watcher(watcher)` Set the current child watcher to *watcher* for the current policy. *watcher* must implement methods defined in the [`AbstractChildWatcher`](#asyncio.AbstractChildWatcher "asyncio.AbstractChildWatcher") base class. Note Third-party event loops implementations might not support custom child watchers. For such event loops, using [`set_child_watcher()`](#asyncio.set_child_watcher "asyncio.set_child_watcher") might be prohibited or have no effect. `class asyncio.AbstractChildWatcher` `add_child_handler(pid, callback, *args)` Register a new child handler. Arrange for `callback(pid, returncode, *args)` to be called when a process with PID equal to *pid* terminates. Specifying another callback for the same process replaces the previous handler. The *callback* callable must be thread-safe. `remove_child_handler(pid)` Removes the handler for process with PID equal to *pid*. The function returns `True` if the handler was successfully removed, `False` if there was nothing to remove. `attach_loop(loop)` Attach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. Note: loop may be `None`. `is_active()` Return `True` if the watcher is ready to use. Spawning a subprocess with *inactive* current child watcher raises [`RuntimeError`](exceptions#RuntimeError "RuntimeError"). New in version 3.8. `close()` Close the watcher. This method has to be called to ensure that underlying resources are cleaned-up. `class asyncio.ThreadedChildWatcher` This implementation starts a new waiting thread for every subprocess spawn. It works reliably even when the asyncio event loop is run in a non-main OS thread. There is no noticeable overhead when handling a big number of children (*O(1)* each time a child terminates), but starting a thread per process requires extra memory. This watcher is used by default. New in version 3.8. `class asyncio.MultiLoopChildWatcher` This implementation registers a `SIGCHLD` signal handler on instantiation. That can break third-party code that installs a custom handler for `SIGCHLD` signal. The watcher avoids disrupting other code spawning processes by polling every process explicitly on a `SIGCHLD` signal. There is no limitation for running subprocesses from different threads once the watcher is installed. The solution is safe but it has a significant overhead when handling a big number of processes (*O(n)* each time a `SIGCHLD` is received). New in version 3.8. `class asyncio.SafeChildWatcher` This implementation uses active event loop from the main thread to handle `SIGCHLD` signal. If the main thread has no running event loop another thread cannot spawn a subprocess ([`RuntimeError`](exceptions#RuntimeError "RuntimeError") is raised). The watcher avoids disrupting other code spawning processes by polling every process explicitly on a `SIGCHLD` signal. This solution is as safe as [`MultiLoopChildWatcher`](#asyncio.MultiLoopChildWatcher "asyncio.MultiLoopChildWatcher") and has the same *O(N)* complexity but requires a running event loop in the main thread to work. `class asyncio.FastChildWatcher` This implementation reaps every terminated processes by calling `os.waitpid(-1)` directly, possibly breaking other code spawning processes and waiting for their termination. There is no noticeable overhead when handling a big number of children (*O(1)* each time a child terminates). This solution requires a running event loop in the main thread to work, as [`SafeChildWatcher`](#asyncio.SafeChildWatcher "asyncio.SafeChildWatcher"). `class asyncio.PidfdChildWatcher` This implementation polls process file descriptors (pidfds) to await child process termination. In some respects, [`PidfdChildWatcher`](#asyncio.PidfdChildWatcher "asyncio.PidfdChildWatcher") is a “Goldilocks” child watcher implementation. It doesn’t require signals or threads, doesn’t interfere with any processes launched outside the event loop, and scales linearly with the number of subprocesses launched by the event loop. The main disadvantage is that pidfds are specific to Linux, and only work on recent (5.3+) kernels. New in version 3.9. Custom Policies --------------- To implement a new event loop policy, it is recommended to subclass [`DefaultEventLoopPolicy`](#asyncio.DefaultEventLoopPolicy "asyncio.DefaultEventLoopPolicy") and override the methods for which custom behavior is wanted, e.g.: ``` class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): """Get the event loop. This may be None or an instance of EventLoop. """ loop = super().get_event_loop() # Do something with loop ... return loop asyncio.set_event_loop_policy(MyEventLoopPolicy()) ``` python Text Processing Services Text Processing Services ======================== The modules described in this chapter provide a wide range of string manipulation operations and other text processing services. The [`codecs`](codecs#module-codecs "codecs: Encode and decode data and streams.") module described under [Binary Data Services](binary#binaryservices) is also highly relevant to text processing. In addition, see the documentation for Python’s built-in string type in [Text Sequence Type — str](stdtypes#textseq). * [`string` — Common string operations](string) + [String constants](string#string-constants) + [Custom String Formatting](string#custom-string-formatting) + [Format String Syntax](string#format-string-syntax) - [Format Specification Mini-Language](string#format-specification-mini-language) - [Format examples](string#format-examples) + [Template strings](string#template-strings) + [Helper functions](string#helper-functions) * [`re` — Regular expression operations](re) + [Regular Expression Syntax](re#regular-expression-syntax) + [Module Contents](re#module-contents) + [Regular Expression Objects](re#regular-expression-objects) + [Match Objects](re#match-objects) + [Regular Expression Examples](re#regular-expression-examples) - [Checking for a Pair](re#checking-for-a-pair) - [Simulating scanf()](re#simulating-scanf) - [search() vs. match()](re#search-vs-match) - [Making a Phonebook](re#making-a-phonebook) - [Text Munging](re#text-munging) - [Finding all Adverbs](re#finding-all-adverbs) - [Finding all Adverbs and their Positions](re#finding-all-adverbs-and-their-positions) - [Raw String Notation](re#raw-string-notation) - [Writing a Tokenizer](re#writing-a-tokenizer) * [`difflib` — Helpers for computing deltas](difflib) + [SequenceMatcher Objects](difflib#sequencematcher-objects) + [SequenceMatcher Examples](difflib#sequencematcher-examples) + [Differ Objects](difflib#differ-objects) + [Differ Example](difflib#differ-example) + [A command-line interface to difflib](difflib#a-command-line-interface-to-difflib) * [`textwrap` — Text wrapping and filling](textwrap) * [`unicodedata` — Unicode Database](unicodedata) * [`stringprep` — Internet String Preparation](stringprep) * [`readline` — GNU readline interface](readline) + [Init file](readline#init-file) + [Line buffer](readline#line-buffer) + [History file](readline#history-file) + [History list](readline#history-list) + [Startup hooks](readline#startup-hooks) + [Completion](readline#completion) + [Example](readline#example) * [`rlcompleter` — Completion function for GNU readline](rlcompleter) + [Completer Objects](rlcompleter#completer-objects) python ast — Abstract Syntax Trees ast — Abstract Syntax Trees =========================== **Source code:** [Lib/ast.py](https://github.com/python/cpython/tree/3.9/Lib/ast.py) The [`ast`](#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like. An abstract syntax tree can be generated by passing [`ast.PyCF_ONLY_AST`](#ast.PyCF_ONLY_AST "ast.PyCF_ONLY_AST") as a flag to the [`compile()`](functions#compile "compile") built-in function, or using the [`parse()`](#ast.parse "ast.parse") helper provided in this module. The result will be a tree of objects whose classes all inherit from [`ast.AST`](#ast.AST "ast.AST"). An abstract syntax tree can be compiled into a Python code object using the built-in [`compile()`](functions#compile "compile") function. Abstract Grammar ---------------- The abstract grammar is currently defined as follows: ``` -- ASDL's 4 builtin types are: -- identifier, int, string, constant module Python { mod = Module(stmt* body, type_ignore* type_ignores) | Interactive(stmt* body) | Expression(expr body) | FunctionType(expr* argtypes, expr returns) stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment) | AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment) | ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list) | Return(expr? value) | Delete(expr* targets) | Assign(expr* targets, expr value, string? type_comment) | AugAssign(expr target, operator op, expr value) -- 'simple' indicates that we annotate simple name without parens | AnnAssign(expr target, expr annotation, expr? value, int simple) -- use 'orelse' because else is a keyword in target languages | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) | While(expr test, stmt* body, stmt* orelse) | If(expr test, stmt* body, stmt* orelse) | With(withitem* items, stmt* body, string? type_comment) | AsyncWith(withitem* items, stmt* body, string? type_comment) | Raise(expr? exc, expr? cause) | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) | Assert(expr test, expr? msg) | Import(alias* names) | ImportFrom(identifier? module, alias* names, int? level) | Global(identifier* names) | Nonlocal(identifier* names) | Expr(expr value) | Pass | Break | Continue -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) -- BoolOp() can use left & right? expr = BoolOp(boolop op, expr* values) | NamedExpr(expr target, expr value) | BinOp(expr left, operator op, expr right) | UnaryOp(unaryop op, expr operand) | Lambda(arguments args, expr body) | IfExp(expr test, expr body, expr orelse) | Dict(expr* keys, expr* values) | Set(expr* elts) | ListComp(expr elt, comprehension* generators) | SetComp(expr elt, comprehension* generators) | DictComp(expr key, expr value, comprehension* generators) | GeneratorExp(expr elt, comprehension* generators) -- the grammar constrains where yield expressions can occur | Await(expr value) | Yield(expr? value) | YieldFrom(expr value) -- need sequences for compare to distinguish between -- x < 4 < 3 and (x < 4) < 3 | Compare(expr left, cmpop* ops, expr* comparators) | Call(expr func, expr* args, keyword* keywords) | FormattedValue(expr value, int? conversion, expr? format_spec) | JoinedStr(expr* values) | Constant(constant value, string? kind) -- the following expression can appear in assignment context | Attribute(expr value, identifier attr, expr_context ctx) | Subscript(expr value, expr slice, expr_context ctx) | Starred(expr value, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) | Tuple(expr* elts, expr_context ctx) -- can appear only in Subscript | Slice(expr? lower, expr? upper, expr? step) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) expr_context = Load | Store | Del boolop = And | Or operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv unaryop = Invert | Not | UAdd | USub cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn comprehension = (expr target, expr iter, expr* ifs, int is_async) excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body) attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults) arg = (identifier arg, expr? annotation, string? type_comment) attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) -- keyword arguments supplied to call (NULL identifier for **kwargs) keyword = (identifier? arg, expr value) attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) -- import name with optional 'as' alias. alias = (identifier name, identifier? asname) withitem = (expr context_expr, expr? optional_vars) type_ignore = TypeIgnore(int lineno, string tag) } ``` Node classes ------------ `class ast.AST` This is the base of all AST node classes. The actual node classes are derived from the `Parser/Python.asdl` file, which is reproduced [below](#abstract-grammar). They are defined in the `_ast` C module and re-exported in [`ast`](#module-ast "ast: Abstract Syntax Tree classes and manipulation."). There is one class defined for each left-hand side symbol in the abstract grammar (for example, `ast.stmt` or `ast.expr`). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, [`ast.BinOp`](#ast.BinOp "ast.BinOp") inherits from `ast.expr`. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created. `_fields` Each concrete class has an attribute [`_fields`](#ast.AST._fields "ast.AST._fields") which gives the names of all child nodes. Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, [`ast.BinOp`](#ast.BinOp "ast.BinOp") instances have an attribute `left` of type `ast.expr`. If these attributes are marked as optional in the grammar (using a question mark), the value might be `None`. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with [`compile()`](functions#compile "compile"). `lineno` `col_offset` `end_lineno` `end_col_offset` Instances of `ast.expr` and `ast.stmt` subclasses have [`lineno`](#ast.AST.lineno "ast.AST.lineno"), [`col_offset`](#ast.AST.col_offset "ast.AST.col_offset"), [`end_lineno`](#ast.AST.end_lineno "ast.AST.end_lineno"), and [`end_col_offset`](#ast.AST.end_col_offset "ast.AST.end_col_offset") attributes. The [`lineno`](#ast.AST.lineno "ast.AST.lineno") and [`end_lineno`](#ast.AST.end_lineno "ast.AST.end_lineno") are the first and last line numbers of the source text span (1-indexed so the first line is line 1), and the [`col_offset`](#ast.AST.col_offset "ast.AST.col_offset") and [`end_col_offset`](#ast.AST.end_col_offset "ast.AST.end_col_offset") are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally. Note that the end positions are not required by the compiler and are therefore optional. The end offset is *after* the last symbol, for example one can get the source segment of a one-line expression node using `source_line[node.col_offset : node.end_col_offset]`. The constructor of a class `ast.T` parses its arguments as follows: * If there are positional arguments, there must be as many as there are items in `T._fields`; they will be assigned as attributes of these names. * If there are keyword arguments, they will set the attributes of the same names to the given values. For example, to create and populate an [`ast.UnaryOp`](#ast.UnaryOp "ast.UnaryOp") node, you could use ``` node = ast.UnaryOp() node.op = ast.USub() node.operand = ast.Constant() node.operand.value = 5 node.operand.lineno = 0 node.operand.col_offset = 0 node.lineno = 0 node.col_offset = 0 ``` or the more compact ``` node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), lineno=0, col_offset=0) ``` Changed in version 3.8: Class [`ast.Constant`](#ast.Constant "ast.Constant") is now used for all constants. Changed in version 3.9: Simple indices are represented by their value, extended slices are represented as tuples. Deprecated since version 3.8: Old classes `ast.Num`, `ast.Str`, `ast.Bytes`, `ast.NameConstant` and `ast.Ellipsis` are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class. Deprecated since version 3.9: Old classes `ast.Index` and `ast.ExtSlice` are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class. Note The descriptions of the specific node classes displayed here were initially adapted from the fantastic [Green Tree Snakes](https://greentreesnakes.readthedocs.io/en/latest/) project and all its contributors. ### Literals `class ast.Constant(value)` A constant value. The `value` attribute of the `Constant` literal contains the Python object it represents. The values represented can be simple types such as a number, string or `None`, but also immutable container types (tuples and frozensets) if all of their elements are constant. ``` >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123)) ``` `class ast.FormattedValue(value, conversion, format_spec)` Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in [`JoinedStr`](#ast.JoinedStr "ast.JoinedStr"). * `value` is any expression node (such as a literal, a variable, or a function call). * `conversion` is an integer: + -1: no formatting + 115: `!s` string formatting + 114: `!r` repr formatting + 97: `!a` ascii formatting * `format_spec` is a [`JoinedStr`](#ast.JoinedStr "ast.JoinedStr") node representing the formatting of the value, or `None` if no format was specified. Both `conversion` and `format_spec` can be set at the same time. `class ast.JoinedStr(values)` An f-string, comprising a series of [`FormattedValue`](#ast.FormattedValue "ast.FormattedValue") and [`Constant`](#ast.Constant "ast.Constant") nodes. ``` >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) Expression( body=JoinedStr( values=[ Constant(value='sin('), FormattedValue( value=Name(id='a', ctx=Load()), conversion=-1), Constant(value=') is '), FormattedValue( value=Call( func=Name(id='sin', ctx=Load()), args=[ Name(id='a', ctx=Load())], keywords=[]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))])) ``` `class ast.List(elts, ctx)` `class ast.Tuple(elts, ctx)` A list or tuple. `elts` holds a list of nodes representing the elements. `ctx` is [`Store`](#ast.Store "ast.Store") if the container is an assignment target (i.e. `(x,y)=something`), and [`Load`](#ast.Load "ast.Load") otherwise. ``` >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) Expression( body=List( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load())) >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) Expression( body=Tuple( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load())) ``` `class ast.Set(elts)` A set. `elts` holds a list of nodes representing the set’s elements. ``` >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4)) Expression( body=Set( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)])) ``` `class ast.Dict(keys, values)` A dictionary. `keys` and `values` hold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when calling `dictionary.keys()` and `dictionary.values()`). When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the `values` list, with a `None` at the corresponding position in `keys`. ``` >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) Expression( body=Dict( keys=[ Constant(value='a'), None], values=[ Constant(value=1), Name(id='d', ctx=Load())])) ``` ### Variables `class ast.Name(id, ctx)` A variable name. `id` holds the name as a string, and `ctx` is one of the following types. `class ast.Load` `class ast.Store` `class ast.Del` Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases. ``` >>> print(ast.dump(ast.parse('a'), indent=4)) Module( body=[ Expr( value=Name(id='a', ctx=Load()))], type_ignores=[]) >>> print(ast.dump(ast.parse('a = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='a', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> print(ast.dump(ast.parse('del a'), indent=4)) Module( body=[ Delete( targets=[ Name(id='a', ctx=Del())])], type_ignores=[]) ``` `class ast.Starred(value, ctx)` A `*var` variable reference. `value` holds the variable, typically a [`Name`](#ast.Name "ast.Name") node. This type must be used when building a [`Call`](#ast.Call "ast.Call") node with `*args`. ``` >>> print(ast.dump(ast.parse('a, *b = it'), indent=4)) Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Starred( value=Name(id='b', ctx=Store()), ctx=Store())], ctx=Store())], value=Name(id='it', ctx=Load()))], type_ignores=[]) ``` ### Expressions `class ast.Expr(value)` When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container. `value` holds one of the other nodes in this section, a [`Constant`](#ast.Constant "ast.Constant"), a [`Name`](#ast.Name "ast.Name"), a [`Lambda`](#ast.Lambda "ast.Lambda"), a [`Yield`](#ast.Yield "ast.Yield") or [`YieldFrom`](#ast.YieldFrom "ast.YieldFrom") node. ``` >>> print(ast.dump(ast.parse('-a'), indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a', ctx=Load())))], type_ignores=[]) ``` `class ast.UnaryOp(op, operand)` A unary operation. `op` is the operator, and `operand` any expression node. `class ast.UAdd` `class ast.USub` `class ast.Not` `class ast.Invert` Unary operator tokens. [`Not`](#ast.Not "ast.Not") is the `not` keyword, [`Invert`](#ast.Invert "ast.Invert") is the `~` operator. ``` >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4)) Expression( body=UnaryOp( op=Not(), operand=Name(id='x', ctx=Load()))) ``` `class ast.BinOp(left, op, right)` A binary operation (like addition or division). `op` is the operator, and `left` and `right` are any expression nodes. ``` >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4)) Expression( body=BinOp( left=Name(id='x', ctx=Load()), op=Add(), right=Name(id='y', ctx=Load()))) ``` `class ast.Add` `class ast.Sub` `class ast.Mult` `class ast.Div` `class ast.FloorDiv` `class ast.Mod` `class ast.Pow` `class ast.LShift` `class ast.RShift` `class ast.BitOr` `class ast.BitXor` `class ast.BitAnd` `class ast.MatMult` Binary operator tokens. `class ast.BoolOp(op, values)` A boolean operation, ‘or’ or ‘and’. `op` is [`Or`](#ast.Or "ast.Or") or [`And`](#ast.And "ast.And"). `values` are the values involved. Consecutive operations with the same operator, such as `a or b or c`, are collapsed into one node with several values. This doesn’t include `not`, which is a [`UnaryOp`](#ast.UnaryOp "ast.UnaryOp"). ``` >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x', ctx=Load()), Name(id='y', ctx=Load())])) ``` `class ast.And` `class ast.Or` Boolean operator tokens. `class ast.Compare(left, ops, comparators)` A comparison of two or more values. `left` is the first value in the comparison, `ops` the list of operators, and `comparators` the list of values after the first element in the comparison. ``` >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) Expression( body=Compare( left=Constant(value=1), ops=[ LtE(), Lt()], comparators=[ Name(id='a', ctx=Load()), Constant(value=10)])) ``` `class ast.Eq` `class ast.NotEq` `class ast.Lt` `class ast.LtE` `class ast.Gt` `class ast.GtE` `class ast.Is` `class ast.IsNot` `class ast.In` `class ast.NotIn` Comparison operator tokens. `class ast.Call(func, args, keywords, starargs, kwargs)` A function call. `func` is the function, which will often be a [`Name`](#ast.Name "ast.Name") or [`Attribute`](#ast.Attribute "ast.Attribute") object. Of the arguments: * `args` holds a list of the arguments passed by position. * `keywords` holds a list of [`keyword`](keyword#module-keyword "keyword: Test whether a string is a keyword in Python.") objects representing arguments passed by keyword. When creating a `Call` node, `args` and `keywords` are required, but they can be empty lists. `starargs` and `kwargs` are optional. ``` >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) Expression( body=Call( func=Name(id='func', ctx=Load()), args=[ Name(id='a', ctx=Load()), Starred( value=Name(id='d', ctx=Load()), ctx=Load())], keywords=[ keyword( arg='b', value=Name(id='c', ctx=Load())), keyword( value=Name(id='e', ctx=Load()))])) ``` `class ast.keyword(arg, value)` A keyword argument to a function call or class definition. `arg` is a raw string of the parameter name, `value` is a node to pass in. `class ast.IfExp(test, body, orelse)` An expression such as `a if b else c`. Each field holds a single node, so in the following example, all three are [`Name`](#ast.Name "ast.Name") nodes. ``` >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4)) Expression( body=IfExp( test=Name(id='b', ctx=Load()), body=Name(id='a', ctx=Load()), orelse=Name(id='c', ctx=Load()))) ``` `class ast.Attribute(value, attr, ctx)` Attribute access, e.g. `d.keys`. `value` is a node, typically a [`Name`](#ast.Name "ast.Name"). `attr` is a bare string giving the name of the attribute, and `ctx` is [`Load`](#ast.Load "ast.Load"), [`Store`](#ast.Store "ast.Store") or [`Del`](#ast.Del "ast.Del") according to how the attribute is acted on. ``` >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4)) Expression( body=Attribute( value=Name(id='snake', ctx=Load()), attr='colour', ctx=Load())) ``` `class ast.NamedExpr(target, value)` A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the [`Assign`](#ast.Assign "ast.Assign") node in which the first argument can be multiple nodes, in this case both `target` and `value` must be single nodes. ``` >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4)) Expression( body=NamedExpr( target=Name(id='x', ctx=Store()), value=Constant(value=4))) ``` #### Subscripting `class ast.Subscript(value, slice, ctx)` A subscript, such as `l[1]`. `value` is the subscripted object (usually sequence or mapping). `slice` is an index, slice or key. It can be a [`Tuple`](#ast.Tuple "ast.Tuple") and contain a [`Slice`](#ast.Slice "ast.Slice"). `ctx` is [`Load`](#ast.Load "ast.Load"), [`Store`](#ast.Store "ast.Store") or [`Del`](#ast.Del "ast.Del") according to the action performed with the subscript. ``` >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l', ctx=Load()), slice=Tuple( elts=[ Slice( lower=Constant(value=1), upper=Constant(value=2)), Constant(value=3)], ctx=Load()), ctx=Load())) ``` `class ast.Slice(lower, upper, step)` Regular slicing (on the form `lower:upper` or `lower:upper:step`). Can occur only inside the *slice* field of [`Subscript`](#ast.Subscript "ast.Subscript"), either directly or as an element of [`Tuple`](#ast.Tuple "ast.Tuple"). ``` >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l', ctx=Load()), slice=Slice( lower=Constant(value=1), upper=Constant(value=2)), ctx=Load())) ``` #### Comprehensions `class ast.ListComp(elt, generators)` `class ast.SetComp(elt, generators)` `class ast.GeneratorExp(elt, generators)` `class ast.DictComp(key, value, generators)` List and set comprehensions, generator expressions, and dictionary comprehensions. `elt` (or `key` and `value`) is a single node representing the part that will be evaluated for each item. `generators` is a list of [`comprehension`](#ast.comprehension "ast.comprehension") nodes. ``` >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4)) Expression( body=ListComp( elt=Name(id='x', ctx=Load()), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4)) Expression( body=DictComp( key=Name(id='x', ctx=Load()), value=BinOp( left=Name(id='x', ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4)) Expression( body=SetComp( elt=Name(id='x', ctx=Load()), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)])) ``` `class ast.comprehension(target, iter, ifs, is_async)` One `for` clause in a comprehension. `target` is the reference to use for each element - typically a [`Name`](#ast.Name "ast.Name") or [`Tuple`](#ast.Tuple "ast.Tuple") node. `iter` is the object to iterate over. `ifs` is a list of test expressions: each `for` clause can have multiple `ifs`. `is_async` indicates a comprehension is asynchronous (using an `async for` instead of `for`). The value is an integer (0 or 1). ``` >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'), ... indent=4)) # Multiple comprehensions in one. Expression( body=ListComp( elt=Call( func=Name(id='ord', ctx=Load()), args=[ Name(id='c', ctx=Load())], keywords=[]), generators=[ comprehension( target=Name(id='line', ctx=Store()), iter=Name(id='file', ctx=Load()), ifs=[], is_async=0), comprehension( target=Name(id='c', ctx=Store()), iter=Name(id='line', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'), ... indent=4)) # generator comprehension Expression( body=GeneratorExp( elt=BinOp( left=Name(id='n', ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='n', ctx=Store()), iter=Name(id='it', ctx=Load()), ifs=[ Compare( left=Name(id='n', ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), Compare( left=Name(id='n', ctx=Load()), ops=[ Lt()], comparators=[ Constant(value=10)])], is_async=0)])) >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'), ... indent=4)) # Async comprehension Expression( body=ListComp( elt=Name(id='i', ctx=Load()), generators=[ comprehension( target=Name(id='i', ctx=Store()), iter=Name(id='soc', ctx=Load()), ifs=[], is_async=1)])) ``` ### Statements `class ast.Assign(targets, value, type_comment)` An assignment. `targets` is a list of nodes, and `value` is a single node. Multiple nodes in `targets` represents assigning the same value to each. Unpacking is represented by putting a [`Tuple`](#ast.Tuple "ast.Tuple") or [`List`](#ast.List "ast.List") within `targets`. `type_comment` `type_comment` is an optional string with the type annotation as a comment. ``` >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ctx=Store())], value=Name(id='c', ctx=Load()))], type_ignores=[]) ``` `class ast.AnnAssign(target, annotation, value, simple)` An assignment with a type annotation. `target` is a single node and can be a [`Name`](#ast.Name "ast.Name"), a [`Attribute`](#ast.Attribute "ast.Attribute") or a [`Subscript`](#ast.Subscript "ast.Subscript"). `annotation` is the annotation, such as a [`Constant`](#ast.Constant "ast.Constant") or [`Name`](#ast.Name "ast.Name") node. `value` is a single optional node. `simple` is a boolean integer set to True for a [`Name`](#ast.Name "ast.Name") node in `target` that do not appear in between parenthesis and are hence pure names and not expressions. ``` >>> print(ast.dump(ast.parse('c: int'), indent=4)) Module( body=[ AnnAssign( target=Name(id='c', ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=1)], type_ignores=[]) >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis Module( body=[ AnnAssign( target=Name(id='a', ctx=Store()), annotation=Name(id='int', ctx=Load()), value=Constant(value=1), simple=0)], type_ignores=[]) >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation Module( body=[ AnnAssign( target=Attribute( value=Name(id='a', ctx=Load()), attr='b', ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=0)], type_ignores=[]) >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a', ctx=Load()), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=0)], type_ignores=[]) ``` `class ast.AugAssign(target, op, value)` Augmented assignment, such as `a += 1`. In the following example, `target` is a [`Name`](#ast.Name "ast.Name") node for `x` (with the [`Store`](#ast.Store "ast.Store") context), `op` is [`Add`](#ast.Add "ast.Add"), and `value` is a [`Constant`](#ast.Constant "ast.Constant") with value for 1. The `target` attribute connot be of class [`Tuple`](#ast.Tuple "ast.Tuple") or [`List`](#ast.List "ast.List"), unlike the targets of [`Assign`](#ast.Assign "ast.Assign"). ``` >>> print(ast.dump(ast.parse('x += 2'), indent=4)) Module( body=[ AugAssign( target=Name(id='x', ctx=Store()), op=Add(), value=Constant(value=2))], type_ignores=[]) ``` `class ast.Raise(exc, cause)` A `raise` statement. `exc` is the exception object to be raised, normally a [`Call`](#ast.Call "ast.Call") or [`Name`](#ast.Name "ast.Name"), or `None` for a standalone `raise`. `cause` is the optional part for `y` in `raise x from y`. ``` >>> print(ast.dump(ast.parse('raise x from y'), indent=4)) Module( body=[ Raise( exc=Name(id='x', ctx=Load()), cause=Name(id='y', ctx=Load()))], type_ignores=[]) ``` `class ast.Assert(test, msg)` An assertion. `test` holds the condition, such as a [`Compare`](#ast.Compare "ast.Compare") node. `msg` holds the failure message. ``` >>> print(ast.dump(ast.parse('assert x,y'), indent=4)) Module( body=[ Assert( test=Name(id='x', ctx=Load()), msg=Name(id='y', ctx=Load()))], type_ignores=[]) ``` `class ast.Delete(targets)` Represents a `del` statement. `targets` is a list of nodes, such as [`Name`](#ast.Name "ast.Name"), [`Attribute`](#ast.Attribute "ast.Attribute") or [`Subscript`](#ast.Subscript "ast.Subscript") nodes. ``` >>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) Module( body=[ Delete( targets=[ Name(id='x', ctx=Del()), Name(id='y', ctx=Del()), Name(id='z', ctx=Del())])], type_ignores=[]) ``` `class ast.Pass` A `pass` statement. ``` >>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()], type_ignores=[]) ``` Other statements which are only applicable inside functions or loops are described in other sections. #### Imports `class ast.Import(names)` An import statement. `names` is a list of [`alias`](#ast.alias "ast.alias") nodes. ``` >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')])], type_ignores=[]) ``` `class ast.ImportFrom(module, names, level)` Represents `from x import y`. `module` is a raw string of the ‘from’ name, without any leading dots, or `None` for statements such as `from . import foo`. `level` is an integer holding the level of the relative import (0 means absolute import). ``` >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4)) Module( body=[ ImportFrom( module='y', names=[ alias(name='x'), alias(name='y'), alias(name='z')], level=0)], type_ignores=[]) ``` `class ast.alias(name, asname)` Both parameters are raw strings of the names. `asname` can be `None` if the regular name is to be used. ``` >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4)) Module( body=[ ImportFrom( module='foo.bar', names=[ alias(name='a', asname='b'), alias(name='c')], level=2)], type_ignores=[]) ``` ### Control flow Note Optional clauses such as `else` are stored as an empty list if they’re not present. `class ast.If(test, body, orelse)` An `if` statement. `test` holds a single node, such as a [`Compare`](#ast.Compare "ast.Compare") node. `body` and `orelse` each hold a list of nodes. `elif` clauses don’t have a special representation in the AST, but rather appear as extra [`If`](#ast.If "ast.If") nodes within the `orelse` section of the previous one. ``` >>> print(ast.dump(ast.parse(""" ... if x: ... ... ... elif y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ If( test=Name(id='x', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ If( test=Name(id='y', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) ``` `class ast.For(target, iter, body, orelse, type_comment)` A `for` loop. `target` holds the variable(s) the loop assigns to, as a single [`Name`](#ast.Name "ast.Name"), [`Tuple`](#ast.Tuple "ast.Tuple") or [`List`](#ast.List "ast.List") node. `iter` holds the item to be looped over, again as a single node. `body` and `orelse` contain lists of nodes to execute. Those in `orelse` are executed if the loop finishes normally, rather than via a `break` statement. `type_comment` `type_comment` is an optional string with the type annotation as a comment. ``` >>> print(ast.dump(ast.parse(""" ... for x in y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ For( target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) ``` `class ast.While(test, body, orelse)` A `while` loop. `test` holds the condition, such as a [`Compare`](#ast.Compare "ast.Compare") node. ``` >> print(ast.dump(ast.parse(""" ... while x: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ While( test=Name(id='x', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) ``` `class ast.Break` `class ast.Continue` The `break` and `continue` statements. ``` >>> print(ast.dump(ast.parse("""\ ... for a in b: ... if a > 5: ... break ... else: ... continue ... ... """), indent=4)) Module( body=[ For( target=Name(id='a', ctx=Store()), iter=Name(id='b', ctx=Load()), body=[ If( test=Compare( left=Name(id='a', ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), body=[ Break()], orelse=[ Continue()])], orelse=[])], type_ignores=[]) ``` `class ast.Try(body, handlers, orelse, finalbody)` `try` blocks. All attributes are list of nodes to execute, except for `handlers`, which is a list of [`ExceptHandler`](#ast.ExceptHandler "ast.ExceptHandler") nodes. ``` >>> print(ast.dump(ast.parse(""" ... try: ... ... ... except Exception: ... ... ... except OtherException as e: ... ... ... else: ... ... ... finally: ... ... ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))]), ExceptHandler( type=Name(id='OtherException', ctx=Load()), name='e', body=[ Expr( value=Constant(value=Ellipsis))])], orelse=[ Expr( value=Constant(value=Ellipsis))], finalbody=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) ``` `class ast.ExceptHandler(type, name, body)` A single `except` clause. `type` is the exception type it will match, typically a [`Name`](#ast.Name "ast.Name") node (or `None` for a catch-all `except:` clause). `name` is a raw string for the name to hold the exception, or `None` if the clause doesn’t have `as foo`. `body` is a list of nodes. ``` >>> print(ast.dump(ast.parse("""\ ... try: ... a + 1 ... except TypeError: ... pass ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=BinOp( left=Name(id='a', ctx=Load()), op=Add(), right=Constant(value=1)))], handlers=[ ExceptHandler( type=Name(id='TypeError', ctx=Load()), body=[ Pass()])], orelse=[], finalbody=[])], type_ignores=[]) ``` `class ast.With(items, body, type_comment)` A `with` block. `items` is a list of [`withitem`](#ast.withitem "ast.withitem") nodes representing the context managers, and `body` is the indented block inside the context. `type_comment` `type_comment` is an optional string with the type annotation as a comment. `class ast.withitem(context_expr, optional_vars)` A single context manager in a `with` block. `context_expr` is the context manager, often a [`Call`](#ast.Call "ast.Call") node. `optional_vars` is a [`Name`](#ast.Name "ast.Name"), [`Tuple`](#ast.Tuple "ast.Tuple") or [`List`](#ast.List "ast.List") for the `as foo` part, or `None` if that isn’t used. ``` >>> print(ast.dump(ast.parse("""\ ... with a as b, c as d: ... something(b, d) ... """), indent=4)) Module( body=[ With( items=[ withitem( context_expr=Name(id='a', ctx=Load()), optional_vars=Name(id='b', ctx=Store())), withitem( context_expr=Name(id='c', ctx=Load()), optional_vars=Name(id='d', ctx=Store()))], body=[ Expr( value=Call( func=Name(id='something', ctx=Load()), args=[ Name(id='b', ctx=Load()), Name(id='d', ctx=Load())], keywords=[]))])], type_ignores=[]) ``` ### Function and class definitions `class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment)` A function definition. * `name` is a raw string of the function name. * `args` is an [`arguments`](#ast.arguments "ast.arguments") node. * `body` is the list of nodes inside the function. * `decorator_list` is the list of decorators to be applied, stored outermost first (i.e. the first in the list will be applied last). * `returns` is the return annotation. `type_comment` `type_comment` is an optional string with the type annotation as a comment. `class ast.Lambda(args, body)` `lambda` is a minimal function definition that can be used inside an expression. Unlike [`FunctionDef`](#ast.FunctionDef "ast.FunctionDef"), `body` holds a single node. ``` >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) Module( body=[ Expr( value=Lambda( args=arguments( posonlyargs=[], args=[ arg(arg='x'), arg(arg='y')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=Constant(value=Ellipsis)))], type_ignores=[]) ``` `class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)` The arguments for a function. * `posonlyargs`, `args` and `kwonlyargs` are lists of [`arg`](#ast.arg "ast.arg") nodes. * `vararg` and `kwarg` are single [`arg`](#ast.arg "ast.arg") nodes, referring to the `*args, **kwargs` parameters. * `kw_defaults` is a list of default values for keyword-only arguments. If one is `None`, the corresponding argument is required. * `defaults` is a list of default values for arguments that can be passed positionally. If there are fewer defaults, they correspond to the last n arguments. `class ast.arg(arg, annotation, type_comment)` A single argument in a list. `arg` is a raw string of the argument name, `annotation` is its annotation, such as a `Str` or [`Name`](#ast.Name "ast.Name") node. `type_comment` `type_comment` is an optional string with the type annotation as a comment ``` >>> print(ast.dump(ast.parse("""\ ... @decorator1 ... @decorator2 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': ... pass ... """), indent=4)) Module( body=[ FunctionDef( name='f', args=arguments( posonlyargs=[], args=[ arg( arg='a', annotation=Constant(value='annotation')), arg(arg='b'), arg(arg='c')], vararg=arg(arg='d'), kwonlyargs=[ arg(arg='e'), arg(arg='f')], kw_defaults=[ None, Constant(value=3)], kwarg=arg(arg='g'), defaults=[ Constant(value=1), Constant(value=2)]), body=[ Pass()], decorator_list=[ Name(id='decorator1', ctx=Load()), Name(id='decorator2', ctx=Load())], returns=Constant(value='return annotation'))], type_ignores=[]) ``` `class ast.Return(value)` A `return` statement. ``` >>> print(ast.dump(ast.parse('return 4'), indent=4)) Module( body=[ Return( value=Constant(value=4))], type_ignores=[]) ``` `class ast.Yield(value)` `class ast.YieldFrom(value)` A `yield` or `yield from` expression. Because these are expressions, they must be wrapped in a [`Expr`](#ast.Expr "ast.Expr") node if the value sent back is not used. ``` >>> print(ast.dump(ast.parse('yield x'), indent=4)) Module( body=[ Expr( value=Yield( value=Name(id='x', ctx=Load())))], type_ignores=[]) >>> print(ast.dump(ast.parse('yield from x'), indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x', ctx=Load())))], type_ignores=[]) ``` `class ast.Global(names)` `class ast.Nonlocal(names)` `global` and `nonlocal` statements. `names` is a list of raw strings. ``` >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) Module( body=[ Global( names=[ 'x', 'y', 'z'])], type_ignores=[]) >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])], type_ignores=[]) ``` `class ast.ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)` A class definition. * `name` is a raw string for the class name * `bases` is a list of nodes for explicitly specified base classes. * `keywords` is a list of [`keyword`](keyword#module-keyword "keyword: Test whether a string is a keyword in Python.") nodes, principally for ‘metaclass’. Other keywords will be passed to the metaclass, as per [PEP-3115](https://www.python.org/dev/peps/pep-3115/). * `starargs` and `kwargs` are each a single node, as in a function call. starargs will be expanded to join the list of base classes, and kwargs will be passed to the metaclass. * `body` is a list of nodes representing the code within the class definition. * `decorator_list` is a list of nodes, as in [`FunctionDef`](#ast.FunctionDef "ast.FunctionDef"). ``` >>> print(ast.dump(ast.parse("""\ ... @decorator1 ... @decorator2 ... class Foo(base1, base2, metaclass=meta): ... pass ... """), indent=4)) Module( body=[ ClassDef( name='Foo', bases=[ Name(id='base1', ctx=Load()), Name(id='base2', ctx=Load())], keywords=[ keyword( arg='metaclass', value=Name(id='meta', ctx=Load()))], body=[ Pass()], decorator_list=[ Name(id='decorator1', ctx=Load()), Name(id='decorator2', ctx=Load())])], type_ignores=[]) ``` ### Async and await `class ast.AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)` An `async def` function definition. Has the same fields as [`FunctionDef`](#ast.FunctionDef "ast.FunctionDef"). `class ast.Await(value)` An `await` expression. `value` is what it waits for. Only valid in the body of an [`AsyncFunctionDef`](#ast.AsyncFunctionDef "ast.AsyncFunctionDef"). ``` >>> print(ast.dump(ast.parse("""\ ... async def f(): ... await other_func() ... """), indent=4)) Module( body=[ AsyncFunctionDef( name='f', args=arguments( posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=[ Expr( value=Await( value=Call( func=Name(id='other_func', ctx=Load()), args=[], keywords=[])))], decorator_list=[])], type_ignores=[]) ``` `class ast.AsyncFor(target, iter, body, orelse, type_comment)` `class ast.AsyncWith(items, body, type_comment)` `async for` loops and `async with` context managers. They have the same fields as [`For`](#ast.For "ast.For") and [`With`](#ast.With "ast.With"), respectively. Only valid in the body of an [`AsyncFunctionDef`](#ast.AsyncFunctionDef "ast.AsyncFunctionDef"). Note When a string is parsed by [`ast.parse()`](#ast.parse "ast.parse"), operator nodes (subclasses of `ast.operator`, `ast.unaryop`, `ast.cmpop`, `ast.boolop` and `ast.expr_context`) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (e.g. [`ast.Add`](#ast.Add "ast.Add")). ast Helpers ----------- Apart from the node classes, the [`ast`](#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module defines these utility functions and classes for traversing abstract syntax trees: `ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)` Parse the source into an AST node. Equivalent to `compile(source, filename, mode, ast.PyCF_ONLY_AST)`. If `type_comments=True` is given, the parser is modified to check and return type comments as specified by [**PEP 484**](https://www.python.org/dev/peps/pep-0484) and [**PEP 526**](https://www.python.org/dev/peps/pep-0526). This is equivalent to adding [`ast.PyCF_TYPE_COMMENTS`](#ast.PyCF_TYPE_COMMENTS "ast.PyCF_TYPE_COMMENTS") to the flags passed to [`compile()`](functions#compile "compile"). This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the `type_comment` field on selected AST nodes will always be `None`. In addition, the locations of `# type: ignore` comments will be returned as the `type_ignores` attribute of `Module` (otherwise it is always an empty list). In addition, if `mode` is `'func_type'`, the input syntax is modified to correspond to [**PEP 484**](https://www.python.org/dev/peps/pep-0484) “signature type comments”, e.g. `(str, int) -> List[str]`. Also, setting `feature_version` to a tuple `(major, minor)` will attempt to parse using that Python version’s grammar. Currently `major` must equal to `3`. For example, setting `feature_version=(3, 4)` will allow the use of `async` and `await` as variable names. The lowest supported version is `(3, 4)`; the highest is `sys.version_info[0:2]`. If source contains a null character (‘0’), [`ValueError`](exceptions#ValueError "ValueError") is raised. Warning Note that successfully parsing source code into an AST object doesn’t guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further [`SyntaxError`](exceptions#SyntaxError "SyntaxError") exceptions. For instance, the source `return 42` generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node). In particular, [`ast.parse()`](#ast.parse "ast.parse") won’t do any scoping checks, which the compilation step does. Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler. Changed in version 3.8: Added `type_comments`, `mode='func_type'` and `feature_version`. `ast.unparse(ast_obj)` Unparse an [`ast.AST`](#ast.AST "ast.AST") object and generate a string with code that would produce an equivalent [`ast.AST`](#ast.AST "ast.AST") object if parsed back with [`ast.parse()`](#ast.parse "ast.parse"). Warning The produced code string will not necessarily be equal to the original code that generated the [`ast.AST`](#ast.AST "ast.AST") object (without any compiler optimizations, such as constant tuples/frozensets). Warning Trying to unparse a highly complex expression would result with [`RecursionError`](exceptions#RecursionError "RecursionError"). New in version 3.9. `ast.literal_eval(node_or_string)` Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and `None`. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing. Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler. Changed in version 3.2: Now allows bytes and set literals. Changed in version 3.9: Now supports creating empty sets with `'set()'`. `ast.get_docstring(node, clean=True)` Return the docstring of the given *node* (which must be a [`FunctionDef`](#ast.FunctionDef "ast.FunctionDef"), [`AsyncFunctionDef`](#ast.AsyncFunctionDef "ast.AsyncFunctionDef"), [`ClassDef`](#ast.ClassDef "ast.ClassDef"), or `Module` node), or `None` if it has no docstring. If *clean* is true, clean up the docstring’s indentation with [`inspect.cleandoc()`](inspect#inspect.cleandoc "inspect.cleandoc"). Changed in version 3.5: [`AsyncFunctionDef`](#ast.AsyncFunctionDef "ast.AsyncFunctionDef") is now supported. `ast.get_source_segment(source, node, *, padded=False)` Get source code segment of the *source* that generated *node*. If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return `None`. If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its original position. New in version 3.8. `ast.fix_missing_locations(node)` When you compile a node tree with [`compile()`](functions#compile "compile"), the compiler expects `lineno` and `col_offset` attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. `ast.increment_lineno(node, n=1)` Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to “move code” to a different location in a file. `ast.copy_location(new_node, old_node)` Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`) from *old\_node* to *new\_node* if possible, and return *new\_node*. `ast.iter_fields(node)` Yield a tuple of `(fieldname, value)` for each field in `node._fields` that is present on *node*. `ast.iter_child_nodes(node)` Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. `ast.walk(node)` Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context. `class ast.NodeVisitor` A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the [`visit()`](#ast.NodeVisitor.visit "ast.NodeVisitor.visit") method. This class is meant to be subclassed, with the subclass adding visitor methods. `visit(node)` Visit a node. The default implementation calls the method called `self.visit_*classname*` where *classname* is the name of the node class, or [`generic_visit()`](#ast.NodeVisitor.generic_visit "ast.NodeVisitor.generic_visit") if that method doesn’t exist. `generic_visit(node)` This visitor calls [`visit()`](#ast.NodeVisitor.visit "ast.NodeVisitor.visit") on all children of the node. Note that child nodes of nodes that have a custom visitor method won’t be visited unless the visitor calls [`generic_visit()`](#ast.NodeVisitor.generic_visit "ast.NodeVisitor.generic_visit") or visits them itself. Don’t use the [`NodeVisitor`](#ast.NodeVisitor "ast.NodeVisitor") if you want to apply changes to nodes during traversal. For this a special visitor exists ([`NodeTransformer`](#ast.NodeTransformer "ast.NodeTransformer")) that allows modifications. Deprecated since version 3.8: Methods `visit_Num()`, `visit_Str()`, `visit_Bytes()`, `visit_NameConstant()` and `visit_Ellipsis()` are deprecated now and will not be called in future Python versions. Add the `visit_Constant()` method to handle all constant nodes. `class ast.NodeTransformer` A [`NodeVisitor`](#ast.NodeVisitor "ast.NodeVisitor") subclass that walks the abstract syntax tree and allows modification of nodes. The [`NodeTransformer`](#ast.NodeTransformer "ast.NodeTransformer") will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is `None`, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place. Here is an example transformer that rewrites all occurrences of name lookups (`foo`) to `data['foo']`: ``` class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx ) ``` Keep in mind that if the node you’re operating on has child nodes you must either transform the child nodes yourself or call the `generic_visit()` method for the node first. For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node. If [`NodeTransformer`](#ast.NodeTransformer "ast.NodeTransformer") introduces new nodes (that weren’t part of original tree) without giving them location information (such as `lineno`), [`fix_missing_locations()`](#ast.fix_missing_locations "ast.fix_missing_locations") should be called with the new sub-tree to recalculate the location information: ``` tree = ast.parse('foo', mode='eval') new_tree = fix_missing_locations(RewriteName().visit(tree)) ``` Usually you use the transformer like this: ``` node = YourTransformer().visit(node) ``` `ast.dump(node, annotate_fields=True, include_attributes=False, *, indent=None)` Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. If *annotate\_fields* is true (by default), the returned string will show the names and the values for fields. If *annotate\_fields* is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include\_attributes* can be set to true. If *indent* is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or `""` will only insert newlines. `None` (the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If *indent* is a string (such as `"\t"`), that string is used to indent each level. Changed in version 3.9: Added the *indent* option. Compiler Flags -------------- The following flags may be passed to [`compile()`](functions#compile "compile") in order to change effects on the compilation of a program: `ast.PyCF_ALLOW_TOP_LEVEL_AWAIT` Enables support for top-level `await`, `async for`, `async with` and async comprehensions. New in version 3.8. `ast.PyCF_ONLY_AST` Generates and returns an abstract syntax tree instead of returning a compiled code object. `ast.PyCF_TYPE_COMMENTS` Enables support for [**PEP 484**](https://www.python.org/dev/peps/pep-0484) and [**PEP 526**](https://www.python.org/dev/peps/pep-0526) style type comments (`# type: <type>`, `# type: ignore <stuff>`). New in version 3.8. Command-Line Usage ------------------ New in version 3.9. The [`ast`](#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module can be executed as a script from the command line. It is as simple as: ``` python -m ast [-m <mode>] [-a] [infile] ``` The following options are accepted: `-h, --help` Show the help message and exit. `-m <mode>` `--mode <mode>` Specify what kind of code must be compiled, like the *mode* argument in [`parse()`](#ast.parse "ast.parse"). `--no-type-comments` Don’t parse type comments. `-a, --include-attributes` Include attributes such as line numbers and column offsets. `-i <indent>` `--indent <indent>` Indentation of nodes in AST (number of spaces). If `infile` is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin. See also [Green Tree Snakes](https://greentreesnakes.readthedocs.io/), an external documentation resource, has good details on working with Python ASTs. [ASTTokens](https://asttokens.readthedocs.io/en/latest/user-guide.html) annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations. [leoAst.py](http://leoeditor.com/appendices.html#leoast-py) unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes. [LibCST](https://libcst.readthedocs.io/) parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It’s useful for building automated refactoring (codemod) applications and linters. [Parso](https://parso.readthedocs.io) is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your python file.
programming_docs
python modulefinder — Find modules used by a script modulefinder — Find modules used by a script ============================================ **Source code:** [Lib/modulefinder.py](https://github.com/python/cpython/tree/3.9/Lib/modulefinder.py) This module provides a [`ModuleFinder`](#modulefinder.ModuleFinder "modulefinder.ModuleFinder") class that can be used to determine the set of modules imported by a script. `modulefinder.py` can also be run as a script, giving the filename of a Python script as its argument, after which a report of the imported modules will be printed. `modulefinder.AddPackagePath(pkg_name, path)` Record that the package named *pkg\_name* can be found in the specified *path*. `modulefinder.ReplacePackage(oldname, newname)` Allows specifying that the module named *oldname* is in fact the package named *newname*. `class modulefinder.ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[])` This class provides [`run_script()`](#modulefinder.ModuleFinder.run_script "modulefinder.ModuleFinder.run_script") and [`report()`](#modulefinder.ModuleFinder.report "modulefinder.ModuleFinder.report") methods to determine the set of modules imported by a script. *path* can be a list of directories to search for modules; if not specified, `sys.path` is used. *debug* sets the debugging level; higher values make the class print debugging messages about what it’s doing. *excludes* is a list of module names to exclude from the analysis. *replace\_paths* is a list of `(oldpath, newpath)` tuples that will be replaced in module paths. `report()` Print a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing. `run_script(pathname)` Analyze the contents of the *pathname* file, which must contain Python code. `modules` A dictionary mapping module names to modules. See [Example usage of ModuleFinder](#modulefinder-example). Example usage of ModuleFinder ----------------------------- The script that is going to get analyzed later on (bacon.py): ``` import re, itertools try: import baconhameggs except ImportError: pass try: import guido.python.ham except ImportError: pass ``` The script that will output the report of bacon.py: ``` from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('bacon.py') print('Loaded modules:') for name, mod in finder.modules.items(): print('%s: ' % name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('-'*50) print('Modules not imported:') print('\n'.join(finder.badmodules.keys())) ``` Sample output (may vary depending on the architecture): ``` Loaded modules: _types: copyreg: _inverted_registry,_slotnames,__all__ sre_compile: isstring,_sre,_optimize_unicode _sre: sre_constants: REPEAT_ONE,makedict,AT_END_LINE sys: re: __module__,finditer,_expand itertools: __main__: re,itertools,baconhameggs sre_parse: _PATTERNENDERS,SRE_FLAG_UNICODE array: types: __module__,IntType,TypeType --------------------------------------------------- Modules not imported: guido.python.ham baconhameggs ``` python poplib — POP3 protocol client poplib — POP3 protocol client ============================= **Source code:** [Lib/poplib.py](https://github.com/python/cpython/tree/3.9/Lib/poplib.py) This module defines a class, [`POP3`](#poplib.POP3 "poplib.POP3"), which encapsulates a connection to a POP3 server and implements the protocol as defined in [**RFC 1939**](https://tools.ietf.org/html/rfc1939.html). The [`POP3`](#poplib.POP3 "poplib.POP3") class supports both the minimal and optional command sets from [**RFC 1939**](https://tools.ietf.org/html/rfc1939.html). The [`POP3`](#poplib.POP3 "poplib.POP3") class also supports the `STLS` command introduced in [**RFC 2595**](https://tools.ietf.org/html/rfc2595.html) to enable encrypted communication on an already established connection. Additionally, this module provides a class [`POP3_SSL`](#poplib.POP3_SSL "poplib.POP3_SSL"), which provides support for connecting to POP3 servers that use SSL as an underlying protocol layer. Note that POP3, though widely supported, is obsolescent. The implementation quality of POP3 servers varies widely, and too many are quite poor. If your mailserver supports IMAP, you would be better off using the [`imaplib.IMAP4`](imaplib#imaplib.IMAP4 "imaplib.IMAP4") class, as IMAP servers tend to be better implemented. The [`poplib`](#module-poplib "poplib: POP3 protocol client (requires sockets).") module provides two classes: `class poplib.POP3(host, port=POP3_PORT[, timeout])` This class implements the actual POP3 protocol. The connection is created when the instance is initialized. If *port* is omitted, the standard POP3 port (110) is used. The optional *timeout* parameter specifies a timeout in seconds for the connection attempt (if not specified, the global default timeout setting will be used). Raises an [auditing event](sys#auditing) `poplib.connect` with arguments `self`, `host`, `port`. All commands will raise an [auditing event](sys#auditing) `poplib.putline` with arguments `self` and `line`, where `line` is the bytes about to be sent to the remote host. Changed in version 3.9: If the *timeout* parameter is set to be zero, it will raise a [`ValueError`](exceptions#ValueError "ValueError") to prevent the creation of a non-blocking socket. `class poplib.POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None)` This is a subclass of [`POP3`](#poplib.POP3 "poplib.POP3") that connects to the server over an SSL encrypted socket. If *port* is not specified, 995, the standard POP3-over-SSL port is used. *timeout* works as in the [`POP3`](#poplib.POP3 "poplib.POP3") constructor. *context* is an optional [`ssl.SSLContext`](ssl#ssl.SSLContext "ssl.SSLContext") object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read [Security considerations](ssl#ssl-security) for best practices. *keyfile* and *certfile* are a legacy alternative to *context* - they can point to PEM-formatted private key and certificate chain files, respectively, for the SSL connection. Raises an [auditing event](sys#auditing) `poplib.connect` with arguments `self`, `host`, `port`. All commands will raise an [auditing event](sys#auditing) `poplib.putline` with arguments `self` and `line`, where `line` is the bytes about to be sent to the remote host. Changed in version 3.2: *context* parameter added. Changed in version 3.4: The class now supports hostname check with [`ssl.SSLContext.check_hostname`](ssl#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") and *Server Name Indication* (see [`ssl.HAS_SNI`](ssl#ssl.HAS_SNI "ssl.HAS_SNI")). Deprecated since version 3.6: *keyfile* and *certfile* are deprecated in favor of *context*. Please use [`ssl.SSLContext.load_cert_chain()`](ssl#ssl.SSLContext.load_cert_chain "ssl.SSLContext.load_cert_chain") instead, or let [`ssl.create_default_context()`](ssl#ssl.create_default_context "ssl.create_default_context") select the system’s trusted CA certificates for you. Changed in version 3.9: If the *timeout* parameter is set to be zero, it will raise a [`ValueError`](exceptions#ValueError "ValueError") to prevent the creation of a non-blocking socket. One exception is defined as an attribute of the [`poplib`](#module-poplib "poplib: POP3 protocol client (requires sockets).") module: `exception poplib.error_proto` Exception raised on any errors from this module (errors from [`socket`](socket#module-socket "socket: Low-level networking interface.") module are not caught). The reason for the exception is passed to the constructor as a string. See also `Module` [`imaplib`](imaplib#module-imaplib "imaplib: IMAP4 protocol client (requires sockets).") The standard Python IMAP module. [Frequently Asked Questions About Fetchmail](http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html) The FAQ for the **fetchmail** POP/IMAP client collects information on POP3 server variations and RFC noncompliance that may be useful if you need to write an application based on the POP protocol. POP3 Objects ------------ All POP3 commands are represented by methods of the same name, in lower-case; most return the response text sent by the server. An [`POP3`](#poplib.POP3 "poplib.POP3") instance has the following methods: `POP3.set_debuglevel(level)` Set the instance’s debugging level. This controls the amount of debugging output printed. The default, `0`, produces no debugging output. A value of `1` produces a moderate amount of debugging output, generally a single line per request. A value of `2` or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection. `POP3.getwelcome()` Returns the greeting string sent by the POP3 server. `POP3.capa()` Query the server’s capabilities as specified in [**RFC 2449**](https://tools.ietf.org/html/rfc2449.html). Returns a dictionary in the form `{'name': ['param'...]}`. New in version 3.4. `POP3.user(username)` Send user command, response should indicate that a password is required. `POP3.pass_(password)` Send password, response includes message count and mailbox size. Note: the mailbox on the server is locked until `quit()` is called. `POP3.apop(user, secret)` Use the more secure APOP authentication to log into the POP3 server. `POP3.rpop(user)` Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server. `POP3.stat()` Get mailbox status. The result is a tuple of 2 integers: `(message count, mailbox size)`. `POP3.list([which])` Request message list, result is in the form `(response, ['mesg_num octets', ...], octets)`. If *which* is set, it is the message to list. `POP3.retr(which)` Retrieve whole message number *which*, and set its seen flag. Result is in form `(response, ['line', ...], octets)`. `POP3.dele(which)` Flag message number *which* for deletion. On most servers deletions are not actually performed until QUIT (the major exception is Eudora QPOP, which deliberately violates the RFCs by doing pending deletes on any disconnect). `POP3.rset()` Remove any deletion marks for the mailbox. `POP3.noop()` Do nothing. Might be used as a keep-alive. `POP3.quit()` Signoff: commit changes, unlock mailbox, drop connection. `POP3.top(which, howmuch)` Retrieves the message header plus *howmuch* lines of the message after the header of message number *which*. Result is in form `(response, ['line', ...], octets)`. The POP3 TOP command this method uses, unlike the RETR command, doesn’t set the message’s seen flag; unfortunately, TOP is poorly specified in the RFCs and is frequently broken in off-brand servers. Test this method by hand against the POP3 servers you will use before trusting it. `POP3.uidl(which=None)` Return message digest (unique id) list. If *which* is specified, result contains the unique id for that message in the form `'response mesgnum uid`, otherwise result is list `(response, ['mesgnum uid', ...], octets)`. `POP3.utf8()` Try to switch to UTF-8 mode. Returns the server response if successful, raises [`error_proto`](#poplib.error_proto "poplib.error_proto") if not. Specified in [**RFC 6856**](https://tools.ietf.org/html/rfc6856.html). New in version 3.5. `POP3.stls(context=None)` Start a TLS session on the active connection as specified in [**RFC 2595**](https://tools.ietf.org/html/rfc2595.html). This is only allowed before user authentication *context* parameter is a [`ssl.SSLContext`](ssl#ssl.SSLContext "ssl.SSLContext") object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read [Security considerations](ssl#ssl-security) for best practices. This method supports hostname checking via [`ssl.SSLContext.check_hostname`](ssl#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") and *Server Name Indication* (see [`ssl.HAS_SNI`](ssl#ssl.HAS_SNI "ssl.HAS_SNI")). New in version 3.4. Instances of [`POP3_SSL`](#poplib.POP3_SSL "poplib.POP3_SSL") have no additional methods. The interface of this subclass is identical to its parent. POP3 Example ------------ Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages: ``` import getpass, poplib M = poplib.POP3('localhost') M.user(getpass.getuser()) M.pass_(getpass.getpass()) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print(j) ``` At the end of the module, there is a test section that contains a more extensive example of usage. python mmap — Memory-mapped file support mmap — Memory-mapped file support ================================= Memory-mapped file objects behave like both [`bytearray`](stdtypes#bytearray "bytearray") and like [file objects](../glossary#term-file-object). You can use mmap objects in most places where [`bytearray`](stdtypes#bytearray "bytearray") are expected; for example, you can use the [`re`](re#module-re "re: Regular expression operations.") module to search through a memory-mapped file. You can also change a single byte by doing `obj[index] = 97`, or change a subsequence by assigning to a slice: `obj[i1:i2] = b'...'`. You can also read and write data starting at the current file position, and `seek()` through the file to different positions. A memory-mapped file is created by the [`mmap`](#mmap.mmap "mmap.mmap") constructor, which is different on Unix and on Windows. In either case you must provide a file descriptor for a file opened for update. If you wish to map an existing Python file object, use its `fileno()` method to obtain the correct value for the *fileno* parameter. Otherwise, you can open the file using the [`os.open()`](os#os.open "os.open") function, which returns a file descriptor directly (the file still needs to be closed when done). Note If you want to create a memory-mapping for a writable, buffered file, you should [`flush()`](io#io.IOBase.flush "io.IOBase.flush") the file first. This is necessary to ensure that local modifications to the buffers are actually available to the mapping. For both the Unix and Windows versions of the constructor, *access* may be specified as an optional keyword parameter. *access* accepts one of four values: `ACCESS_READ`, `ACCESS_WRITE`, or `ACCESS_COPY` to specify read-only, write-through or copy-on-write memory respectively, or `ACCESS_DEFAULT` to defer to *prot*. *access* can be used on both Unix and Windows. If *access* is not specified, Windows mmap returns a write-through mapping. The initial memory values for all three access types are taken from the specified file. Assignment to an `ACCESS_READ` memory map raises a [`TypeError`](exceptions#TypeError "TypeError") exception. Assignment to an `ACCESS_WRITE` memory map affects both memory and the underlying file. Assignment to an `ACCESS_COPY` memory map affects memory but does not update the underlying file. Changed in version 3.7: Added `ACCESS_DEFAULT` constant. To map anonymous memory, -1 should be passed as the fileno along with the length. `class mmap.mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])` **(Windows version)** Maps *length* bytes from the file specified by the file handle *fileno*, and creates a mmap object. If *length* is larger than the current size of the file, the file is extended to contain *length* bytes. If *length* is `0`, the maximum length of the map is the current size of the file, except that if the file is empty Windows raises an exception (you cannot create an empty mapping on Windows). *tagname*, if specified and not `None`, is a string giving a tag name for the mapping. Windows allows you to have many different mappings against the same file. If you specify the name of an existing tag, that tag is opened, otherwise a new tag of this name is created. If this parameter is omitted or `None`, the mapping is created without a name. Avoiding the use of the tag parameter will assist in keeping your code portable between Unix and Windows. *offset* may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. *offset* defaults to 0. *offset* must be a multiple of the `ALLOCATIONGRANULARITY`. Raises an [auditing event](sys#auditing) `mmap.__new__` with arguments `fileno`, `length`, `access`, `offset`. `class mmap.mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])` **(Unix version)** Maps *length* bytes from the file specified by the file descriptor *fileno*, and returns a mmap object. If *length* is `0`, the maximum length of the map will be the current size of the file when [`mmap`](#mmap.mmap "mmap.mmap") is called. *flags* specifies the nature of the mapping. `MAP_PRIVATE` creates a private copy-on-write mapping, so changes to the contents of the mmap object will be private to this process, and `MAP_SHARED` creates a mapping that’s shared with all other processes mapping the same areas of the file. The default value is `MAP_SHARED`. *prot*, if specified, gives the desired memory protection; the two most useful values are `PROT_READ` and `PROT_WRITE`, to specify that the pages may be read or written. *prot* defaults to `PROT_READ | PROT_WRITE`. *access* may be specified in lieu of *flags* and *prot* as an optional keyword parameter. It is an error to specify both *flags*, *prot* and *access*. See the description of *access* above for information on how to use this parameter. *offset* may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. *offset* defaults to 0. *offset* must be a multiple of `ALLOCATIONGRANULARITY` which is equal to `PAGESIZE` on Unix systems. To ensure validity of the created memory mapping the file specified by the descriptor *fileno* is internally automatically synchronized with physical backing store on macOS and OpenVMS. This example shows a simple way of using [`mmap`](#mmap.mmap "mmap.mmap"): ``` import mmap # write a simple example file with open("hello.txt", "wb") as f: f.write(b"Hello Python!\n") with open("hello.txt", "r+b") as f: # memory-map the file, size 0 means whole file mm = mmap.mmap(f.fileno(), 0) # read content via standard file methods print(mm.readline()) # prints b"Hello Python!\n" # read content via slice notation print(mm[:5]) # prints b"Hello" # update content using slice notation; # note that new content must have same size mm[6:] = b" world!\n" # ... and read again using standard file methods mm.seek(0) print(mm.readline()) # prints b"Hello world!\n" # close the map mm.close() ``` [`mmap`](#mmap.mmap "mmap.mmap") can also be used as a context manager in a [`with`](../reference/compound_stmts#with) statement: ``` import mmap with mmap.mmap(-1, 13) as mm: mm.write(b"Hello world!") ``` New in version 3.2: Context manager support. The next example demonstrates how to create an anonymous map and exchange data between the parent and child processes: ``` import mmap import os mm = mmap.mmap(-1, 13) mm.write(b"Hello world!") pid = os.fork() if pid == 0: # In a child process mm.seek(0) print(mm.readline()) mm.close() ``` Raises an [auditing event](sys#auditing) `mmap.__new__` with arguments `fileno`, `length`, `access`, `offset`. Memory-mapped file objects support the following methods: `close()` Closes the mmap. Subsequent calls to other methods of the object will result in a ValueError exception being raised. This will not close the open file. `closed` `True` if the file is closed. New in version 3.2. `find(sub[, start[, end]])` Returns the lowest index in the object where the subsequence *sub* is found, such that *sub* is contained in the range [*start*, *end*]. Optional arguments *start* and *end* are interpreted as in slice notation. Returns `-1` on failure. Changed in version 3.5: Writable [bytes-like object](../glossary#term-bytes-like-object) is now accepted. `flush([offset[, size]])` Flushes changes made to the in-memory copy of a file back to disk. Without use of this call there is no guarantee that changes are written back before the object is destroyed. If *offset* and *size* are specified, only changes to the given range of bytes will be flushed to disk; otherwise, the whole extent of the mapping is flushed. *offset* must be a multiple of the `PAGESIZE` or `ALLOCATIONGRANULARITY`. `None` is returned to indicate success. An exception is raised when the call failed. Changed in version 3.8: Previously, a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix. `madvise(option[, start[, length]])` Send advice *option* to the kernel about the memory region beginning at *start* and extending *length* bytes. *option* must be one of the [MADV\_\* constants](#madvise-constants) available on the system. If *start* and *length* are omitted, the entire mapping is spanned. On some systems (including Linux), *start* must be a multiple of the `PAGESIZE`. Availability: Systems with the `madvise()` system call. New in version 3.8. `move(dest, src, count)` Copy the *count* bytes starting at offset *src* to the destination index *dest*. If the mmap was created with `ACCESS_READ`, then calls to move will raise a [`TypeError`](exceptions#TypeError "TypeError") exception. `read([n])` Return a [`bytes`](stdtypes#bytes "bytes") containing up to *n* bytes starting from the current file position. If the argument is omitted, `None` or negative, return all bytes from the current file position to the end of the mapping. The file position is updated to point after the bytes that were returned. Changed in version 3.3: Argument can be omitted or `None`. `read_byte()` Returns a byte at the current file position as an integer, and advances the file position by 1. `readline()` Returns a single line, starting at the current file position and up to the next newline. The file position is updated to point after the bytes that were returned. `resize(newsize)` Resizes the map and the underlying file, if any. If the mmap was created with `ACCESS_READ` or `ACCESS_COPY`, resizing the map will raise a [`TypeError`](exceptions#TypeError "TypeError") exception. `rfind(sub[, start[, end]])` Returns the highest index in the object where the subsequence *sub* is found, such that *sub* is contained in the range [*start*, *end*]. Optional arguments *start* and *end* are interpreted as in slice notation. Returns `-1` on failure. Changed in version 3.5: Writable [bytes-like object](../glossary#term-bytes-like-object) is now accepted. `seek(pos[, whence])` Set the file’s current position. *whence* argument is optional and defaults to `os.SEEK_SET` or `0` (absolute file positioning); other values are `os.SEEK_CUR` or `1` (seek relative to the current position) and `os.SEEK_END` or `2` (seek relative to the file’s end). `size()` Return the length of the file, which can be larger than the size of the memory-mapped area. `tell()` Returns the current position of the file pointer. `write(bytes)` Write the bytes in *bytes* into memory at the current position of the file pointer and return the number of bytes written (never less than `len(bytes)`, since if the write fails, a [`ValueError`](exceptions#ValueError "ValueError") will be raised). The file position is updated to point after the bytes that were written. If the mmap was created with `ACCESS_READ`, then writing to it will raise a [`TypeError`](exceptions#TypeError "TypeError") exception. Changed in version 3.5: Writable [bytes-like object](../glossary#term-bytes-like-object) is now accepted. Changed in version 3.6: The number of bytes written is now returned. `write_byte(byte)` Write the integer *byte* into memory at the current position of the file pointer; the file position is advanced by `1`. If the mmap was created with `ACCESS_READ`, then writing to it will raise a [`TypeError`](exceptions#TypeError "TypeError") exception. MADV\_\* Constants ------------------ `mmap.MADV_NORMAL` `mmap.MADV_RANDOM` `mmap.MADV_SEQUENTIAL` `mmap.MADV_WILLNEED` `mmap.MADV_DONTNEED` `mmap.MADV_REMOVE` `mmap.MADV_DONTFORK` `mmap.MADV_DOFORK` `mmap.MADV_HWPOISON` `mmap.MADV_MERGEABLE` `mmap.MADV_UNMERGEABLE` `mmap.MADV_SOFT_OFFLINE` `mmap.MADV_HUGEPAGE` `mmap.MADV_NOHUGEPAGE` `mmap.MADV_DONTDUMP` `mmap.MADV_DODUMP` `mmap.MADV_FREE` `mmap.MADV_NOSYNC` `mmap.MADV_AUTOSYNC` `mmap.MADV_NOCORE` `mmap.MADV_CORE` `mmap.MADV_PROTECT` These options can be passed to [`mmap.madvise()`](#mmap.mmap.madvise "mmap.mmap.madvise"). Not every option will be present on every system. Availability: Systems with the madvise() system call. New in version 3.8.
programming_docs
python tkinter.colorchooser — Color choosing dialog tkinter.colorchooser — Color choosing dialog ============================================ **Source code:** [Lib/tkinter/colorchooser.py](https://github.com/python/cpython/tree/3.9/Lib/tkinter/colorchooser.py) The [`tkinter.colorchooser`](#module-tkinter.colorchooser "tkinter.colorchooser: Color choosing dialog (Tk)") module provides the [`Chooser`](#tkinter.colorchooser.Chooser "tkinter.colorchooser.Chooser") class as an interface to the native color picker dialog. `Chooser` implements a modal color choosing dialog window. The `Chooser` class inherits from the [`Dialog`](dialog#tkinter.commondialog.Dialog "tkinter.commondialog.Dialog") class. `class tkinter.colorchooser.Chooser(master=None, **options)` `tkinter.colorchooser.askcolor(color=None, **options)` Create a color choosing dialog. A call to this method will show the window, wait for the user to make a selection, and return the selected color (or `None`) to the caller. See also `Module` [`tkinter.commondialog`](dialog#module-tkinter.commondialog "tkinter.commondialog: Tkinter base class for dialogs (Tk)") Tkinter standard dialog module python venv — Creation of virtual environments venv — Creation of virtual environments ======================================= New in version 3.3. **Source code:** [Lib/venv/](https://github.com/python/cpython/tree/3.9/Lib/venv/) The [`venv`](#module-venv "venv: Creation of virtual environments.") module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories. See [**PEP 405**](https://www.python.org/dev/peps/pep-0405) for more information about Python virtual environments. See also [Python Packaging User Guide: Creating and using virtual environments](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment) Creating virtual environments ----------------------------- Creation of [virtual environments](#venv-def) is done by executing the command `venv`: ``` python3 -m venv /path/to/new/virtual/environment ``` Running this command creates the target directory (creating any parent directories that don’t exist already) and places a `pyvenv.cfg` file in it with a `home` key pointing to the Python installation from which the command was run (a common name for the target directory is `.venv`). It also creates a `bin` (or `Scripts` on Windows) subdirectory containing a copy/symlink of the Python binary/binaries (as appropriate for the platform or arguments used at environment creation time). It also creates an (initially empty) `lib/pythonX.Y/site-packages` subdirectory (on Windows, this is `Lib\site-packages`). If an existing directory is specified, it will be re-used. Deprecated since version 3.6: `pyvenv` was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is [deprecated in Python 3.6](https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features). Changed in version 3.5: The use of `venv` is now recommended for creating virtual environments. On Windows, invoke the `venv` command as follows: ``` c:\>c:\Python35\python -m venv c:\path\to\myenv ``` Alternatively, if you configured the `PATH` and `PATHEXT` variables for your [Python installation](../using/windows#using-on-windows): ``` c:\>python -m venv c:\path\to\myenv ``` The command, if run with `-h`, will show the available options: ``` usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] ENV_DIR [ENV_DIR ...] Creates virtual Python environments in one or more target directories. positional arguments: ENV_DIR A directory to create the environment in. optional arguments: -h, --help show this help message and exit --system-site-packages Give the virtual environment access to the system site-packages dir. --symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform. --copies Try to use copies rather than symlinks, even when symlinks are the default for the platform. --clear Delete the contents of the environment directory if it already exists, before environment creation. --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place. --without-pip Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default) --prompt PROMPT Provides an alternative prompt prefix for this environment. --upgrade-deps Upgrade core dependencies: pip setuptools to the latest version in PyPI Once an environment has been created, you may wish to activate it, e.g. by sourcing an activate script in its bin directory. ``` Changed in version 3.9: Add `--upgrade-deps` option to upgrade pip + setuptools to the latest on PyPI Changed in version 3.4: Installs pip by default, added the `--without-pip` and `--copies` options Changed in version 3.4: In earlier versions, if the target directory already existed, an error was raised, unless the `--clear` or `--upgrade` option was provided. Note While symlinks are supported on Windows, they are not recommended. Of particular note is that double-clicking `python.exe` in File Explorer will resolve the symlink eagerly and ignore the virtual environment. Note On Microsoft Windows, it may be required to enable the `Activate.ps1` script by setting the execution policy for the user. You can do this by issuing the following PowerShell command: PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser See [About Execution Policies](https://go.microsoft.com/fwlink/?LinkID=135170) for more information. The created `pyvenv.cfg` file also includes the `include-system-site-packages` key, set to `true` if `venv` is run with the `--system-site-packages` option, `false` otherwise. Unless the `--without-pip` option is given, [`ensurepip`](ensurepip#module-ensurepip "ensurepip: Bootstrapping the \"pip\" installer into an existing Python installation or virtual environment.") will be invoked to bootstrap `pip` into the virtual environment. Multiple paths can be given to `venv`, in which case an identical virtual environment will be created, according to the given options, at each provided path. Once a virtual environment has been created, it can be “activated” using a script in the virtual environment’s binary directory. The invocation of the script is platform-specific (`<venv>` must be replaced by the path of the directory containing the virtual environment): | Platform | Shell | Command to activate virtual environment | | --- | --- | --- | | POSIX | bash/zsh | $ source <venv>/bin/activate | | | fish | $ source <venv>/bin/activate.fish | | | csh/tcsh | $ source <venv>/bin/activate.csh | | | PowerShell Core | $ <venv>/bin/Activate.ps1 | | Windows | cmd.exe | C:\> <venv>\Scripts\activate.bat | | | PowerShell | PS C:\> <venv>\Scripts\Activate.ps1 | When a virtual environment is active, the `VIRTUAL_ENV` environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment. You don’t specifically *need* to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically. You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used). New in version 3.4: `fish` and `csh` activation scripts. New in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Core support. Note A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system. A virtual environment is a directory tree which contains Python executable files and other files which indicate that it is a virtual environment. Common installation tools such as [setuptools](https://pypi.org/project/setuptools/) and [pip](https://pypi.org/project/pip/) work as expected with virtual environments. In other words, when a virtual environment is active, they install Python packages into the virtual environment without needing to be told to do so explicitly. When a virtual environment is active (i.e., the virtual environment’s Python interpreter is running), the attributes [`sys.prefix`](sys#sys.prefix "sys.prefix") and [`sys.exec_prefix`](sys#sys.exec_prefix "sys.exec_prefix") point to the base directory of the virtual environment, whereas [`sys.base_prefix`](sys#sys.base_prefix "sys.base_prefix") and [`sys.base_exec_prefix`](sys#sys.base_exec_prefix "sys.base_exec_prefix") point to the non-virtual environment Python installation which was used to create the virtual environment. If a virtual environment is not active, then [`sys.prefix`](sys#sys.prefix "sys.prefix") is the same as [`sys.base_prefix`](sys#sys.base_prefix "sys.base_prefix") and [`sys.exec_prefix`](sys#sys.exec_prefix "sys.exec_prefix") is the same as [`sys.base_exec_prefix`](sys#sys.base_exec_prefix "sys.base_exec_prefix") (they all point to a non-virtual environment Python installation). When a virtual environment is active, any options that change the installation path will be ignored from all [`distutils`](distutils#module-distutils "distutils: Support for building and installing Python modules into an existing Python installation.") configuration files to prevent projects being inadvertently installed outside of the virtual environment. When working in a command shell, users can make a virtual environment active by running an `activate` script in the virtual environment’s executables directory (the precise filename and command to use the file is shell-dependent), which prepends the virtual environment’s directory for executables to the `PATH` environment variable for the running shell. There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter. This means that the script will run with that interpreter regardless of the value of `PATH`. On Windows, “shebang” line processing is supported if you have the Python Launcher for Windows installed (this was added to Python in 3.3 - see [**PEP 397**](https://www.python.org/dev/peps/pep-0397) for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in `PATH`. API --- The high-level method described above makes use of a simple API which provides mechanisms for third-party virtual environment creators to customize environment creation according to their needs, the [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") class. `class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False)` The [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") class accepts the following keyword arguments on instantiation: * `system_site_packages` – a Boolean value indicating that the system Python site-packages should be available to the environment (defaults to `False`). * `clear` – a Boolean value which, if true, will delete the contents of any existing target directory, before creating the environment. * `symlinks` – a Boolean value indicating whether to attempt to symlink the Python binary rather than copying. * `upgrade` – a Boolean value which, if true, will upgrade an existing environment with the running Python - for use when that Python has been upgraded in-place (defaults to `False`). * `with_pip` – a Boolean value which, if true, ensures pip is installed in the virtual environment. This uses [`ensurepip`](ensurepip#module-ensurepip "ensurepip: Bootstrapping the \"pip\" installer into an existing Python installation or virtual environment.") with the `--default-pip` option. * `prompt` – a String to be used after virtual environment is activated (defaults to `None` which means directory name of the environment would be used). If the special string `"."` is provided, the basename of the current directory is used as the prompt. * `upgrade_deps` – Update the base venv modules to the latest on PyPI Changed in version 3.4: Added the `with_pip` parameter New in version 3.6: Added the `prompt` parameter New in version 3.9: Added the `upgrade_deps` parameter Creators of third-party virtual environment tools will be free to use the provided [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") class as a base class. The returned env-builder is an object which has a method, `create`: `create(env_dir)` Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The `create` method will either create the environment in the specified directory, or raise an appropriate exception. The `create` method of the [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") class illustrates the hooks available for subclass customization: ``` def create(self, env_dir): """ Create a virtualized Python environment in a directory. env_dir is the target directory to create an environment in. """ env_dir = os.path.abspath(env_dir) context = self.ensure_directories(env_dir) self.create_configuration(context) self.setup_python(context) self.setup_scripts(context) self.post_setup(context) ``` Each of the methods [`ensure_directories()`](#venv.EnvBuilder.ensure_directories "venv.EnvBuilder.ensure_directories"), [`create_configuration()`](#venv.EnvBuilder.create_configuration "venv.EnvBuilder.create_configuration"), [`setup_python()`](#venv.EnvBuilder.setup_python "venv.EnvBuilder.setup_python"), [`setup_scripts()`](#venv.EnvBuilder.setup_scripts "venv.EnvBuilder.setup_scripts") and [`post_setup()`](#venv.EnvBuilder.post_setup "venv.EnvBuilder.post_setup") can be overridden. `ensure_directories(env_dir)` Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either `clear` or `upgrade` were specified to allow operating on an existing environment directory. `create_configuration(context)` Creates the `pyvenv.cfg` configuration file in the environment. `setup_python(context)` Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable `python3.x` was used, symlinks to `python` and `python3` will be created pointing to that executable, unless files with those names already exist. `setup_scripts(context)` Installs activation scripts appropriate to the platform into the virtual environment. `upgrade_dependencies(context)` Upgrades the core venv dependency packages (currently `pip` and `setuptools`) in the environment. This is done by shelling out to the `pip` executable in the environment. New in version 3.9. `post_setup(context)` A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. Changed in version 3.7.2: Windows now uses redirector scripts for `python[w].exe` instead of copying the actual binaries. In 3.7.2 only [`setup_python()`](#venv.EnvBuilder.setup_python "venv.EnvBuilder.setup_python") does nothing unless running from a build in the source tree. Changed in version 3.7.3: Windows copies the redirector scripts as part of [`setup_python()`](#venv.EnvBuilder.setup_python "venv.EnvBuilder.setup_python") instead of [`setup_scripts()`](#venv.EnvBuilder.setup_scripts "venv.EnvBuilder.setup_scripts"). This was not the case in 3.7.2. When using symlinks, the original executables will be linked. In addition, [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") provides this utility method that can be called from [`setup_scripts()`](#venv.EnvBuilder.setup_scripts "venv.EnvBuilder.setup_scripts") or [`post_setup()`](#venv.EnvBuilder.post_setup "venv.EnvBuilder.post_setup") in subclasses to assist in installing custom scripts into the virtual environment. `install_scripts(context, path)` *path* is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to [`os.name`](os#os.name "os.name") are copied after some text replacement of placeholders: * `__VENV_DIR__` is replaced with the absolute path of the environment directory. * `__VENV_NAME__` is replaced with the environment name (final path segment of environment directory). * `__VENV_PROMPT__` is replaced with the prompt (the environment name surrounded by parentheses and with a following space) * `__VENV_BIN_NAME__` is replaced with the name of the bin directory (either `bin` or `Scripts`). * `__VENV_PYTHON__` is replaced with the absolute path of the environment’s executable. The directories are allowed to exist (for when an existing environment is being upgraded). There is also a module-level convenience function: `venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)` Create an [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") with the given keyword arguments, and call its [`create()`](#venv.EnvBuilder.create "venv.EnvBuilder.create") method with the *env\_dir* argument. New in version 3.3. Changed in version 3.4: Added the `with_pip` parameter Changed in version 3.6: Added the `prompt` parameter An example of extending `EnvBuilder` ------------------------------------ The following script shows how to extend [`EnvBuilder`](#venv.EnvBuilder "venv.EnvBuilder") by implementing a subclass which installs setuptools and pip into a created virtual environment: ``` import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlparse from urllib.request import urlretrieve import venv class ExtendedEnvBuilder(venv.EnvBuilder): """ This builder installs setuptools and pip so that you can pip or easy_install other packages into the created virtual environment. :param nodist: If true, setuptools and pip are not installed into the created virtual environment. :param nopip: If true, pip is not installed into the created virtual environment. :param progress: If setuptools or pip are installed, the progress of the installation can be monitored by passing a progress callable. If specified, it is called with two arguments: a string indicating some progress, and a context indicating where the string is coming from. The context argument can have one of three values: 'main', indicating that it is called from virtualize() itself, and 'stdout' and 'stderr', which are obtained by reading lines from the output streams of a subprocess which is used to install the app. If a callable is not specified, default progress information is output to sys.stderr. """ def __init__(self, *args, **kwargs): self.nodist = kwargs.pop('nodist', False) self.nopip = kwargs.pop('nopip', False) self.progress = kwargs.pop('progress', None) self.verbose = kwargs.pop('verbose', False) super().__init__(*args, **kwargs) def post_setup(self, context): """ Set up any packages which need to be pre-installed into the virtual environment being created. :param context: The information for the virtual environment creation request being processed. """ os.environ['VIRTUAL_ENV'] = context.env_dir if not self.nodist: self.install_setuptools(context) # Can't install pip without setuptools if not self.nopip and not self.nodist: self.install_pip(context) def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress while True: s = stream.readline() if not s: break if progress is not None: progress(s, context) else: if not self.verbose: sys.stderr.write('.') else: sys.stderr.write(s.decode('utf-8')) sys.stderr.flush() stream.close() def install_script(self, context, name, url): _, _, path, _, _, _ = urlparse(url) fn = os.path.split(path)[-1] binpath = context.bin_path distpath = os.path.join(binpath, fn) # Download script into the virtual environment's binaries folder urlretrieve(url, distpath) progress = self.progress if self.verbose: term = '\n' else: term = '' if progress is not None: progress('Installing %s ...%s' % (name, term), 'main') else: sys.stderr.write('Installing %s ...%s' % (name, term)) sys.stderr.flush() # Install in the virtual environment args = [context.env_exe, fn] p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) t1.start() t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) t2.start() p.wait() t1.join() t2.join() if progress is not None: progress('done.', 'main') else: sys.stderr.write('done.\n') # Clean up - no longer needed os.unlink(distpath) def install_setuptools(self, context): """ Install setuptools in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py' self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: f = os.path.join(context.bin_path, f) os.unlink(f) def install_pip(self, context): """ Install pip in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = 'https://bootstrap.pypa.io/get-pip.py' self.install_script(context, 'pip', url) def main(args=None): compatible = True if sys.version_info < (3, 3): compatible = False elif not hasattr(sys, 'base_prefix'): compatible = False if not compatible: raise ValueError('This script is only for use with ' 'Python 3.3 or later') else: import argparse parser = argparse.ArgumentParser(prog=__name__, description='Creates virtual Python ' 'environments in one or ' 'more target ' 'directories.') parser.add_argument('dirs', metavar='ENV_DIR', nargs='+', help='A directory in which to create the ' 'virtual environment.') parser.add_argument('--no-setuptools', default=False, action='store_true', dest='nodist', help="Don't install setuptools or pip in the " "virtual environment.") parser.add_argument('--no-pip', default=False, action='store_true', dest='nopip', help="Don't install pip in the virtual " "environment.") parser.add_argument('--system-site-packages', default=False, action='store_true', dest='system_site', help='Give the virtual environment access to the ' 'system site-packages dir.') if os.name == 'nt': use_symlinks = False else: use_symlinks = True parser.add_argument('--symlinks', default=use_symlinks, action='store_true', dest='symlinks', help='Try to use symlinks rather than copies, ' 'when symlinks are not the default for ' 'the platform.') parser.add_argument('--clear', default=False, action='store_true', dest='clear', help='Delete the contents of the ' 'virtual environment ' 'directory if it already ' 'exists, before virtual ' 'environment creation.') parser.add_argument('--upgrade', default=False, action='store_true', dest='upgrade', help='Upgrade the virtual ' 'environment directory to ' 'use this version of ' 'Python, assuming Python ' 'has been upgraded ' 'in-place.') parser.add_argument('--verbose', default=False, action='store_true', dest='verbose', help='Display the output ' 'from the scripts which ' 'install setuptools and pip.') options = parser.parse_args(args) if options.upgrade and options.clear: raise ValueError('you cannot supply --upgrade and --clear together.') builder = ExtendedEnvBuilder(system_site_packages=options.system_site, clear=options.clear, symlinks=options.symlinks, upgrade=options.upgrade, nodist=options.nodist, nopip=options.nopip, verbose=options.verbose) for d in options.dirs: builder.create(d) if __name__ == '__main__': rc = 1 try: main() rc = 0 except Exception as e: print('Error: %s' % e, file=sys.stderr) sys.exit(rc) ``` This script is also available for download [online](https://gist.github.com/vsajip/4673395).
programming_docs
python contextvars — Context Variables contextvars — Context Variables =============================== This module provides APIs to manage, store, and access context-local state. The [`ContextVar`](#contextvars.ContextVar "contextvars.ContextVar") class is used to declare and work with *Context Variables*. The [`copy_context()`](#contextvars.copy_context "contextvars.copy_context") function and the [`Context`](#contextvars.Context "contextvars.Context") class should be used to manage the current context in asynchronous frameworks. Context managers that have state should use Context Variables instead of [`threading.local()`](threading#threading.local "threading.local") to prevent their state from bleeding to other code unexpectedly, when used in concurrent code. See also [**PEP 567**](https://www.python.org/dev/peps/pep-0567) for additional details. New in version 3.7. Context Variables ----------------- `class contextvars.ContextVar(name[, *, default])` This class is used to declare a new Context Variable, e.g.: ``` var: ContextVar[int] = ContextVar('var', default=42) ``` The required *name* parameter is used for introspection and debug purposes. The optional keyword-only *default* parameter is returned by [`ContextVar.get()`](#contextvars.ContextVar.get "contextvars.ContextVar.get") when no value for the variable is found in the current context. **Important:** Context Variables should be created at the top module level and never in closures. [`Context`](#contextvars.Context "contextvars.Context") objects hold strong references to context variables which prevents context variables from being properly garbage collected. `name` The name of the variable. This is a read-only property. New in version 3.7.1. `get([default])` Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will: * return the value of the *default* argument of the method, if provided; or * return the default value for the context variable, if it was created with one; or * raise a [`LookupError`](exceptions#LookupError "LookupError"). `set(value)` Call to set a new value for the context variable in the current context. The required *value* argument is the new value for the context variable. Returns a [`Token`](#contextvars.Token "contextvars.Token") object that can be used to restore the variable to its previous value via the [`ContextVar.reset()`](#contextvars.ContextVar.reset "contextvars.ContextVar.reset") method. `reset(token)` Reset the context variable to the value it had before the [`ContextVar.set()`](#contextvars.ContextVar.set "contextvars.ContextVar.set") that created the *token* was used. For example: ``` var = ContextVar('var') token = var.set('new value') # code that uses 'var'; var.get() returns 'new value'. var.reset(token) # After the reset call the var has no value again, so # var.get() would raise a LookupError. ``` `class contextvars.Token` *Token* objects are returned by the [`ContextVar.set()`](#contextvars.ContextVar.set "contextvars.ContextVar.set") method. They can be passed to the [`ContextVar.reset()`](#contextvars.ContextVar.reset "contextvars.ContextVar.reset") method to revert the value of the variable to what it was before the corresponding *set*. `var` A read-only property. Points to the [`ContextVar`](#contextvars.ContextVar "contextvars.ContextVar") object that created the token. `old_value` A read-only property. Set to the value the variable had before the [`ContextVar.set()`](#contextvars.ContextVar.set "contextvars.ContextVar.set") method call that created the token. It points to [`Token.MISSING`](#contextvars.Token.MISSING "contextvars.Token.MISSING") is the variable was not set before the call. `MISSING` A marker object used by [`Token.old_value`](#contextvars.Token.old_value "contextvars.Token.old_value"). Manual Context Management ------------------------- `contextvars.copy_context()` Returns a copy of the current [`Context`](#contextvars.Context "contextvars.Context") object. The following snippet gets a copy of the current context and prints all variables and their values that are set in it: ``` ctx: Context = copy_context() print(list(ctx.items())) ``` The function has an O(1) complexity, i.e. works equally fast for contexts with a few context variables and for contexts that have a lot of them. `class contextvars.Context` A mapping of [`ContextVars`](#contextvars.ContextVar "contextvars.ContextVar") to their values. `Context()` creates an empty context with no values in it. To get a copy of the current context use the [`copy_context()`](#contextvars.copy_context "contextvars.copy_context") function. Context implements the [`collections.abc.Mapping`](collections.abc#collections.abc.Mapping "collections.abc.Mapping") interface. `run(callable, *args, **kwargs)` Execute `callable(*args, **kwargs)` code in the context object the *run* method is called on. Return the result of the execution or propagate an exception if one occurred. Any changes to any context variables that *callable* makes will be contained in the context object: ``` var = ContextVar('var') var.set('spam') def main(): # 'var' was set to 'spam' before # calling 'copy_context()' and 'ctx.run(main)', so: # var.get() == ctx[var] == 'spam' var.set('ham') # Now, after setting 'var' to 'ham': # var.get() == ctx[var] == 'ham' ctx = copy_context() # Any changes that the 'main' function makes to 'var' # will be contained in 'ctx'. ctx.run(main) # The 'main()' function was run in the 'ctx' context, # so changes to 'var' are contained in it: # ctx[var] == 'ham' # However, outside of 'ctx', 'var' is still set to 'spam': # var.get() == 'spam' ``` The method raises a [`RuntimeError`](exceptions#RuntimeError "RuntimeError") when called on the same context object from more than one OS thread, or when called recursively. `copy()` Return a shallow copy of the context object. `var in context` Return `True` if the *context* has a value for *var* set; return `False` otherwise. `context[var]` Return the value of the *var* [`ContextVar`](#contextvars.ContextVar "contextvars.ContextVar") variable. If the variable is not set in the context object, a [`KeyError`](exceptions#KeyError "KeyError") is raised. `get(var[, default])` Return the value for *var* if *var* has the value in the context object. Return *default* otherwise. If *default* is not given, return `None`. `iter(context)` Return an iterator over the variables stored in the context object. `len(proxy)` Return the number of variables set in the context object. `keys()` Return a list of all variables in the context object. `values()` Return a list of all variables’ values in the context object. `items()` Return a list of 2-tuples containing all variables and their values in the context object. asyncio support --------------- Context variables are natively supported in [`asyncio`](asyncio#module-asyncio "asyncio: Asynchronous I/O.") and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client: ``` import asyncio import contextvars client_addr_var = contextvars.ContextVar('client_addr') def render_goodbye(): # The address of the currently handled client can be accessed # without passing it explicitly to this function. client_addr = client_addr_var.get() return f'Good bye, client @ {client_addr}\n'.encode() async def handle_request(reader, writer): addr = writer.transport.get_extra_info('socket').getpeername() client_addr_var.set(addr) # In any code that we call is now possible to get # client's address by calling 'client_addr_var.get()'. while True: line = await reader.readline() print(line) if not line.strip(): break writer.write(line) writer.write(render_goodbye()) writer.close() async def main(): srv = await asyncio.start_server( handle_request, '127.0.0.1', 8081) async with srv: await srv.serve_forever() asyncio.run(main()) # To test it you can use telnet: # telnet 127.0.0.1 8081 ``` python builtins — Built-in objects builtins — Built-in objects =========================== This module provides direct access to all ‘built-in’ identifiers of Python; for example, `builtins.open` is the full name for the built-in function [`open()`](functions#open "open"). See [Built-in Functions](functions#built-in-funcs) and [Built-in Constants](constants#built-in-consts) for documentation. This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an [`open()`](functions#open "open") function that wraps the built-in [`open()`](functions#open "open"), this module can be used directly: ``` import builtins def open(path): f = builtins.open(path, 'r') return UpperCaser(f) class UpperCaser: '''Wrapper around a file that converts output to upper-case.''' def __init__(self, f): self._f = f def read(self, count=-1): return self._f.read(count).upper() # ... ``` As an implementation detail, most modules have the name `__builtins__` made available as part of their globals. The value of `__builtins__` is normally either this module or the value of this module’s [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python. python binascii — Convert between binary and ASCII binascii — Convert between binary and ASCII =========================================== The [`binascii`](#module-binascii "binascii: Tools for converting between binary and various ASCII-encoded binary representations.") module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like [`uu`](uu#module-uu "uu: Encode and decode files in uuencode format. (deprecated)"), [`base64`](base64#module-base64 "base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85"), or [`binhex`](binhex#module-binhex "binhex: Encode and decode files in binhex4 format.") instead. The [`binascii`](#module-binascii "binascii: Tools for converting between binary and various ASCII-encoded binary representations.") module contains low-level functions written in C for greater speed that are used by the higher-level modules. Note `a2b_*` functions accept Unicode strings containing only ASCII characters. Other functions only accept [bytes-like objects](../glossary#term-bytes-like-object) (such as [`bytes`](stdtypes#bytes "bytes"), [`bytearray`](stdtypes#bytearray "bytearray") and other objects that support the buffer protocol). Changed in version 3.3: ASCII-only unicode strings are now accepted by the `a2b_*` functions. The [`binascii`](#module-binascii "binascii: Tools for converting between binary and various ASCII-encoded binary representations.") module defines the following functions: `binascii.a2b_uu(string)` Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace. `binascii.b2a_uu(data, *, backtick=False)` Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of *data* should be at most 45. If *backtick* is true, zeros are represented by `'`'` instead of spaces. Changed in version 3.7: Added the *backtick* parameter. `binascii.a2b_base64(string)` Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time. `binascii.b2a_base64(data, *, newline=True)` Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if *newline* is true. The output of this function conforms to [**RFC 3548**](https://tools.ietf.org/html/rfc3548.html). Changed in version 3.6: Added the *newline* parameter. `binascii.a2b_qp(data, header=False)` Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument *header* is present and true, underscores will be decoded as spaces. `binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)` Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument *quotetabs* is present and true, all tabs and spaces will be encoded. If the optional argument *istext* is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument *header* is present and true, spaces will be encoded as underscores per [**RFC 1522**](https://tools.ietf.org/html/rfc1522.html). If the optional argument *header* is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream. `binascii.a2b_hqx(string)` Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero. Deprecated since version 3.9. `binascii.rledecode_hqx(data)` Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses `0x90` after a byte as a repeat indicator, followed by a count. A count of `0` specifies a byte value of `0x90`. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the [`Incomplete`](#binascii.Incomplete "binascii.Incomplete") exception is raised. Changed in version 3.2: Accept only bytestring or bytearray objects as input. Deprecated since version 3.9. `binascii.rlecode_hqx(data)` Perform binhex4 style RLE-compression on *data* and return the result. Deprecated since version 3.9. `binascii.b2a_hqx(data)` Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment). Deprecated since version 3.9. `binascii.crc_hqx(data, value)` Compute a 16-bit CRC value of *data*, starting with *value* as the initial CRC, and return the result. This uses the CRC-CCITT polynomial *x*16 + *x*12 + *x*5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format. `binascii.crc32(data[, value])` Compute CRC-32, the unsigned 32-bit checksum of *data*, starting with an initial CRC of *value*. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: ``` print(binascii.crc32(b"hello world")) # Or, in two pieces: crc = binascii.crc32(b"hello") crc = binascii.crc32(b" world", crc) print('crc32 = {:#010x}'.format(crc)) ``` Changed in version 3.0: The result is always unsigned. To generate the same numeric value when using Python 2 or earlier, use `crc32(data) & 0xffffffff`. `binascii.b2a_hex(data[, sep[, bytes_per_sep=1]])` `binascii.hexlify(data[, sep[, bytes_per_sep=1]])` Return the hexadecimal representation of the binary *data*. Every byte of *data* is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of *data*. Similar functionality (but returning a text string) is also conveniently accessible using the [`bytes.hex()`](stdtypes#bytes.hex "bytes.hex") method. If *sep* is specified, it must be a single character str or bytes object. It will be inserted in the output after every *bytes\_per\_sep* input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative *bytes\_per\_sep* value. ``` >>> import binascii >>> binascii.b2a_hex(b'\xb9\x01\xef') b'b901ef' >>> binascii.hexlify(b'\xb9\x01\xef', '-') b'b9-01-ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) b'b9_01ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) b'b901 ef' ``` Changed in version 3.8: The *sep* and *bytes\_per\_sep* parameters were added. `binascii.a2b_hex(hexstr)` `binascii.unhexlify(hexstr)` Return the binary data represented by the hexadecimal string *hexstr*. This function is the inverse of [`b2a_hex()`](#binascii.b2a_hex "binascii.b2a_hex"). *hexstr* must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an [`Error`](#binascii.Error "binascii.Error") exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the [`bytes.fromhex()`](stdtypes#bytes.fromhex "bytes.fromhex") class method. `exception binascii.Error` Exception raised on errors. These are usually programming errors. `exception binascii.Incomplete` Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again. See also `Module` [`base64`](base64#module-base64 "base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85") Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85. `Module` [`binhex`](binhex#module-binhex "binhex: Encode and decode files in binhex4 format.") Support for the binhex format used on the Macintosh. `Module` [`uu`](uu#module-uu "uu: Encode and decode files in uuencode format. (deprecated)") Support for UU encoding used on Unix. `Module` [`quopri`](quopri#module-quopri "quopri: Encode and decode files using the MIME quoted-printable encoding.") Support for quoted-printable encoding used in MIME email messages. python multiprocessing — Process-based parallelism multiprocessing — Process-based parallelism =========================================== **Source code:** [Lib/multiprocessing/](https://github.com/python/cpython/tree/3.9/Lib/multiprocessing/) Introduction ------------ [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") is a package that supports spawning processes using an API similar to the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module. The [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") package offers both local and remote concurrency, effectively side-stepping the [Global Interpreter Lock](../glossary#term-global-interpreter-lock) by using subprocesses instead of threads. Due to this, the [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows. The [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") module also introduces APIs which do not have analogs in the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module. A prime example of this is the [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") object which offers a convenient means of parallelizing the execution of a function across multiple input values, distributing the input data across processes (data parallelism). The following example demonstrates the common practice of defining such functions in a module so that child processes can successfully import that module. This basic example of data parallelism using [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool"), ``` from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(5) as p: print(p.map(f, [1, 2, 3])) ``` will print to standard output ``` [1, 4, 9] ``` ### The [`Process`](#multiprocessing.Process "multiprocessing.Process") class In [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism."), processes are spawned by creating a [`Process`](#multiprocessing.Process "multiprocessing.Process") object and then calling its [`start()`](#multiprocessing.Process.start "multiprocessing.Process.start") method. [`Process`](#multiprocessing.Process "multiprocessing.Process") follows the API of [`threading.Thread`](threading#threading.Thread "threading.Thread"). A trivial example of a multiprocess program is ``` from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` To show the individual process IDs involved, here is an expanded example: ``` from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__) print('parent process:', os.getppid()) print('process id:', os.getpid()) def f(name): info('function f') print('hello', name) if __name__ == '__main__': info('main line') p = Process(target=f, args=('bob',)) p.start() p.join() ``` For an explanation of why the `if __name__ == '__main__'` part is necessary, see [Programming guidelines](#multiprocessing-programming). ### Contexts and start methods Depending on the platform, [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") supports three ways to start a process. These *start methods* are *spawn* The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the process object’s [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run") method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using *fork* or *forkserver*. Available on Unix and Windows. The default on Windows and macOS. *fork* The parent process uses [`os.fork()`](os#os.fork "os.fork") to fork the Python interpreter. The child process, when it begins, is effectively identical to the parent process. All resources of the parent are inherited by the child process. Note that safely forking a multithreaded process is problematic. Available on Unix only. The default on Unix. *forkserver* When the program starts and selects the *forkserver* start method, a server process is started. From then on, whenever a new process is needed, the parent process connects to the server and requests that it fork a new process. The fork server process is single threaded so it is safe for it to use [`os.fork()`](os#os.fork "os.fork"). No unnecessary resources are inherited. Available on Unix platforms which support passing file descriptors over Unix pipes. Changed in version 3.8: On macOS, the *spawn* start method is now the default. The *fork* start method should be considered unsafe as it can lead to crashes of the subprocess. See [bpo-33725](https://bugs.python.org/issue?@action=redirect&bpo=33725). Changed in version 3.4: *spawn* added on all unix platforms, and *forkserver* added for some unix platforms. Child processes no longer inherit all of the parents inheritable handles on Windows. On Unix using the *spawn* or *forkserver* start methods will also start a *resource tracker* process which tracks the unlinked named system resources (such as named semaphores or [`SharedMemory`](multiprocessing.shared_memory#multiprocessing.shared_memory.SharedMemory "multiprocessing.shared_memory.SharedMemory") objects) created by processes of the program. When all processes have exited the resource tracker unlinks any remaining tracked object. Usually there should be none, but if a process was killed by a signal there may be some “leaked” resources. (Neither leaked semaphores nor shared memory segments will be automatically unlinked until the next reboot. This is problematic for both objects because the system allows only a limited number of named semaphores, and shared memory segments occupy some space in the main memory.) To select a start method you use the [`set_start_method()`](#multiprocessing.set_start_method "multiprocessing.set_start_method") in the `if __name__ == '__main__'` clause of the main module. For example: ``` import multiprocessing as mp def foo(q): q.put('hello') if __name__ == '__main__': mp.set_start_method('spawn') q = mp.Queue() p = mp.Process(target=foo, args=(q,)) p.start() print(q.get()) p.join() ``` [`set_start_method()`](#multiprocessing.set_start_method "multiprocessing.set_start_method") should not be used more than once in the program. Alternatively, you can use [`get_context()`](#multiprocessing.get_context "multiprocessing.get_context") to obtain a context object. Context objects have the same API as the multiprocessing module, and allow one to use multiple start methods in the same program. ``` import multiprocessing as mp def foo(q): q.put('hello') if __name__ == '__main__': ctx = mp.get_context('spawn') q = ctx.Queue() p = ctx.Process(target=foo, args=(q,)) p.start() print(q.get()) p.join() ``` Note that objects related to one context may not be compatible with processes for a different context. In particular, locks created using the *fork* context cannot be passed to processes started using the *spawn* or *forkserver* start methods. A library which wants to use a particular start method should probably use [`get_context()`](#multiprocessing.get_context "multiprocessing.get_context") to avoid interfering with the choice of the library user. Warning The `'spawn'` and `'forkserver'` start methods cannot currently be used with “frozen” executables (i.e., binaries produced by packages like **PyInstaller** and **cx\_Freeze**) on Unix. The `'fork'` start method does work. ### Exchanging objects between processes [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") supports two types of communication channel between processes: **Queues** The [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") class is a near clone of [`queue.Queue`](queue#queue.Queue "queue.Queue"). For example: ``` from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get()) # prints "[42, None, 'hello']" p.join() ``` Queues are thread and process safe. **Pipes** The [`Pipe()`](#multiprocessing.Pipe "multiprocessing.Pipe") function returns a pair of connection objects connected by a pipe which by default is duplex (two-way). For example: ``` from multiprocessing import Process, Pipe def f(conn): conn.send([42, None, 'hello']) conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) # prints "[42, None, 'hello']" p.join() ``` The two connection objects returned by [`Pipe()`](#multiprocessing.Pipe "multiprocessing.Pipe") represent the two ends of the pipe. Each connection object has `send()` and `recv()` methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the *same* end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time. ### Synchronization between processes [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") contains equivalents of all the synchronization primitives from [`threading`](threading#module-threading "threading: Thread-based parallelism."). For instance one can use a lock to ensure that only one process prints to standard output at a time: ``` from multiprocessing import Process, Lock def f(l, i): l.acquire() try: print('hello world', i) finally: l.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start() ``` Without using the lock output from the different processes is liable to get all mixed up. ### Sharing state between processes As mentioned above, when doing concurrent programming it is usually best to avoid using shared state as far as possible. This is particularly true when using multiple processes. However, if you really do need to use some shared data then [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") provides a couple of ways of doing so. **Shared memory** Data can be stored in a shared memory map using [`Value`](#multiprocessing.Value "multiprocessing.Value") or [`Array`](#multiprocessing.Array "multiprocessing.Array"). For example, the following code ``` from multiprocessing import Process, Value, Array def f(n, a): n.value = 3.1415927 for i in range(len(a)): a[i] = -a[i] if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) p = Process(target=f, args=(num, arr)) p.start() p.join() print(num.value) print(arr[:]) ``` will print ``` 3.1415927 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] ``` The `'d'` and `'i'` arguments used when creating `num` and `arr` are typecodes of the kind used by the [`array`](array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module: `'d'` indicates a double precision float and `'i'` indicates a signed integer. These shared objects will be process and thread-safe. For more flexibility in using shared memory one can use the [`multiprocessing.sharedctypes`](#module-multiprocessing.sharedctypes "multiprocessing.sharedctypes: Allocate ctypes objects from shared memory.") module which supports the creation of arbitrary ctypes objects allocated from shared memory. **Server process** A manager object returned by [`Manager()`](#multiprocessing.Manager "multiprocessing.Manager") controls a server process which holds Python objects and allows other processes to manipulate them using proxies. A manager returned by [`Manager()`](#multiprocessing.Manager "multiprocessing.Manager") will support types [`list`](stdtypes#list "list"), [`dict`](stdtypes#dict "dict"), [`Namespace`](#multiprocessing.managers.Namespace "multiprocessing.managers.Namespace"), [`Lock`](#multiprocessing.Lock "multiprocessing.Lock"), [`RLock`](#multiprocessing.RLock "multiprocessing.RLock"), [`Semaphore`](#multiprocessing.Semaphore "multiprocessing.Semaphore"), [`BoundedSemaphore`](#multiprocessing.BoundedSemaphore "multiprocessing.BoundedSemaphore"), [`Condition`](#multiprocessing.Condition "multiprocessing.Condition"), [`Event`](#multiprocessing.Event "multiprocessing.Event"), [`Barrier`](#multiprocessing.Barrier "multiprocessing.Barrier"), [`Queue`](#multiprocessing.Queue "multiprocessing.Queue"), [`Value`](#multiprocessing.Value "multiprocessing.Value") and [`Array`](#multiprocessing.Array "multiprocessing.Array"). For example, ``` from multiprocessing import Process, Manager def f(d, l): d[1] = '1' d['2'] = 2 d[0.25] = None l.reverse() if __name__ == '__main__': with Manager() as manager: d = manager.dict() l = manager.list(range(10)) p = Process(target=f, args=(d, l)) p.start() p.join() print(d) print(l) ``` will print ``` {0.25: None, 1: '1', '2': 2} [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ``` Server process managers are more flexible than using shared memory objects because they can be made to support arbitrary object types. Also, a single manager can be shared by processes on different computers over a network. They are, however, slower than using shared memory. ### Using a pool of workers The [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") class represents a pool of worker processes. It has methods which allows tasks to be offloaded to the worker processes in a few different ways. For example: ``` from multiprocessing import Pool, TimeoutError import time import os def f(x): return x*x if __name__ == '__main__': # start 4 worker processes with Pool(processes=4) as pool: # print "[0, 1, 4,..., 81]" print(pool.map(f, range(10))) # print same numbers in arbitrary order for i in pool.imap_unordered(f, range(10)): print(i) # evaluate "f(20)" asynchronously res = pool.apply_async(f, (20,)) # runs in *only* one process print(res.get(timeout=1)) # prints "400" # evaluate "os.getpid()" asynchronously res = pool.apply_async(os.getpid, ()) # runs in *only* one process print(res.get(timeout=1)) # prints the PID of that process # launching multiple evaluations asynchronously *may* use more processes multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)] print([res.get(timeout=1) for res in multiple_results]) # make a single worker sleep for 10 secs res = pool.apply_async(time.sleep, (10,)) try: print(res.get(timeout=1)) except TimeoutError: print("We lacked patience and got a multiprocessing.TimeoutError") print("For the moment, the pool remains available for more work") # exiting the 'with'-block has stopped the pool print("Now the pool is closed and no longer available") ``` Note that the methods of a pool should only ever be used by the process which created it. Note Functionality within this package requires that the `__main__` module be importable by the children. This is covered in [Programming guidelines](#multiprocessing-programming) however it is worth pointing out here. This means that some examples, such as the [`multiprocessing.pool.Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") examples will not work in the interactive interpreter. For example: ``` >>> from multiprocessing import Pool >>> p = Pool(5) >>> def f(x): ... return x*x ... >>> with p: ... p.map(f, [1,2,3]) Process PoolWorker-1: Process PoolWorker-2: Process PoolWorker-3: Traceback (most recent call last): AttributeError: 'module' object has no attribute 'f' AttributeError: 'module' object has no attribute 'f' AttributeError: 'module' object has no attribute 'f' ``` (If you try this it will actually output three full tracebacks interleaved in a semi-random fashion, and then you may have to stop the parent process somehow.) Reference --------- The [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") package mostly replicates the API of the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module. ### [`Process`](#multiprocessing.Process "multiprocessing.Process") and exceptions `class multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)` Process objects represent activity that is run in a separate process. The [`Process`](#multiprocessing.Process "multiprocessing.Process") class has equivalents of all the methods of [`threading.Thread`](threading#threading.Thread "threading.Thread"). The constructor should always be called with keyword arguments. *group* should always be `None`; it exists solely for compatibility with [`threading.Thread`](threading#threading.Thread "threading.Thread"). *target* is the callable object to be invoked by the [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run") method. It defaults to `None`, meaning nothing is called. *name* is the process name (see [`name`](#multiprocessing.Process.name "multiprocessing.Process.name") for more details). *args* is the argument tuple for the target invocation. *kwargs* is a dictionary of keyword arguments for the target invocation. If provided, the keyword-only *daemon* argument sets the process [`daemon`](#multiprocessing.Process.daemon "multiprocessing.Process.daemon") flag to `True` or `False`. If `None` (the default), this flag will be inherited from the creating process. By default, no arguments are passed to *target*. If a subclass overrides the constructor, it must make sure it invokes the base class constructor (`Process.__init__()`) before doing anything else to the process. Changed in version 3.3: Added the *daemon* argument. `run()` Method representing the process’s activity. You may override this method in a subclass. The standard [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run") method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the *args* and *kwargs* arguments, respectively. `start()` Start the process’s activity. This must be called at most once per process object. It arranges for the object’s [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run") method to be invoked in a separate process. `join([timeout])` If the optional argument *timeout* is `None` (the default), the method blocks until the process whose [`join()`](#multiprocessing.Process.join "multiprocessing.Process.join") method is called terminates. If *timeout* is a positive number, it blocks at most *timeout* seconds. Note that the method returns `None` if its process terminates or if the method times out. Check the process’s [`exitcode`](#multiprocessing.Process.exitcode "multiprocessing.Process.exitcode") to determine if it terminated. A process can be joined many times. A process cannot join itself because this would cause a deadlock. It is an error to attempt to join a process before it has been started. `name` The process’s name. The name is a string used for identification purposes only. It has no semantics. Multiple processes may be given the same name. The initial name is set by the constructor. If no explicit name is provided to the constructor, a name of the form ‘Process-N1:N2:…:Nk’ is constructed, where each Nk is the N-th child of its parent. `is_alive()` Return whether the process is alive. Roughly, a process object is alive from the moment the [`start()`](#multiprocessing.Process.start "multiprocessing.Process.start") method returns until the child process terminates. `daemon` The process’s daemon flag, a Boolean value. This must be set before [`start()`](#multiprocessing.Process.start "multiprocessing.Process.start") is called. The initial value is inherited from the creating process. When a process exits, it attempts to terminate all of its daemonic child processes. Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are **not** Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited. In addition to the [`threading.Thread`](threading#threading.Thread "threading.Thread") API, [`Process`](#multiprocessing.Process "multiprocessing.Process") objects also support the following attributes and methods: `pid` Return the process ID. Before the process is spawned, this will be `None`. `exitcode` The child’s exit code. This will be `None` if the process has not yet terminated. If the child’s [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run") method returned normally, the exit code will be 0. If it terminated via [`sys.exit()`](sys#sys.exit "sys.exit") with an integer argument *N*, the exit code will be *N*. If the child terminated due to an exception not caught within [`run()`](#multiprocessing.Process.run "multiprocessing.Process.run"), the exit code will be 1. If it was terminated by signal *N*, the exit code will be the negative value *-N*. `authkey` The process’s authentication key (a byte string). When [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") is initialized the main process is assigned a random string using [`os.urandom()`](os#os.urandom "os.urandom"). When a [`Process`](#multiprocessing.Process "multiprocessing.Process") object is created, it will inherit the authentication key of its parent process, although this may be changed by setting [`authkey`](#multiprocessing.Process.authkey "multiprocessing.Process.authkey") to another byte string. See [Authentication keys](#multiprocessing-auth-keys). `sentinel` A numeric handle of a system object which will become “ready” when the process ends. You can use this value if you want to wait on several events at once using [`multiprocessing.connection.wait()`](#multiprocessing.connection.wait "multiprocessing.connection.wait"). Otherwise calling [`join()`](#multiprocessing.Process.join "multiprocessing.Process.join") is simpler. On Windows, this is an OS handle usable with the `WaitForSingleObject` and `WaitForMultipleObjects` family of API calls. On Unix, this is a file descriptor usable with primitives from the [`select`](select#module-select "select: Wait for I/O completion on multiple streams.") module. New in version 3.3. `terminate()` Terminate the process. On Unix this is done using the `SIGTERM` signal; on Windows `TerminateProcess()` is used. Note that exit handlers and finally clauses, etc., will not be executed. Note that descendant processes of the process will *not* be terminated – they will simply become orphaned. Warning If this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process. Similarly, if the process has acquired a lock or semaphore etc. then terminating it is liable to cause other processes to deadlock. `kill()` Same as [`terminate()`](#multiprocessing.Process.terminate "multiprocessing.Process.terminate") but using the `SIGKILL` signal on Unix. New in version 3.7. `close()` Close the [`Process`](#multiprocessing.Process "multiprocessing.Process") object, releasing all resources associated with it. [`ValueError`](exceptions#ValueError "ValueError") is raised if the underlying process is still running. Once [`close()`](#multiprocessing.Process.close "multiprocessing.Process.close") returns successfully, most other methods and attributes of the [`Process`](#multiprocessing.Process "multiprocessing.Process") object will raise [`ValueError`](exceptions#ValueError "ValueError"). New in version 3.7. Note that the [`start()`](#multiprocessing.Process.start "multiprocessing.Process.start"), [`join()`](#multiprocessing.Process.join "multiprocessing.Process.join"), [`is_alive()`](#multiprocessing.Process.is_alive "multiprocessing.Process.is_alive"), [`terminate()`](#multiprocessing.Process.terminate "multiprocessing.Process.terminate") and [`exitcode`](#multiprocessing.Process.exitcode "multiprocessing.Process.exitcode") methods should only be called by the process that created the process object. Example usage of some of the methods of [`Process`](#multiprocessing.Process "multiprocessing.Process"): ``` >>> import multiprocessing, time, signal >>> p = multiprocessing.Process(target=time.sleep, args=(1000,)) >>> print(p, p.is_alive()) <Process ... initial> False >>> p.start() >>> print(p, p.is_alive()) <Process ... started> True >>> p.terminate() >>> time.sleep(0.1) >>> print(p, p.is_alive()) <Process ... stopped exitcode=-SIGTERM> False >>> p.exitcode == -signal.SIGTERM True ``` `exception multiprocessing.ProcessError` The base class of all [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") exceptions. `exception multiprocessing.BufferTooShort` Exception raised by `Connection.recv_bytes_into()` when the supplied buffer object is too small for the message read. If `e` is an instance of [`BufferTooShort`](#multiprocessing.BufferTooShort "multiprocessing.BufferTooShort") then `e.args[0]` will give the message as a byte string. `exception multiprocessing.AuthenticationError` Raised when there is an authentication error. `exception multiprocessing.TimeoutError` Raised by methods with a timeout when the timeout expires. ### Pipes and Queues When using multiple processes, one generally uses message passing for communication between processes and avoids having to use any synchronization primitives like locks. For passing messages one can use [`Pipe()`](#multiprocessing.Pipe "multiprocessing.Pipe") (for a connection between two processes) or a queue (which allows multiple producers and consumers). The [`Queue`](#multiprocessing.Queue "multiprocessing.Queue"), [`SimpleQueue`](#multiprocessing.SimpleQueue "multiprocessing.SimpleQueue") and [`JoinableQueue`](#multiprocessing.JoinableQueue "multiprocessing.JoinableQueue") types are multi-producer, multi-consumer FIFO queues modelled on the [`queue.Queue`](queue#queue.Queue "queue.Queue") class in the standard library. They differ in that [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") lacks the [`task_done()`](queue#queue.Queue.task_done "queue.Queue.task_done") and [`join()`](queue#queue.Queue.join "queue.Queue.join") methods introduced into Python 2.5’s [`queue.Queue`](queue#queue.Queue "queue.Queue") class. If you use [`JoinableQueue`](#multiprocessing.JoinableQueue "multiprocessing.JoinableQueue") then you **must** call [`JoinableQueue.task_done()`](#multiprocessing.JoinableQueue.task_done "multiprocessing.JoinableQueue.task_done") for each task removed from the queue or else the semaphore used to count the number of unfinished tasks may eventually overflow, raising an exception. Note that one can also create a shared queue by using a manager object – see [Managers](#multiprocessing-managers). Note [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") uses the usual [`queue.Empty`](queue#queue.Empty "queue.Empty") and [`queue.Full`](queue#queue.Full "queue.Full") exceptions to signal a timeout. They are not available in the [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") namespace so you need to import them from [`queue`](queue#module-queue "queue: A synchronized queue class."). Note When an object is put on a queue, the object is pickled and a background thread later flushes the pickled data to an underlying pipe. This has some consequences which are a little surprising, but should not cause any practical difficulties – if they really bother you then you can instead use a queue created with a [manager](#multiprocessing-managers). 1. After putting an object on an empty queue there may be an infinitesimal delay before the queue’s [`empty()`](#multiprocessing.Queue.empty "multiprocessing.Queue.empty") method returns [`False`](constants#False "False") and [`get_nowait()`](#multiprocessing.Queue.get_nowait "multiprocessing.Queue.get_nowait") can return without raising [`queue.Empty`](queue#queue.Empty "queue.Empty"). 2. If multiple processes are enqueuing objects, it is possible for the objects to be received at the other end out-of-order. However, objects enqueued by the same process will always be in the expected order with respect to each other. Warning If a process is killed using [`Process.terminate()`](#multiprocessing.Process.terminate "multiprocessing.Process.terminate") or [`os.kill()`](os#os.kill "os.kill") while it is trying to use a [`Queue`](#multiprocessing.Queue "multiprocessing.Queue"), then the data in the queue is likely to become corrupted. This may cause any other process to get an exception when it tries to use the queue later on. Warning As mentioned above, if a child process has put items on a queue (and it has not used [`JoinableQueue.cancel_join_thread`](#multiprocessing.Queue.cancel_join_thread "multiprocessing.Queue.cancel_join_thread")), then that process will not terminate until all buffered items have been flushed to the pipe. This means that if you try joining that process you may get a deadlock unless you are sure that all items which have been put on the queue have been consumed. Similarly, if the child process is non-daemonic then the parent process may hang on exit when it tries to join all its non-daemonic children. Note that a queue created using a manager does not have this issue. See [Programming guidelines](#multiprocessing-programming). For an example of the usage of queues for interprocess communication see [Examples](#multiprocessing-examples). `multiprocessing.Pipe([duplex])` Returns a pair `(conn1, conn2)` of [`Connection`](#multiprocessing.connection.Connection "multiprocessing.connection.Connection") objects representing the ends of a pipe. If *duplex* is `True` (the default) then the pipe is bidirectional. If *duplex* is `False` then the pipe is unidirectional: `conn1` can only be used for receiving messages and `conn2` can only be used for sending messages. `class multiprocessing.Queue([maxsize])` Returns a process shared queue implemented using a pipe and a few locks/semaphores. When a process first puts an item on the queue a feeder thread is started which transfers objects from a buffer into the pipe. The usual [`queue.Empty`](queue#queue.Empty "queue.Empty") and [`queue.Full`](queue#queue.Full "queue.Full") exceptions from the standard library’s [`queue`](queue#module-queue "queue: A synchronized queue class.") module are raised to signal timeouts. [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") implements all the methods of [`queue.Queue`](queue#queue.Queue "queue.Queue") except for [`task_done()`](queue#queue.Queue.task_done "queue.Queue.task_done") and [`join()`](queue#queue.Queue.join "queue.Queue.join"). `qsize()` Return the approximate size of the queue. Because of multithreading/multiprocessing semantics, this number is not reliable. Note that this may raise [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") on Unix platforms like macOS where `sem_getvalue()` is not implemented. `empty()` Return `True` if the queue is empty, `False` otherwise. Because of multithreading/multiprocessing semantics, this is not reliable. `full()` Return `True` if the queue is full, `False` otherwise. Because of multithreading/multiprocessing semantics, this is not reliable. `put(obj[, block[, timeout]])` Put obj into the queue. If the optional argument *block* is `True` (the default) and *timeout* is `None` (the default), block if necessary until a free slot is available. If *timeout* is a positive number, it blocks at most *timeout* seconds and raises the [`queue.Full`](queue#queue.Full "queue.Full") exception if no free slot was available within that time. Otherwise (*block* is `False`), put an item on the queue if a free slot is immediately available, else raise the [`queue.Full`](queue#queue.Full "queue.Full") exception (*timeout* is ignored in that case). Changed in version 3.8: If the queue is closed, [`ValueError`](exceptions#ValueError "ValueError") is raised instead of [`AssertionError`](exceptions#AssertionError "AssertionError"). `put_nowait(obj)` Equivalent to `put(obj, False)`. `get([block[, timeout]])` Remove and return an item from the queue. If optional args *block* is `True` (the default) and *timeout* is `None` (the default), block if necessary until an item is available. If *timeout* is a positive number, it blocks at most *timeout* seconds and raises the [`queue.Empty`](queue#queue.Empty "queue.Empty") exception if no item was available within that time. Otherwise (block is `False`), return an item if one is immediately available, else raise the [`queue.Empty`](queue#queue.Empty "queue.Empty") exception (*timeout* is ignored in that case). Changed in version 3.8: If the queue is closed, [`ValueError`](exceptions#ValueError "ValueError") is raised instead of [`OSError`](exceptions#OSError "OSError"). `get_nowait()` Equivalent to `get(False)`. [`multiprocessing.Queue`](#multiprocessing.Queue "multiprocessing.Queue") has a few additional methods not found in [`queue.Queue`](queue#queue.Queue "queue.Queue"). These methods are usually unnecessary for most code: `close()` Indicate that no more data will be put on this queue by the current process. The background thread will quit once it has flushed all buffered data to the pipe. This is called automatically when the queue is garbage collected. `join_thread()` Join the background thread. This can only be used after [`close()`](#multiprocessing.Queue.close "multiprocessing.Queue.close") has been called. It blocks until the background thread exits, ensuring that all data in the buffer has been flushed to the pipe. By default if a process is not the creator of the queue then on exit it will attempt to join the queue’s background thread. The process can call [`cancel_join_thread()`](#multiprocessing.Queue.cancel_join_thread "multiprocessing.Queue.cancel_join_thread") to make [`join_thread()`](#multiprocessing.Queue.join_thread "multiprocessing.Queue.join_thread") do nothing. `cancel_join_thread()` Prevent [`join_thread()`](#multiprocessing.Queue.join_thread "multiprocessing.Queue.join_thread") from blocking. In particular, this prevents the background thread from being joined automatically when the process exits – see [`join_thread()`](#multiprocessing.Queue.join_thread "multiprocessing.Queue.join_thread"). A better name for this method might be `allow_exit_without_flush()`. It is likely to cause enqueued data to lost, and you almost certainly will not need to use it. It is really only there if you need the current process to exit immediately without waiting to flush enqueued data to the underlying pipe, and you don’t care about lost data. Note This class’s functionality requires a functioning shared semaphore implementation on the host operating system. Without one, the functionality in this class will be disabled, and attempts to instantiate a [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") will result in an [`ImportError`](exceptions#ImportError "ImportError"). See [bpo-3770](https://bugs.python.org/issue?@action=redirect&bpo=3770) for additional information. The same holds true for any of the specialized queue types listed below. `class multiprocessing.SimpleQueue` It is a simplified [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") type, very close to a locked [`Pipe`](#multiprocessing.Pipe "multiprocessing.Pipe"). `close()` Close the queue: release internal resources. A queue must not be used anymore after it is closed. For example, [`get()`](#multiprocessing.SimpleQueue.get "multiprocessing.SimpleQueue.get"), [`put()`](#multiprocessing.SimpleQueue.put "multiprocessing.SimpleQueue.put") and [`empty()`](#multiprocessing.SimpleQueue.empty "multiprocessing.SimpleQueue.empty") methods must no longer be called. New in version 3.9. `empty()` Return `True` if the queue is empty, `False` otherwise. `get()` Remove and return an item from the queue. `put(item)` Put *item* into the queue. `class multiprocessing.JoinableQueue([maxsize])` [`JoinableQueue`](#multiprocessing.JoinableQueue "multiprocessing.JoinableQueue"), a [`Queue`](#multiprocessing.Queue "multiprocessing.Queue") subclass, is a queue which additionally has [`task_done()`](#multiprocessing.JoinableQueue.task_done "multiprocessing.JoinableQueue.task_done") and [`join()`](#multiprocessing.JoinableQueue.join "multiprocessing.JoinableQueue.join") methods. `task_done()` Indicate that a formerly enqueued task is complete. Used by queue consumers. For each [`get()`](#multiprocessing.Queue.get "multiprocessing.Queue.get") used to fetch a task, a subsequent call to [`task_done()`](#multiprocessing.JoinableQueue.task_done "multiprocessing.JoinableQueue.task_done") tells the queue that the processing on the task is complete. If a [`join()`](queue#queue.Queue.join "queue.Queue.join") is currently blocking, it will resume when all items have been processed (meaning that a [`task_done()`](#multiprocessing.JoinableQueue.task_done "multiprocessing.JoinableQueue.task_done") call was received for every item that had been [`put()`](#multiprocessing.Queue.put "multiprocessing.Queue.put") into the queue). Raises a [`ValueError`](exceptions#ValueError "ValueError") if called more times than there were items placed in the queue. `join()` Block until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls [`task_done()`](#multiprocessing.JoinableQueue.task_done "multiprocessing.JoinableQueue.task_done") to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, [`join()`](queue#queue.Queue.join "queue.Queue.join") unblocks. ### Miscellaneous `multiprocessing.active_children()` Return list of all live children of the current process. Calling this has the side effect of “joining” any processes which have already finished. `multiprocessing.cpu_count()` Return the number of CPUs in the system. This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with `len(os.sched_getaffinity(0))` When the number of CPUs cannot be determined a [`NotImplementedError`](exceptions#NotImplementedError "NotImplementedError") is raised. See also [`os.cpu_count()`](os#os.cpu_count "os.cpu_count") `multiprocessing.current_process()` Return the [`Process`](#multiprocessing.Process "multiprocessing.Process") object corresponding to the current process. An analogue of [`threading.current_thread()`](threading#threading.current_thread "threading.current_thread"). `multiprocessing.parent_process()` Return the [`Process`](#multiprocessing.Process "multiprocessing.Process") object corresponding to the parent process of the [`current_process()`](#multiprocessing.current_process "multiprocessing.current_process"). For the main process, `parent_process` will be `None`. New in version 3.8. `multiprocessing.freeze_support()` Add support for when a program which uses [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") has been frozen to produce a Windows executable. (Has been tested with **py2exe**, **PyInstaller** and **cx\_Freeze**.) One needs to call this function straight after the `if __name__ == '__main__'` line of the main module. For example: ``` from multiprocessing import Process, freeze_support def f(): print('hello world!') if __name__ == '__main__': freeze_support() Process(target=f).start() ``` If the `freeze_support()` line is omitted then trying to run the frozen executable will raise [`RuntimeError`](exceptions#RuntimeError "RuntimeError"). Calling `freeze_support()` has no effect when invoked on any operating system other than Windows. In addition, if the module is being run normally by the Python interpreter on Windows (the program has not been frozen), then `freeze_support()` has no effect. `multiprocessing.get_all_start_methods()` Returns a list of the supported start methods, the first of which is the default. The possible start methods are `'fork'`, `'spawn'` and `'forkserver'`. On Windows only `'spawn'` is available. On Unix `'fork'` and `'spawn'` are always supported, with `'fork'` being the default. New in version 3.4. `multiprocessing.get_context(method=None)` Return a context object which has the same attributes as the [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") module. If *method* is `None` then the default context is returned. Otherwise *method* should be `'fork'`, `'spawn'`, `'forkserver'`. [`ValueError`](exceptions#ValueError "ValueError") is raised if the specified start method is not available. New in version 3.4. `multiprocessing.get_start_method(allow_none=False)` Return the name of start method used for starting processes. If the start method has not been fixed and *allow\_none* is false, then the start method is fixed to the default and the name is returned. If the start method has not been fixed and *allow\_none* is true then `None` is returned. The return value can be `'fork'`, `'spawn'`, `'forkserver'` or `None`. `'fork'` is the default on Unix, while `'spawn'` is the default on Windows and macOS. Changed in version 3.8: On macOS, the *spawn* start method is now the default. The *fork* start method should be considered unsafe as it can lead to crashes of the subprocess. See [bpo-33725](https://bugs.python.org/issue?@action=redirect&bpo=33725). New in version 3.4. `multiprocessing.set_executable(executable)` Set the path of the Python interpreter to use when starting a child process. (By default [`sys.executable`](sys#sys.executable "sys.executable") is used). Embedders will probably need to do some thing like ``` set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe')) ``` before they can create child processes. Changed in version 3.4: Now supported on Unix when the `'spawn'` start method is used. `multiprocessing.set_start_method(method)` Set the method which should be used to start child processes. *method* can be `'fork'`, `'spawn'` or `'forkserver'`. Note that this should be called at most once, and it should be protected inside the `if __name__ == '__main__'` clause of the main module. New in version 3.4. Note [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") contains no analogues of [`threading.active_count()`](threading#threading.active_count "threading.active_count"), [`threading.enumerate()`](threading#threading.enumerate "threading.enumerate"), [`threading.settrace()`](threading#threading.settrace "threading.settrace"), [`threading.setprofile()`](threading#threading.setprofile "threading.setprofile"), [`threading.Timer`](threading#threading.Timer "threading.Timer"), or [`threading.local`](threading#threading.local "threading.local"). ### Connection Objects Connection objects allow the sending and receiving of picklable objects or strings. They can be thought of as message oriented connected sockets. Connection objects are usually created using [`Pipe`](#multiprocessing.Pipe "multiprocessing.Pipe") – see also [Listeners and Clients](#multiprocessing-listeners-clients). `class multiprocessing.connection.Connection` `send(obj)` Send an object to the other end of the connection which should be read using [`recv()`](#multiprocessing.connection.Connection.recv "multiprocessing.connection.Connection.recv"). The object must be picklable. Very large pickles (approximately 32 MiB+, though it depends on the OS) may raise a [`ValueError`](exceptions#ValueError "ValueError") exception. `recv()` Return an object sent from the other end of the connection using [`send()`](#multiprocessing.connection.Connection.send "multiprocessing.connection.Connection.send"). Blocks until there is something to receive. Raises [`EOFError`](exceptions#EOFError "EOFError") if there is nothing left to receive and the other end was closed. `fileno()` Return the file descriptor or handle used by the connection. `close()` Close the connection. This is called automatically when the connection is garbage collected. `poll([timeout])` Return whether there is any data available to be read. If *timeout* is not specified then it will return immediately. If *timeout* is a number then this specifies the maximum time in seconds to block. If *timeout* is `None` then an infinite timeout is used. Note that multiple connection objects may be polled at once by using [`multiprocessing.connection.wait()`](#multiprocessing.connection.wait "multiprocessing.connection.wait"). `send_bytes(buffer[, offset[, size]])` Send byte data from a [bytes-like object](../glossary#term-bytes-like-object) as a complete message. If *offset* is given then data is read from that position in *buffer*. If *size* is given then that many bytes will be read from buffer. Very large buffers (approximately 32 MiB+, though it depends on the OS) may raise a [`ValueError`](exceptions#ValueError "ValueError") exception `recv_bytes([maxlength])` Return a complete message of byte data sent from the other end of the connection as a string. Blocks until there is something to receive. Raises [`EOFError`](exceptions#EOFError "EOFError") if there is nothing left to receive and the other end has closed. If *maxlength* is specified and the message is longer than *maxlength* then [`OSError`](exceptions#OSError "OSError") is raised and the connection will no longer be readable. Changed in version 3.3: This function used to raise [`IOError`](exceptions#IOError "IOError"), which is now an alias of [`OSError`](exceptions#OSError "OSError"). `recv_bytes_into(buffer[, offset])` Read into *buffer* a complete message of byte data sent from the other end of the connection and return the number of bytes in the message. Blocks until there is something to receive. Raises [`EOFError`](exceptions#EOFError "EOFError") if there is nothing left to receive and the other end was closed. *buffer* must be a writable [bytes-like object](../glossary#term-bytes-like-object). If *offset* is given then the message will be written into the buffer from that position. Offset must be a non-negative integer less than the length of *buffer* (in bytes). If the buffer is too short then a `BufferTooShort` exception is raised and the complete message is available as `e.args[0]` where `e` is the exception instance. Changed in version 3.3: Connection objects themselves can now be transferred between processes using [`Connection.send()`](#multiprocessing.connection.Connection.send "multiprocessing.connection.Connection.send") and [`Connection.recv()`](#multiprocessing.connection.Connection.recv "multiprocessing.connection.Connection.recv"). New in version 3.3: Connection objects now support the context management protocol – see [Context Manager Types](stdtypes#typecontextmanager). [`__enter__()`](stdtypes#contextmanager.__enter__ "contextmanager.__enter__") returns the connection object, and [`__exit__()`](stdtypes#contextmanager.__exit__ "contextmanager.__exit__") calls [`close()`](#multiprocessing.connection.Connection.close "multiprocessing.connection.Connection.close"). For example: ``` >>> from multiprocessing import Pipe >>> a, b = Pipe() >>> a.send([1, 'hello', None]) >>> b.recv() [1, 'hello', None] >>> b.send_bytes(b'thank you') >>> a.recv_bytes() b'thank you' >>> import array >>> arr1 = array.array('i', range(5)) >>> arr2 = array.array('i', [0] * 10) >>> a.send_bytes(arr1) >>> count = b.recv_bytes_into(arr2) >>> assert count == len(arr1) * arr1.itemsize >>> arr2 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]) ``` Warning The [`Connection.recv()`](#multiprocessing.connection.Connection.recv "multiprocessing.connection.Connection.recv") method automatically unpickles the data it receives, which can be a security risk unless you can trust the process which sent the message. Therefore, unless the connection object was produced using `Pipe()` you should only use the [`recv()`](#multiprocessing.connection.Connection.recv "multiprocessing.connection.Connection.recv") and [`send()`](#multiprocessing.connection.Connection.send "multiprocessing.connection.Connection.send") methods after performing some sort of authentication. See [Authentication keys](#multiprocessing-auth-keys). Warning If a process is killed while it is trying to read or write to a pipe then the data in the pipe is likely to become corrupted, because it may become impossible to be sure where the message boundaries lie. ### Synchronization primitives Generally synchronization primitives are not as necessary in a multiprocess program as they are in a multithreaded program. See the documentation for [`threading`](threading#module-threading "threading: Thread-based parallelism.") module. Note that one can also create synchronization primitives by using a manager object – see [Managers](#multiprocessing-managers). `class multiprocessing.Barrier(parties[, action[, timeout]])` A barrier object: a clone of [`threading.Barrier`](threading#threading.Barrier "threading.Barrier"). New in version 3.3. `class multiprocessing.BoundedSemaphore([value])` A bounded semaphore object: a close analog of [`threading.BoundedSemaphore`](threading#threading.BoundedSemaphore "threading.BoundedSemaphore"). A solitary difference from its close analog exists: its `acquire` method’s first argument is named *block*, as is consistent with [`Lock.acquire()`](#multiprocessing.Lock.acquire "multiprocessing.Lock.acquire"). Note On macOS, this is indistinguishable from [`Semaphore`](#multiprocessing.Semaphore "multiprocessing.Semaphore") because `sem_getvalue()` is not implemented on that platform. `class multiprocessing.Condition([lock])` A condition variable: an alias for [`threading.Condition`](threading#threading.Condition "threading.Condition"). If *lock* is specified then it should be a [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") or [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") object from [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism."). Changed in version 3.3: The [`wait_for()`](threading#threading.Condition.wait_for "threading.Condition.wait_for") method was added. `class multiprocessing.Event` A clone of [`threading.Event`](threading#threading.Event "threading.Event"). `class multiprocessing.Lock` A non-recursive lock object: a close analog of [`threading.Lock`](threading#threading.Lock "threading.Lock"). Once a process or thread has acquired a lock, subsequent attempts to acquire it from any process or thread will block until it is released; any process or thread may release it. The concepts and behaviors of [`threading.Lock`](threading#threading.Lock "threading.Lock") as it applies to threads are replicated here in [`multiprocessing.Lock`](#multiprocessing.Lock "multiprocessing.Lock") as it applies to either processes or threads, except as noted. Note that [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") is actually a factory function which returns an instance of `multiprocessing.synchronize.Lock` initialized with a default context. [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") supports the [context manager](../glossary#term-context-manager) protocol and thus may be used in [`with`](../reference/compound_stmts#with) statements. `acquire(block=True, timeout=None)` Acquire a lock, blocking or non-blocking. With the *block* argument set to `True` (the default), the method call will block until the lock is in an unlocked state, then set it to locked and return `True`. Note that the name of this first argument differs from that in [`threading.Lock.acquire()`](threading#threading.Lock.acquire "threading.Lock.acquire"). With the *block* argument set to `False`, the method call does not block. If the lock is currently in a locked state, return `False`; otherwise set the lock to a locked state and return `True`. When invoked with a positive, floating-point value for *timeout*, block for at most the number of seconds specified by *timeout* as long as the lock can not be acquired. Invocations with a negative value for *timeout* are equivalent to a *timeout* of zero. Invocations with a *timeout* value of `None` (the default) set the timeout period to infinite. Note that the treatment of negative or `None` values for *timeout* differs from the implemented behavior in [`threading.Lock.acquire()`](threading#threading.Lock.acquire "threading.Lock.acquire"). The *timeout* argument has no practical implications if the *block* argument is set to `False` and is thus ignored. Returns `True` if the lock has been acquired or `False` if the timeout period has elapsed. `release()` Release a lock. This can be called from any process or thread, not only the process or thread which originally acquired the lock. Behavior is the same as in [`threading.Lock.release()`](threading#threading.Lock.release "threading.Lock.release") except that when invoked on an unlocked lock, a [`ValueError`](exceptions#ValueError "ValueError") is raised. `class multiprocessing.RLock` A recursive lock object: a close analog of [`threading.RLock`](threading#threading.RLock "threading.RLock"). A recursive lock must be released by the process or thread that acquired it. Once a process or thread has acquired a recursive lock, the same process or thread may acquire it again without blocking; that process or thread must release it once for each time it has been acquired. Note that [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") is actually a factory function which returns an instance of `multiprocessing.synchronize.RLock` initialized with a default context. [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") supports the [context manager](../glossary#term-context-manager) protocol and thus may be used in [`with`](../reference/compound_stmts#with) statements. `acquire(block=True, timeout=None)` Acquire a lock, blocking or non-blocking. When invoked with the *block* argument set to `True`, block until the lock is in an unlocked state (not owned by any process or thread) unless the lock is already owned by the current process or thread. The current process or thread then takes ownership of the lock (if it does not already have ownership) and the recursion level inside the lock increments by one, resulting in a return value of `True`. Note that there are several differences in this first argument’s behavior compared to the implementation of [`threading.RLock.acquire()`](threading#threading.RLock.acquire "threading.RLock.acquire"), starting with the name of the argument itself. When invoked with the *block* argument set to `False`, do not block. If the lock has already been acquired (and thus is owned) by another process or thread, the current process or thread does not take ownership and the recursion level within the lock is not changed, resulting in a return value of `False`. If the lock is in an unlocked state, the current process or thread takes ownership and the recursion level is incremented, resulting in a return value of `True`. Use and behaviors of the *timeout* argument are the same as in [`Lock.acquire()`](#multiprocessing.Lock.acquire "multiprocessing.Lock.acquire"). Note that some of these behaviors of *timeout* differ from the implemented behaviors in [`threading.RLock.acquire()`](threading#threading.RLock.acquire "threading.RLock.acquire"). `release()` Release a lock, decrementing the recursion level. If after the decrement the recursion level is zero, reset the lock to unlocked (not owned by any process or thread) and if any other processes or threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling process or thread. Only call this method when the calling process or thread owns the lock. An [`AssertionError`](exceptions#AssertionError "AssertionError") is raised if this method is called by a process or thread other than the owner or if the lock is in an unlocked (unowned) state. Note that the type of exception raised in this situation differs from the implemented behavior in [`threading.RLock.release()`](threading#threading.RLock.release "threading.RLock.release"). `class multiprocessing.Semaphore([value])` A semaphore object: a close analog of [`threading.Semaphore`](threading#threading.Semaphore "threading.Semaphore"). A solitary difference from its close analog exists: its `acquire` method’s first argument is named *block*, as is consistent with [`Lock.acquire()`](#multiprocessing.Lock.acquire "multiprocessing.Lock.acquire"). Note On macOS, `sem_timedwait` is unsupported, so calling `acquire()` with a timeout will emulate that function’s behavior using a sleeping loop. Note If the SIGINT signal generated by `Ctrl-C` arrives while the main thread is blocked by a call to `BoundedSemaphore.acquire()`, [`Lock.acquire()`](#multiprocessing.Lock.acquire "multiprocessing.Lock.acquire"), [`RLock.acquire()`](#multiprocessing.RLock.acquire "multiprocessing.RLock.acquire"), `Semaphore.acquire()`, `Condition.acquire()` or `Condition.wait()` then the call will be immediately interrupted and [`KeyboardInterrupt`](exceptions#KeyboardInterrupt "KeyboardInterrupt") will be raised. This differs from the behaviour of [`threading`](threading#module-threading "threading: Thread-based parallelism.") where SIGINT will be ignored while the equivalent blocking calls are in progress. Note Some of this package’s functionality requires a functioning shared semaphore implementation on the host operating system. Without one, the `multiprocessing.synchronize` module will be disabled, and attempts to import it will result in an [`ImportError`](exceptions#ImportError "ImportError"). See [bpo-3770](https://bugs.python.org/issue?@action=redirect&bpo=3770) for additional information. ### Shared [`ctypes`](ctypes#module-ctypes "ctypes: A foreign function library for Python.") Objects It is possible to create shared objects using shared memory which can be inherited by child processes. `multiprocessing.Value(typecode_or_type, *args, lock=True)` Return a [`ctypes`](ctypes#module-ctypes "ctypes: A foreign function library for Python.") object allocated from shared memory. By default the return value is actually a synchronized wrapper for the object. The object itself can be accessed via the *value* attribute of a [`Value`](#multiprocessing.Value "multiprocessing.Value"). *typecode\_or\_type* determines the type of the returned object: it is either a ctypes type or a one character typecode of the kind used by the [`array`](array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module. *\*args* is passed on to the constructor for the type. If *lock* is `True` (the default) then a new recursive lock object is created to synchronize access to the value. If *lock* is a [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") or [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") object then that will be used to synchronize access to the value. If *lock* is `False` then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”. Operations like `+=` which involve a read and write are not atomic. So if, for instance, you want to atomically increment a shared value it is insufficient to just do ``` counter.value += 1 ``` Assuming the associated lock is recursive (which it is by default) you can instead do ``` with counter.get_lock(): counter.value += 1 ``` Note that *lock* is a keyword-only argument. `multiprocessing.Array(typecode_or_type, size_or_initializer, *, lock=True)` Return a ctypes array allocated from shared memory. By default the return value is actually a synchronized wrapper for the array. *typecode\_or\_type* determines the type of the elements of the returned array: it is either a ctypes type or a one character typecode of the kind used by the [`array`](array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module. If *size\_or\_initializer* is an integer, then it determines the length of the array, and the array will be initially zeroed. Otherwise, *size\_or\_initializer* is a sequence which is used to initialize the array and whose length determines the length of the array. If *lock* is `True` (the default) then a new lock object is created to synchronize access to the value. If *lock* is a [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") or [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") object then that will be used to synchronize access to the value. If *lock* is `False` then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”. Note that *lock* is a keyword only argument. Note that an array of [`ctypes.c_char`](ctypes#ctypes.c_char "ctypes.c_char") has *value* and *raw* attributes which allow one to use it to store and retrieve strings. #### The [`multiprocessing.sharedctypes`](#module-multiprocessing.sharedctypes "multiprocessing.sharedctypes: Allocate ctypes objects from shared memory.") module The [`multiprocessing.sharedctypes`](#module-multiprocessing.sharedctypes "multiprocessing.sharedctypes: Allocate ctypes objects from shared memory.") module provides functions for allocating [`ctypes`](ctypes#module-ctypes "ctypes: A foreign function library for Python.") objects from shared memory which can be inherited by child processes. Note Although it is possible to store a pointer in shared memory remember that this will refer to a location in the address space of a specific process. However, the pointer is quite likely to be invalid in the context of a second process and trying to dereference the pointer from the second process may cause a crash. `multiprocessing.sharedctypes.RawArray(typecode_or_type, size_or_initializer)` Return a ctypes array allocated from shared memory. *typecode\_or\_type* determines the type of the elements of the returned array: it is either a ctypes type or a one character typecode of the kind used by the [`array`](array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module. If *size\_or\_initializer* is an integer then it determines the length of the array, and the array will be initially zeroed. Otherwise *size\_or\_initializer* is a sequence which is used to initialize the array and whose length determines the length of the array. Note that setting and getting an element is potentially non-atomic – use [`Array()`](#multiprocessing.sharedctypes.Array "multiprocessing.sharedctypes.Array") instead to make sure that access is automatically synchronized using a lock. `multiprocessing.sharedctypes.RawValue(typecode_or_type, *args)` Return a ctypes object allocated from shared memory. *typecode\_or\_type* determines the type of the returned object: it is either a ctypes type or a one character typecode of the kind used by the [`array`](array#module-array "array: Space efficient arrays of uniformly typed numeric values.") module. *\*args* is passed on to the constructor for the type. Note that setting and getting the value is potentially non-atomic – use [`Value()`](#multiprocessing.sharedctypes.Value "multiprocessing.sharedctypes.Value") instead to make sure that access is automatically synchronized using a lock. Note that an array of [`ctypes.c_char`](ctypes#ctypes.c_char "ctypes.c_char") has `value` and `raw` attributes which allow one to use it to store and retrieve strings – see documentation for [`ctypes`](ctypes#module-ctypes "ctypes: A foreign function library for Python."). `multiprocessing.sharedctypes.Array(typecode_or_type, size_or_initializer, *, lock=True)` The same as [`RawArray()`](#multiprocessing.sharedctypes.RawArray "multiprocessing.sharedctypes.RawArray") except that depending on the value of *lock* a process-safe synchronization wrapper may be returned instead of a raw ctypes array. If *lock* is `True` (the default) then a new lock object is created to synchronize access to the value. If *lock* is a [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") or [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") object then that will be used to synchronize access to the value. If *lock* is `False` then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”. Note that *lock* is a keyword-only argument. `multiprocessing.sharedctypes.Value(typecode_or_type, *args, lock=True)` The same as [`RawValue()`](#multiprocessing.sharedctypes.RawValue "multiprocessing.sharedctypes.RawValue") except that depending on the value of *lock* a process-safe synchronization wrapper may be returned instead of a raw ctypes object. If *lock* is `True` (the default) then a new lock object is created to synchronize access to the value. If *lock* is a [`Lock`](#multiprocessing.Lock "multiprocessing.Lock") or [`RLock`](#multiprocessing.RLock "multiprocessing.RLock") object then that will be used to synchronize access to the value. If *lock* is `False` then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”. Note that *lock* is a keyword-only argument. `multiprocessing.sharedctypes.copy(obj)` Return a ctypes object allocated from shared memory which is a copy of the ctypes object *obj*. `multiprocessing.sharedctypes.synchronized(obj[, lock])` Return a process-safe wrapper object for a ctypes object which uses *lock* to synchronize access. If *lock* is `None` (the default) then a [`multiprocessing.RLock`](#multiprocessing.RLock "multiprocessing.RLock") object is created automatically. A synchronized wrapper will have two methods in addition to those of the object it wraps: `get_obj()` returns the wrapped object and `get_lock()` returns the lock object used for synchronization. Note that accessing the ctypes object through the wrapper can be a lot slower than accessing the raw ctypes object. Changed in version 3.5: Synchronized objects support the [context manager](../glossary#term-context-manager) protocol. The table below compares the syntax for creating shared ctypes objects from shared memory with the normal ctypes syntax. (In the table `MyStruct` is some subclass of [`ctypes.Structure`](ctypes#ctypes.Structure "ctypes.Structure").) | ctypes | sharedctypes using type | sharedctypes using typecode | | --- | --- | --- | | c\_double(2.4) | RawValue(c\_double, 2.4) | RawValue(‘d’, 2.4) | | MyStruct(4, 6) | RawValue(MyStruct, 4, 6) | | | (c\_short \* 7)() | RawArray(c\_short, 7) | RawArray(‘h’, 7) | | (c\_int \* 3)(9, 2, 8) | RawArray(c\_int, (9, 2, 8)) | RawArray(‘i’, (9, 2, 8)) | Below is an example where a number of ctypes objects are modified by a child process: ``` from multiprocessing import Process, Lock from multiprocessing.sharedctypes import Value, Array from ctypes import Structure, c_double class Point(Structure): _fields_ = [('x', c_double), ('y', c_double)] def modify(n, x, s, A): n.value **= 2 x.value **= 2 s.value = s.value.upper() for a in A: a.x **= 2 a.y **= 2 if __name__ == '__main__': lock = Lock() n = Value('i', 7) x = Value(c_double, 1.0/3.0, lock=False) s = Array('c', b'hello world', lock=lock) A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock) p = Process(target=modify, args=(n, x, s, A)) p.start() p.join() print(n.value) print(x.value) print(s.value) print([(a.x, a.y) for a in A]) ``` The results printed are ``` 49 0.1111111111111111 HELLO WORLD [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)] ``` ### Managers Managers provide a way to create data which can be shared between different processes, including sharing over a network between processes running on different machines. A manager object controls a server process which manages *shared objects*. Other processes can access the shared objects by using proxies. `multiprocessing.Manager()` Returns a started [`SyncManager`](#multiprocessing.managers.SyncManager "multiprocessing.managers.SyncManager") object which can be used for sharing objects between processes. The returned manager object corresponds to a spawned child process and has methods which will create shared objects and return corresponding proxies. Manager processes will be shutdown as soon as they are garbage collected or their parent process exits. The manager classes are defined in the [`multiprocessing.managers`](#module-multiprocessing.managers "multiprocessing.managers: Share data between process with shared objects.") module: `class multiprocessing.managers.BaseManager([address[, authkey]])` Create a BaseManager object. Once created one should call [`start()`](#multiprocessing.managers.BaseManager.start "multiprocessing.managers.BaseManager.start") or `get_server().serve_forever()` to ensure that the manager object refers to a started manager process. *address* is the address on which the manager process listens for new connections. If *address* is `None` then an arbitrary one is chosen. *authkey* is the authentication key which will be used to check the validity of incoming connections to the server process. If *authkey* is `None` then `current_process().authkey` is used. Otherwise *authkey* is used and it must be a byte string. `start([initializer[, initargs]])` Start a subprocess to start the manager. If *initializer* is not `None` then the subprocess will call `initializer(*initargs)` when it starts. `get_server()` Returns a `Server` object which represents the actual server under the control of the Manager. The `Server` object supports the `serve_forever()` method: ``` >>> from multiprocessing.managers import BaseManager >>> manager = BaseManager(address=('', 50000), authkey=b'abc') >>> server = manager.get_server() >>> server.serve_forever() ``` `Server` additionally has an [`address`](#multiprocessing.managers.BaseManager.address "multiprocessing.managers.BaseManager.address") attribute. `connect()` Connect a local manager object to a remote manager process: ``` >>> from multiprocessing.managers import BaseManager >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc') >>> m.connect() ``` `shutdown()` Stop the process used by the manager. This is only available if [`start()`](#multiprocessing.managers.BaseManager.start "multiprocessing.managers.BaseManager.start") has been used to start the server process. This can be called multiple times. `register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])` A classmethod which can be used for registering a type or callable with the manager class. *typeid* is a “type identifier” which is used to identify a particular type of shared object. This must be a string. *callable* is a callable used for creating objects for this type identifier. If a manager instance will be connected to the server using the [`connect()`](#multiprocessing.managers.BaseManager.connect "multiprocessing.managers.BaseManager.connect") method, or if the *create\_method* argument is `False` then this can be left as `None`. *proxytype* is a subclass of [`BaseProxy`](#multiprocessing.managers.BaseProxy "multiprocessing.managers.BaseProxy") which is used to create proxies for shared objects with this *typeid*. If `None` then a proxy class is created automatically. *exposed* is used to specify a sequence of method names which proxies for this typeid should be allowed to access using [`BaseProxy._callmethod()`](#multiprocessing.managers.BaseProxy._callmethod "multiprocessing.managers.BaseProxy._callmethod"). (If *exposed* is `None` then `proxytype._exposed_` is used instead if it exists.) In the case where no exposed list is specified, all “public methods” of the shared object will be accessible. (Here a “public method” means any attribute which has a [`__call__()`](../reference/datamodel#object.__call__ "object.__call__") method and whose name does not begin with `'_'`.) *method\_to\_typeid* is a mapping used to specify the return type of those exposed methods which should return a proxy. It maps method names to typeid strings. (If *method\_to\_typeid* is `None` then `proxytype._method_to_typeid_` is used instead if it exists.) If a method’s name is not a key of this mapping or if the mapping is `None` then the object returned by the method will be copied by value. *create\_method* determines whether a method should be created with name *typeid* which can be used to tell the server process to create a new shared object and return a proxy for it. By default it is `True`. [`BaseManager`](#multiprocessing.managers.BaseManager "multiprocessing.managers.BaseManager") instances also have one read-only property: `address` The address used by the manager. Changed in version 3.3: Manager objects support the context management protocol – see [Context Manager Types](stdtypes#typecontextmanager). [`__enter__()`](stdtypes#contextmanager.__enter__ "contextmanager.__enter__") starts the server process (if it has not already started) and then returns the manager object. [`__exit__()`](stdtypes#contextmanager.__exit__ "contextmanager.__exit__") calls [`shutdown()`](#multiprocessing.managers.BaseManager.shutdown "multiprocessing.managers.BaseManager.shutdown"). In previous versions [`__enter__()`](stdtypes#contextmanager.__enter__ "contextmanager.__enter__") did not start the manager’s server process if it was not already started. `class multiprocessing.managers.SyncManager` A subclass of [`BaseManager`](#multiprocessing.managers.BaseManager "multiprocessing.managers.BaseManager") which can be used for the synchronization of processes. Objects of this type are returned by [`multiprocessing.Manager()`](#multiprocessing.Manager "multiprocessing.Manager"). Its methods create and return [Proxy Objects](#multiprocessing-proxy-objects) for a number of commonly used data types to be synchronized across processes. This notably includes shared lists and dictionaries. `Barrier(parties[, action[, timeout]])` Create a shared [`threading.Barrier`](threading#threading.Barrier "threading.Barrier") object and return a proxy for it. New in version 3.3. `BoundedSemaphore([value])` Create a shared [`threading.BoundedSemaphore`](threading#threading.BoundedSemaphore "threading.BoundedSemaphore") object and return a proxy for it. `Condition([lock])` Create a shared [`threading.Condition`](threading#threading.Condition "threading.Condition") object and return a proxy for it. If *lock* is supplied then it should be a proxy for a [`threading.Lock`](threading#threading.Lock "threading.Lock") or [`threading.RLock`](threading#threading.RLock "threading.RLock") object. Changed in version 3.3: The [`wait_for()`](threading#threading.Condition.wait_for "threading.Condition.wait_for") method was added. `Event()` Create a shared [`threading.Event`](threading#threading.Event "threading.Event") object and return a proxy for it. `Lock()` Create a shared [`threading.Lock`](threading#threading.Lock "threading.Lock") object and return a proxy for it. `Namespace()` Create a shared [`Namespace`](#multiprocessing.managers.Namespace "multiprocessing.managers.Namespace") object and return a proxy for it. `Queue([maxsize])` Create a shared [`queue.Queue`](queue#queue.Queue "queue.Queue") object and return a proxy for it. `RLock()` Create a shared [`threading.RLock`](threading#threading.RLock "threading.RLock") object and return a proxy for it. `Semaphore([value])` Create a shared [`threading.Semaphore`](threading#threading.Semaphore "threading.Semaphore") object and return a proxy for it. `Array(typecode, sequence)` Create an array and return a proxy for it. `Value(typecode, value)` Create an object with a writable `value` attribute and return a proxy for it. `dict()` `dict(mapping)` `dict(sequence)` Create a shared [`dict`](stdtypes#dict "dict") object and return a proxy for it. `list()` `list(sequence)` Create a shared [`list`](stdtypes#list "list") object and return a proxy for it. Changed in version 3.6: Shared objects are capable of being nested. For example, a shared container object such as a shared list can contain other shared objects which will all be managed and synchronized by the [`SyncManager`](#multiprocessing.managers.SyncManager "multiprocessing.managers.SyncManager"). `class multiprocessing.managers.Namespace` A type that can register with [`SyncManager`](#multiprocessing.managers.SyncManager "multiprocessing.managers.SyncManager"). A namespace object has no public methods, but does have writable attributes. Its representation shows the values of its attributes. However, when using a proxy for a namespace object, an attribute beginning with `'_'` will be an attribute of the proxy and not an attribute of the referent: ``` >>> manager = multiprocessing.Manager() >>> Global = manager.Namespace() >>> Global.x = 10 >>> Global.y = 'hello' >>> Global._z = 12.3 # this is an attribute of the proxy >>> print(Global) Namespace(x=10, y='hello') ``` #### Customized managers To create one’s own manager, one creates a subclass of [`BaseManager`](#multiprocessing.managers.BaseManager "multiprocessing.managers.BaseManager") and uses the [`register()`](#multiprocessing.managers.BaseManager.register "multiprocessing.managers.BaseManager.register") classmethod to register new types or callables with the manager class. For example: ``` from multiprocessing.managers import BaseManager class MathsClass: def add(self, x, y): return x + y def mul(self, x, y): return x * y class MyManager(BaseManager): pass MyManager.register('Maths', MathsClass) if __name__ == '__main__': with MyManager() as manager: maths = manager.Maths() print(maths.add(4, 3)) # prints 7 print(maths.mul(7, 8)) # prints 56 ``` #### Using a remote manager It is possible to run a manager server on one machine and have clients use it from other machines (assuming that the firewalls involved allow it). Running the following commands creates a server for a single shared queue which remote clients can access: ``` >>> from multiprocessing.managers import BaseManager >>> from queue import Queue >>> queue = Queue() >>> class QueueManager(BaseManager): pass >>> QueueManager.register('get_queue', callable=lambda:queue) >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra') >>> s = m.get_server() >>> s.serve_forever() ``` One client can access the server as follows: ``` >>> from multiprocessing.managers import BaseManager >>> class QueueManager(BaseManager): pass >>> QueueManager.register('get_queue') >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra') >>> m.connect() >>> queue = m.get_queue() >>> queue.put('hello') ``` Another client can also use it: ``` >>> from multiprocessing.managers import BaseManager >>> class QueueManager(BaseManager): pass >>> QueueManager.register('get_queue') >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra') >>> m.connect() >>> queue = m.get_queue() >>> queue.get() 'hello' ``` Local processes can also access that queue, using the code from above on the client to access it remotely: ``` >>> from multiprocessing import Process, Queue >>> from multiprocessing.managers import BaseManager >>> class Worker(Process): ... def __init__(self, q): ... self.q = q ... super().__init__() ... def run(self): ... self.q.put('local hello') ... >>> queue = Queue() >>> w = Worker(queue) >>> w.start() >>> class QueueManager(BaseManager): pass ... >>> QueueManager.register('get_queue', callable=lambda: queue) >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra') >>> s = m.get_server() >>> s.serve_forever() ``` ### Proxy Objects A proxy is an object which *refers* to a shared object which lives (presumably) in a different process. The shared object is said to be the *referent* of the proxy. Multiple proxy objects may have the same referent. A proxy object has methods which invoke corresponding methods of its referent (although not every method of the referent will necessarily be available through the proxy). In this way, a proxy can be used just like its referent can: ``` >>> from multiprocessing import Manager >>> manager = Manager() >>> l = manager.list([i*i for i in range(10)]) >>> print(l) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> print(repr(l)) <ListProxy object, typeid 'list' at 0x...> >>> l[4] 16 >>> l[2:5] [4, 9, 16] ``` Notice that applying [`str()`](stdtypes#str "str") to a proxy will return the representation of the referent, whereas applying [`repr()`](functions#repr "repr") will return the representation of the proxy. An important feature of proxy objects is that they are picklable so they can be passed between processes. As such, a referent can contain [Proxy Objects](#multiprocessing-proxy-objects). This permits nesting of these managed lists, dicts, and other [Proxy Objects](#multiprocessing-proxy-objects): ``` >>> a = manager.list() >>> b = manager.list() >>> a.append(b) # referent of a now contains referent of b >>> print(a, b) [<ListProxy object, typeid 'list' at ...>] [] >>> b.append('hello') >>> print(a[0], b) ['hello'] ['hello'] ``` Similarly, dict and list proxies may be nested inside one another: ``` >>> l_outer = manager.list([ manager.dict() for i in range(2) ]) >>> d_first_inner = l_outer[0] >>> d_first_inner['a'] = 1 >>> d_first_inner['b'] = 2 >>> l_outer[1]['c'] = 3 >>> l_outer[1]['z'] = 26 >>> print(l_outer[0]) {'a': 1, 'b': 2} >>> print(l_outer[1]) {'c': 3, 'z': 26} ``` If standard (non-proxy) [`list`](stdtypes#list "list") or [`dict`](stdtypes#dict "dict") objects are contained in a referent, modifications to those mutable values will not be propagated through the manager because the proxy has no way of knowing when the values contained within are modified. However, storing a value in a container proxy (which triggers a `__setitem__` on the proxy object) does propagate through the manager and so to effectively modify such an item, one could re-assign the modified value to the container proxy: ``` # create a list proxy and append a mutable object (a dictionary) lproxy = manager.list() lproxy.append({}) # now mutate the dictionary d = lproxy[0] d['a'] = 1 d['b'] = 2 # at this point, the changes to d are not yet synced, but by # updating the dictionary, the proxy is notified of the change lproxy[0] = d ``` This approach is perhaps less convenient than employing nested [Proxy Objects](#multiprocessing-proxy-objects) for most use cases but also demonstrates a level of control over the synchronization. Note The proxy types in [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") do nothing to support comparisons by value. So, for instance, we have: ``` >>> manager.list([1,2,3]) == [1,2,3] False ``` One should just use a copy of the referent instead when making comparisons. `class multiprocessing.managers.BaseProxy` Proxy objects are instances of subclasses of [`BaseProxy`](#multiprocessing.managers.BaseProxy "multiprocessing.managers.BaseProxy"). `_callmethod(methodname[, args[, kwds]])` Call and return the result of a method of the proxy’s referent. If `proxy` is a proxy whose referent is `obj` then the expression ``` proxy._callmethod(methodname, args, kwds) ``` will evaluate the expression ``` getattr(obj, methodname)(*args, **kwds) ``` in the manager’s process. The returned value will be a copy of the result of the call or a proxy to a new shared object – see documentation for the *method\_to\_typeid* argument of [`BaseManager.register()`](#multiprocessing.managers.BaseManager.register "multiprocessing.managers.BaseManager.register"). If an exception is raised by the call, then is re-raised by [`_callmethod()`](#multiprocessing.managers.BaseProxy._callmethod "multiprocessing.managers.BaseProxy._callmethod"). If some other exception is raised in the manager’s process then this is converted into a `RemoteError` exception and is raised by [`_callmethod()`](#multiprocessing.managers.BaseProxy._callmethod "multiprocessing.managers.BaseProxy._callmethod"). Note in particular that an exception will be raised if *methodname* has not been *exposed*. An example of the usage of [`_callmethod()`](#multiprocessing.managers.BaseProxy._callmethod "multiprocessing.managers.BaseProxy._callmethod"): ``` >>> l = manager.list(range(10)) >>> l._callmethod('__len__') 10 >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7] [2, 3, 4, 5, 6] >>> l._callmethod('__getitem__', (20,)) # equivalent to l[20] Traceback (most recent call last): ... IndexError: list index out of range ``` `_getvalue()` Return a copy of the referent. If the referent is unpicklable then this will raise an exception. `__repr__()` Return a representation of the proxy object. `__str__()` Return the representation of the referent. #### Cleanup A proxy object uses a weakref callback so that when it gets garbage collected it deregisters itself from the manager which owns its referent. A shared object gets deleted from the manager process when there are no longer any proxies referring to it. ### Process Pools One can create a pool of processes which will carry out tasks submitted to it with the [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") class. `class multiprocessing.pool.Pool([processes[, initializer[, initargs[, maxtasksperchild[, context]]]]])` A process pool object which controls a pool of worker processes to which jobs can be submitted. It supports asynchronous results with timeouts and callbacks and has a parallel map implementation. *processes* is the number of worker processes to use. If *processes* is `None` then the number returned by [`os.cpu_count()`](os#os.cpu_count "os.cpu_count") is used. If *initializer* is not `None` then each worker process will call `initializer(*initargs)` when it starts. *maxtasksperchild* is the number of tasks a worker process can complete before it will exit and be replaced with a fresh worker process, to enable unused resources to be freed. The default *maxtasksperchild* is `None`, which means worker processes will live as long as the pool. *context* can be used to specify the context used for starting the worker processes. Usually a pool is created using the function `multiprocessing.Pool()` or the [`Pool()`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") method of a context object. In both cases *context* is set appropriately. Note that the methods of the pool object should only be called by the process which created the pool. Warning [`multiprocessing.pool`](#module-multiprocessing.pool "multiprocessing.pool: Create pools of processes.") objects have internal resources that need to be properly managed (like any other resource) by using the pool as a context manager or by calling [`close()`](#multiprocessing.pool.Pool.close "multiprocessing.pool.Pool.close") and [`terminate()`](#multiprocessing.pool.Pool.terminate "multiprocessing.pool.Pool.terminate") manually. Failure to do this can lead to the process hanging on finalization. Note that is **not correct** to rely on the garbage colletor to destroy the pool as CPython does not assure that the finalizer of the pool will be called (see [`object.__del__()`](../reference/datamodel#object.__del__ "object.__del__") for more information). New in version 3.2: *maxtasksperchild* New in version 3.4: *context* Note Worker processes within a [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") typically live for the complete duration of the Pool’s work queue. A frequent pattern found in other systems (such as Apache, mod\_wsgi, etc) to free resources held by workers is to allow a worker within a pool to complete only a set amount of work before being exiting, being cleaned up and a new process spawned to replace the old one. The *maxtasksperchild* argument to the [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") exposes this ability to the end user. `apply(func[, args[, kwds]])` Call *func* with arguments *args* and keyword arguments *kwds*. It blocks until the result is ready. Given this blocks, [`apply_async()`](#multiprocessing.pool.Pool.apply_async "multiprocessing.pool.Pool.apply_async") is better suited for performing work in parallel. Additionally, *func* is only executed in one of the workers of the pool. `apply_async(func[, args[, kwds[, callback[, error_callback]]]])` A variant of the [`apply()`](#multiprocessing.pool.Pool.apply "multiprocessing.pool.Pool.apply") method which returns a [`AsyncResult`](#multiprocessing.pool.AsyncResult "multiprocessing.pool.AsyncResult") object. If *callback* is specified then it should be a callable which accepts a single argument. When the result becomes ready *callback* is applied to it, that is unless the call failed, in which case the *error\_callback* is applied instead. If *error\_callback* is specified then it should be a callable which accepts a single argument. If the target function fails, then the *error\_callback* is called with the exception instance. Callbacks should complete immediately since otherwise the thread which handles the results will get blocked. `map(func, iterable[, chunksize])` A parallel equivalent of the [`map()`](functions#map "map") built-in function (it supports only one *iterable* argument though, for multiple iterables see [`starmap()`](#multiprocessing.pool.Pool.starmap "multiprocessing.pool.Pool.starmap")). It blocks until the result is ready. This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting *chunksize* to a positive integer. Note that it may cause high memory usage for very long iterables. Consider using [`imap()`](#multiprocessing.pool.Pool.imap "multiprocessing.pool.Pool.imap") or [`imap_unordered()`](#multiprocessing.pool.Pool.imap_unordered "multiprocessing.pool.Pool.imap_unordered") with explicit *chunksize* option for better efficiency. `map_async(func, iterable[, chunksize[, callback[, error_callback]]])` A variant of the [`map()`](#multiprocessing.pool.Pool.map "multiprocessing.pool.Pool.map") method which returns a [`AsyncResult`](#multiprocessing.pool.AsyncResult "multiprocessing.pool.AsyncResult") object. If *callback* is specified then it should be a callable which accepts a single argument. When the result becomes ready *callback* is applied to it, that is unless the call failed, in which case the *error\_callback* is applied instead. If *error\_callback* is specified then it should be a callable which accepts a single argument. If the target function fails, then the *error\_callback* is called with the exception instance. Callbacks should complete immediately since otherwise the thread which handles the results will get blocked. `imap(func, iterable[, chunksize])` A lazier version of [`map()`](#multiprocessing.pool.Pool.map "multiprocessing.pool.Pool.map"). The *chunksize* argument is the same as the one used by the [`map()`](#multiprocessing.pool.Pool.map "multiprocessing.pool.Pool.map") method. For very long iterables using a large value for *chunksize* can make the job complete **much** faster than using the default value of `1`. Also if *chunksize* is `1` then the `next()` method of the iterator returned by the [`imap()`](#multiprocessing.pool.Pool.imap "multiprocessing.pool.Pool.imap") method has an optional *timeout* parameter: `next(timeout)` will raise [`multiprocessing.TimeoutError`](#multiprocessing.TimeoutError "multiprocessing.TimeoutError") if the result cannot be returned within *timeout* seconds. `imap_unordered(func, iterable[, chunksize])` The same as [`imap()`](#multiprocessing.pool.Pool.imap "multiprocessing.pool.Pool.imap") except that the ordering of the results from the returned iterator should be considered arbitrary. (Only when there is only one worker process is the order guaranteed to be “correct”.) `starmap(func, iterable[, chunksize])` Like [`map()`](#multiprocessing.pool.Pool.map "multiprocessing.pool.Pool.map") except that the elements of the *iterable* are expected to be iterables that are unpacked as arguments. Hence an *iterable* of `[(1,2), (3, 4)]` results in `[func(1,2), func(3,4)]`. New in version 3.3. `starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])` A combination of [`starmap()`](#multiprocessing.pool.Pool.starmap "multiprocessing.pool.Pool.starmap") and [`map_async()`](#multiprocessing.pool.Pool.map_async "multiprocessing.pool.Pool.map_async") that iterates over *iterable* of iterables and calls *func* with the iterables unpacked. Returns a result object. New in version 3.3. `close()` Prevents any more tasks from being submitted to the pool. Once all the tasks have been completed the worker processes will exit. `terminate()` Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected [`terminate()`](#multiprocessing.pool.Pool.terminate "multiprocessing.pool.Pool.terminate") will be called immediately. `join()` Wait for the worker processes to exit. One must call [`close()`](#multiprocessing.pool.Pool.close "multiprocessing.pool.Pool.close") or [`terminate()`](#multiprocessing.pool.Pool.terminate "multiprocessing.pool.Pool.terminate") before using [`join()`](#multiprocessing.pool.Pool.join "multiprocessing.pool.Pool.join"). New in version 3.3: Pool objects now support the context management protocol – see [Context Manager Types](stdtypes#typecontextmanager). [`__enter__()`](stdtypes#contextmanager.__enter__ "contextmanager.__enter__") returns the pool object, and [`__exit__()`](stdtypes#contextmanager.__exit__ "contextmanager.__exit__") calls [`terminate()`](#multiprocessing.pool.Pool.terminate "multiprocessing.pool.Pool.terminate"). `class multiprocessing.pool.AsyncResult` The class of the result returned by [`Pool.apply_async()`](#multiprocessing.pool.Pool.apply_async "multiprocessing.pool.Pool.apply_async") and [`Pool.map_async()`](#multiprocessing.pool.Pool.map_async "multiprocessing.pool.Pool.map_async"). `get([timeout])` Return the result when it arrives. If *timeout* is not `None` and the result does not arrive within *timeout* seconds then [`multiprocessing.TimeoutError`](#multiprocessing.TimeoutError "multiprocessing.TimeoutError") is raised. If the remote call raised an exception then that exception will be reraised by [`get()`](#multiprocessing.pool.AsyncResult.get "multiprocessing.pool.AsyncResult.get"). `wait([timeout])` Wait until the result is available or until *timeout* seconds pass. `ready()` Return whether the call has completed. `successful()` Return whether the call completed without raising an exception. Will raise [`ValueError`](exceptions#ValueError "ValueError") if the result is not ready. Changed in version 3.7: If the result is not ready, [`ValueError`](exceptions#ValueError "ValueError") is raised instead of [`AssertionError`](exceptions#AssertionError "AssertionError"). The following example demonstrates the use of a pool: ``` from multiprocessing import Pool import time def f(x): return x*x if __name__ == '__main__': with Pool(processes=4) as pool: # start 4 worker processes result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]" it = pool.imap(f, range(10)) print(next(it)) # prints "0" print(next(it)) # prints "1" print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow result = pool.apply_async(time.sleep, (10,)) print(result.get(timeout=1)) # raises multiprocessing.TimeoutError ``` ### Listeners and Clients Usually message passing between processes is done using queues or by using [`Connection`](#multiprocessing.connection.Connection "multiprocessing.connection.Connection") objects returned by [`Pipe()`](#multiprocessing.Pipe "multiprocessing.Pipe"). However, the [`multiprocessing.connection`](#module-multiprocessing.connection "multiprocessing.connection: API for dealing with sockets.") module allows some extra flexibility. It basically gives a high level message oriented API for dealing with sockets or Windows named pipes. It also has support for *digest authentication* using the [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation") module, and for polling multiple connections at the same time. `multiprocessing.connection.deliver_challenge(connection, authkey)` Send a randomly generated message to the other end of the connection and wait for a reply. If the reply matches the digest of the message using *authkey* as the key then a welcome message is sent to the other end of the connection. Otherwise [`AuthenticationError`](#multiprocessing.AuthenticationError "multiprocessing.AuthenticationError") is raised. `multiprocessing.connection.answer_challenge(connection, authkey)` Receive a message, calculate the digest of the message using *authkey* as the key, and then send the digest back. If a welcome message is not received, then [`AuthenticationError`](#multiprocessing.AuthenticationError "multiprocessing.AuthenticationError") is raised. `multiprocessing.connection.Client(address[, family[, authkey]])` Attempt to set up a connection to the listener which is using address *address*, returning a [`Connection`](#multiprocessing.connection.Connection "multiprocessing.connection.Connection"). The type of the connection is determined by *family* argument, but this can generally be omitted since it can usually be inferred from the format of *address*. (See [Address Formats](#multiprocessing-address-formats)) If *authkey* is given and not None, it should be a byte string and will be used as the secret key for an HMAC-based authentication challenge. No authentication is done if *authkey* is None. [`AuthenticationError`](#multiprocessing.AuthenticationError "multiprocessing.AuthenticationError") is raised if authentication fails. See [Authentication keys](#multiprocessing-auth-keys). `class multiprocessing.connection.Listener([address[, family[, backlog[, authkey]]]])` A wrapper for a bound socket or Windows named pipe which is ‘listening’ for connections. *address* is the address to be used by the bound socket or named pipe of the listener object. Note If an address of ‘0.0.0.0’ is used, the address will not be a connectable end point on Windows. If you require a connectable end-point, you should use ‘127.0.0.1’. *family* is the type of socket (or named pipe) to use. This can be one of the strings `'AF_INET'` (for a TCP socket), `'AF_UNIX'` (for a Unix domain socket) or `'AF_PIPE'` (for a Windows named pipe). Of these only the first is guaranteed to be available. If *family* is `None` then the family is inferred from the format of *address*. If *address* is also `None` then a default is chosen. This default is the family which is assumed to be the fastest available. See [Address Formats](#multiprocessing-address-formats). Note that if *family* is `'AF_UNIX'` and address is `None` then the socket will be created in a private temporary directory created using [`tempfile.mkstemp()`](tempfile#tempfile.mkstemp "tempfile.mkstemp"). If the listener object uses a socket then *backlog* (1 by default) is passed to the [`listen()`](socket#socket.socket.listen "socket.socket.listen") method of the socket once it has been bound. If *authkey* is given and not None, it should be a byte string and will be used as the secret key for an HMAC-based authentication challenge. No authentication is done if *authkey* is None. [`AuthenticationError`](#multiprocessing.AuthenticationError "multiprocessing.AuthenticationError") is raised if authentication fails. See [Authentication keys](#multiprocessing-auth-keys). `accept()` Accept a connection on the bound socket or named pipe of the listener object and return a [`Connection`](#multiprocessing.connection.Connection "multiprocessing.connection.Connection") object. If authentication is attempted and fails, then [`AuthenticationError`](#multiprocessing.AuthenticationError "multiprocessing.AuthenticationError") is raised. `close()` Close the bound socket or named pipe of the listener object. This is called automatically when the listener is garbage collected. However it is advisable to call it explicitly. Listener objects have the following read-only properties: `address` The address which is being used by the Listener object. `last_accepted` The address from which the last accepted connection came. If this is unavailable then it is `None`. New in version 3.3: Listener objects now support the context management protocol – see [Context Manager Types](stdtypes#typecontextmanager). [`__enter__()`](stdtypes#contextmanager.__enter__ "contextmanager.__enter__") returns the listener object, and [`__exit__()`](stdtypes#contextmanager.__exit__ "contextmanager.__exit__") calls [`close()`](#multiprocessing.connection.Listener.close "multiprocessing.connection.Listener.close"). `multiprocessing.connection.wait(object_list, timeout=None)` Wait till an object in *object\_list* is ready. Returns the list of those objects in *object\_list* which are ready. If *timeout* is a float then the call blocks for at most that many seconds. If *timeout* is `None` then it will block for an unlimited period. A negative timeout is equivalent to a zero timeout. For both Unix and Windows, an object can appear in *object\_list* if it is * a readable [`Connection`](#multiprocessing.connection.Connection "multiprocessing.connection.Connection") object; * a connected and readable [`socket.socket`](socket#socket.socket "socket.socket") object; or * the [`sentinel`](#multiprocessing.Process.sentinel "multiprocessing.Process.sentinel") attribute of a [`Process`](#multiprocessing.Process "multiprocessing.Process") object. A connection or socket object is ready when there is data available to be read from it, or the other end has been closed. **Unix**: `wait(object_list, timeout)` almost equivalent `select.select(object_list, [], [], timeout)`. The difference is that, if [`select.select()`](select#select.select "select.select") is interrupted by a signal, it can raise [`OSError`](exceptions#OSError "OSError") with an error number of `EINTR`, whereas [`wait()`](#multiprocessing.connection.wait "multiprocessing.connection.wait") will not. **Windows**: An item in *object\_list* must either be an integer handle which is waitable (according to the definition used by the documentation of the Win32 function `WaitForMultipleObjects()`) or it can be an object with a `fileno()` method which returns a socket handle or pipe handle. (Note that pipe handles and socket handles are **not** waitable handles.) New in version 3.3. **Examples** The following server code creates a listener which uses `'secret password'` as an authentication key. It then waits for a connection and sends some data to the client: ``` from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') conn.send_bytes(array('i', [42, 1729])) ``` The following code connects to the server and receives some data from the server: ``` from multiprocessing.connection import Client from array import array address = ('localhost', 6000) with Client(address, authkey=b'secret password') as conn: print(conn.recv()) # => [2.25, None, 'junk', float] print(conn.recv_bytes()) # => 'hello' arr = array('i', [0, 0, 0, 0, 0]) print(conn.recv_bytes_into(arr)) # => 8 print(arr) # => array('i', [42, 1729, 0, 0, 0]) ``` The following code uses [`wait()`](#multiprocessing.connection.wait "multiprocessing.connection.wait") to wait for messages from multiple processes at once: ``` import time, random from multiprocessing import Process, Pipe, current_process from multiprocessing.connection import wait def foo(w): for i in range(10): w.send((i, current_process().name)) w.close() if __name__ == '__main__': readers = [] for i in range(4): r, w = Pipe(duplex=False) readers.append(r) p = Process(target=foo, args=(w,)) p.start() # We close the writable end of the pipe now to be sure that # p is the only process which owns a handle for it. This # ensures that when p closes its handle for the writable end, # wait() will promptly report the readable end as being ready. w.close() while readers: for r in wait(readers): try: msg = r.recv() except EOFError: readers.remove(r) else: print(msg) ``` #### Address Formats * An `'AF_INET'` address is a tuple of the form `(hostname, port)` where *hostname* is a string and *port* is an integer. * An `'AF_UNIX'` address is a string representing a filename on the filesystem. * An `'AF_PIPE'` address is a string of the form `r'\.\pipe{PipeName}'`. To use [`Client()`](#multiprocessing.connection.Client "multiprocessing.connection.Client") to connect to a named pipe on a remote computer called *ServerName* one should use an address of the form `r'\*ServerName*\pipe{PipeName}'` instead. Note that any string beginning with two backslashes is assumed by default to be an `'AF_PIPE'` address rather than an `'AF_UNIX'` address. ### Authentication keys When one uses [`Connection.recv`](#multiprocessing.connection.Connection.recv "multiprocessing.connection.Connection.recv"), the data received is automatically unpickled. Unfortunately unpickling data from an untrusted source is a security risk. Therefore [`Listener`](#multiprocessing.connection.Listener "multiprocessing.connection.Listener") and [`Client()`](#multiprocessing.connection.Client "multiprocessing.connection.Client") use the [`hmac`](hmac#module-hmac "hmac: Keyed-Hashing for Message Authentication (HMAC) implementation") module to provide digest authentication. An authentication key is a byte string which can be thought of as a password: once a connection is established both ends will demand proof that the other knows the authentication key. (Demonstrating that both ends are using the same key does **not** involve sending the key over the connection.) If authentication is requested but no authentication key is specified then the return value of `current_process().authkey` is used (see [`Process`](#multiprocessing.Process "multiprocessing.Process")). This value will be automatically inherited by any [`Process`](#multiprocessing.Process "multiprocessing.Process") object that the current process creates. This means that (by default) all processes of a multi-process program will share a single authentication key which can be used when setting up connections between themselves. Suitable authentication keys can also be generated by using [`os.urandom()`](os#os.urandom "os.urandom"). ### Logging Some support for logging is available. Note, however, that the [`logging`](logging#module-logging "logging: Flexible event logging system for applications.") package does not use process shared locks so it is possible (depending on the handler type) for messages from different processes to get mixed up. `multiprocessing.get_logger()` Returns the logger used by [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism."). If necessary, a new one will be created. When first created the logger has level `logging.NOTSET` and no default handler. Messages sent to this logger will not by default propagate to the root logger. Note that on Windows child processes will only inherit the level of the parent process’s logger – any other customization of the logger will not be inherited. `multiprocessing.log_to_stderr(level=None)` This function performs a call to [`get_logger()`](#multiprocessing.get_logger "multiprocessing.get_logger") but in addition to returning the logger created by get\_logger, it adds a handler which sends output to [`sys.stderr`](sys#sys.stderr "sys.stderr") using format `'[%(levelname)s/%(processName)s] %(message)s'`. You can modify `levelname` of the logger by passing a `level` argument. Below is an example session with logging turned on: ``` >>> import multiprocessing, logging >>> logger = multiprocessing.log_to_stderr() >>> logger.setLevel(logging.INFO) >>> logger.warning('doomed') [WARNING/MainProcess] doomed >>> m = multiprocessing.Manager() [INFO/SyncManager-...] child process calling self.run() [INFO/SyncManager-...] created temp directory /.../pymp-... [INFO/SyncManager-...] manager serving at '/.../listener-...' >>> del m [INFO/MainProcess] sending shutdown message to manager [INFO/SyncManager-...] manager exiting with exitcode 0 ``` For a full table of logging levels, see the [`logging`](logging#module-logging "logging: Flexible event logging system for applications.") module. ### The [`multiprocessing.dummy`](#module-multiprocessing.dummy "multiprocessing.dummy: Dumb wrapper around threading.") module [`multiprocessing.dummy`](#module-multiprocessing.dummy "multiprocessing.dummy: Dumb wrapper around threading.") replicates the API of [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") but is no more than a wrapper around the [`threading`](threading#module-threading "threading: Thread-based parallelism.") module. In particular, the `Pool` function provided by [`multiprocessing.dummy`](#module-multiprocessing.dummy "multiprocessing.dummy: Dumb wrapper around threading.") returns an instance of [`ThreadPool`](#multiprocessing.pool.ThreadPool "multiprocessing.pool.ThreadPool"), which is a subclass of [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") that supports all the same method calls but uses a pool of worker threads rather than worker processes. `class multiprocessing.pool.ThreadPool([processes[, initializer[, initargs]]])` A thread pool object which controls a pool of worker threads to which jobs can be submitted. [`ThreadPool`](#multiprocessing.pool.ThreadPool "multiprocessing.pool.ThreadPool") instances are fully interface compatible with [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool") instances, and their resources must also be properly managed, either by using the pool as a context manager or by calling [`close()`](#multiprocessing.pool.Pool.close "multiprocessing.pool.Pool.close") and [`terminate()`](#multiprocessing.pool.Pool.terminate "multiprocessing.pool.Pool.terminate") manually. *processes* is the number of worker threads to use. If *processes* is `None` then the number returned by [`os.cpu_count()`](os#os.cpu_count "os.cpu_count") is used. If *initializer* is not `None` then each worker process will call `initializer(*initargs)` when it starts. Unlike [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool"), *maxtasksperchild* and *context* cannot be provided. Note A [`ThreadPool`](#multiprocessing.pool.ThreadPool "multiprocessing.pool.ThreadPool") shares the same interface as [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool"), which is designed around a pool of processes and predates the introduction of the [`concurrent.futures`](concurrent.futures#module-concurrent.futures "concurrent.futures: Execute computations concurrently using threads or processes.") module. As such, it inherits some operations that don’t make sense for a pool backed by threads, and it has its own type for representing the status of asynchronous jobs, [`AsyncResult`](#multiprocessing.pool.AsyncResult "multiprocessing.pool.AsyncResult"), that is not understood by any other libraries. Users should generally prefer to use [`concurrent.futures.ThreadPoolExecutor`](concurrent.futures#concurrent.futures.ThreadPoolExecutor "concurrent.futures.ThreadPoolExecutor"), which has a simpler interface that was designed around threads from the start, and which returns [`concurrent.futures.Future`](concurrent.futures#concurrent.futures.Future "concurrent.futures.Future") instances that are compatible with many other libraries, including [`asyncio`](asyncio#module-asyncio "asyncio: Asynchronous I/O."). Programming guidelines ---------------------- There are certain guidelines and idioms which should be adhered to when using [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism."). ### All start methods The following applies to all start methods. Avoid shared state As far as possible one should try to avoid shifting large amounts of data between processes. It is probably best to stick to using queues or pipes for communication between processes rather than using the lower level synchronization primitives. Picklability Ensure that the arguments to the methods of proxies are picklable. Thread safety of proxies Do not use a proxy object from more than one thread unless you protect it with a lock. (There is never a problem with different processes using the *same* proxy.) Joining zombie processes On Unix when a process finishes but has not been joined it becomes a zombie. There should never be very many because each time a new process starts (or [`active_children()`](#multiprocessing.active_children "multiprocessing.active_children") is called) all completed processes which have not yet been joined will be joined. Also calling a finished process’s [`Process.is_alive`](#multiprocessing.Process.is_alive "multiprocessing.Process.is_alive") will join the process. Even so it is probably good practice to explicitly join all the processes that you start. Better to inherit than pickle/unpickle When using the *spawn* or *forkserver* start methods many types from [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") need to be picklable so that child processes can use them. However, one should generally avoid sending shared objects to other processes using pipes or queues. Instead you should arrange the program so that a process which needs access to a shared resource created elsewhere can inherit it from an ancestor process. Avoid terminating processes Using the [`Process.terminate`](#multiprocessing.Process.terminate "multiprocessing.Process.terminate") method to stop a process is liable to cause any shared resources (such as locks, semaphores, pipes and queues) currently being used by the process to become broken or unavailable to other processes. Therefore it is probably best to only consider using [`Process.terminate`](#multiprocessing.Process.terminate "multiprocessing.Process.terminate") on processes which never use any shared resources. Joining processes that use queues Bear in mind that a process that has put items in a queue will wait before terminating until all the buffered items are fed by the “feeder” thread to the underlying pipe. (The child process can call the [`Queue.cancel_join_thread`](#multiprocessing.Queue.cancel_join_thread "multiprocessing.Queue.cancel_join_thread") method of the queue to avoid this behaviour.) This means that whenever you use a queue you need to make sure that all items which have been put on the queue will eventually be removed before the process is joined. Otherwise you cannot be sure that processes which have put items on the queue will terminate. Remember also that non-daemonic processes will be joined automatically. An example which will deadlock is the following: ``` from multiprocessing import Process, Queue def f(q): q.put('X' * 1000000) if __name__ == '__main__': queue = Queue() p = Process(target=f, args=(queue,)) p.start() p.join() # this deadlocks obj = queue.get() ``` A fix here would be to swap the last two lines (or simply remove the `p.join()` line). Explicitly pass resources to child processes On Unix using the *fork* start method, a child process can make use of a shared resource created in a parent process using a global resource. However, it is better to pass the object as an argument to the constructor for the child process. Apart from making the code (potentially) compatible with Windows and the other start methods this also ensures that as long as the child process is still alive the object will not be garbage collected in the parent process. This might be important if some resource is freed when the object is garbage collected in the parent process. So for instance ``` from multiprocessing import Process, Lock def f(): ... do something using "lock" ... if __name__ == '__main__': lock = Lock() for i in range(10): Process(target=f).start() ``` should be rewritten as ``` from multiprocessing import Process, Lock def f(l): ... do something using "l" ... if __name__ == '__main__': lock = Lock() for i in range(10): Process(target=f, args=(lock,)).start() ``` Beware of replacing [`sys.stdin`](sys#sys.stdin "sys.stdin") with a “file like object” [`multiprocessing`](#module-multiprocessing "multiprocessing: Process-based parallelism.") originally unconditionally called: ``` os.close(sys.stdin.fileno()) ``` in the `multiprocessing.Process._bootstrap()` method — this resulted in issues with processes-in-processes. This has been changed to: ``` sys.stdin.close() sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False) ``` Which solves the fundamental issue of processes colliding with each other resulting in a bad file descriptor error, but introduces a potential danger to applications which replace [`sys.stdin()`](sys#sys.stdin "sys.stdin") with a “file-like object” with output buffering. This danger is that if multiple processes call [`close()`](io#io.IOBase.close "io.IOBase.close") on this file-like object, it could result in the same data being flushed to the object multiple times, resulting in corruption. If you write a file-like object and implement your own caching, you can make it fork-safe by storing the pid whenever you append to the cache, and discarding the cache when the pid changes. For example: ``` @property def cache(self): pid = os.getpid() if pid != self._pid: self._pid = pid self._cache = [] return self._cache ``` For more information, see [bpo-5155](https://bugs.python.org/issue?@action=redirect&bpo=5155), [bpo-5313](https://bugs.python.org/issue?@action=redirect&bpo=5313) and [bpo-5331](https://bugs.python.org/issue?@action=redirect&bpo=5331) ### The *spawn* and *forkserver* start methods There are a few extra restriction which don’t apply to the *fork* start method. More picklability Ensure that all arguments to `Process.__init__()` are picklable. Also, if you subclass [`Process`](#multiprocessing.Process "multiprocessing.Process") then make sure that instances will be picklable when the [`Process.start`](#multiprocessing.Process.start "multiprocessing.Process.start") method is called. Global variables Bear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that [`Process.start`](#multiprocessing.Process.start "multiprocessing.Process.start") was called. However, global variables which are just module level constants cause no problems. Safe importing of main module Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process). For example, using the *spawn* or *forkserver* start method running the following module would fail with a [`RuntimeError`](exceptions#RuntimeError "RuntimeError"): ``` from multiprocessing import Process def foo(): print('hello') p = Process(target=foo) p.start() ``` Instead one should protect the “entry point” of the program by using `if __name__ == '__main__':` as follows: ``` from multiprocessing import Process, freeze_support, set_start_method def foo(): print('hello') if __name__ == '__main__': freeze_support() set_start_method('spawn') p = Process(target=foo) p.start() ``` (The `freeze_support()` line can be omitted if the program will be run normally instead of frozen.) This allows the newly spawned Python interpreter to safely import the module and then run the module’s `foo()` function. Similar restrictions apply if a pool or manager is created in the main module. Examples -------- Demonstration of how to create and use customized managers and proxies: ``` from multiprocessing import freeze_support from multiprocessing.managers import BaseManager, BaseProxy import operator ## class Foo: def f(self): print('you called Foo.f()') def g(self): print('you called Foo.g()') def _h(self): print('you called Foo._h()') # A simple generator function def baz(): for i in range(10): yield i*i # Proxy type for generator objects class GeneratorProxy(BaseProxy): _exposed_ = ['__next__'] def __iter__(self): return self def __next__(self): return self._callmethod('__next__') # Function to return the operator module def get_operator_module(): return operator ## class MyManager(BaseManager): pass # register the Foo class; make `f()` and `g()` accessible via proxy MyManager.register('Foo1', Foo) # register the Foo class; make `g()` and `_h()` accessible via proxy MyManager.register('Foo2', Foo, exposed=('g', '_h')) # register the generator function baz; use `GeneratorProxy` to make proxies MyManager.register('baz', baz, proxytype=GeneratorProxy) # register get_operator_module(); make public functions accessible via proxy MyManager.register('operator', get_operator_module) ## def test(): manager = MyManager() manager.start() print('-' * 20) f1 = manager.Foo1() f1.f() f1.g() assert not hasattr(f1, '_h') assert sorted(f1._exposed_) == sorted(['f', 'g']) print('-' * 20) f2 = manager.Foo2() f2.g() f2._h() assert not hasattr(f2, 'f') assert sorted(f2._exposed_) == sorted(['g', '_h']) print('-' * 20) it = manager.baz() for i in it: print('<%d>' % i, end=' ') print() print('-' * 20) op = manager.operator() print('op.add(23, 45) =', op.add(23, 45)) print('op.pow(2, 94) =', op.pow(2, 94)) print('op._exposed_ =', op._exposed_) ## if __name__ == '__main__': freeze_support() test() ``` Using [`Pool`](#multiprocessing.pool.Pool "multiprocessing.pool.Pool"): ``` import multiprocessing import time import random import sys # # Functions used by test code # def calculate(func, args): result = func(*args) return '%s says that %s%s = %s' % ( multiprocessing.current_process().name, func.__name__, args, result ) def calculatestar(args): return calculate(*args) def mul(a, b): time.sleep(0.5 * random.random()) return a * b def plus(a, b): time.sleep(0.5 * random.random()) return a + b def f(x): return 1.0 / (x - 5.0) def pow3(x): return x ** 3 def noop(x): pass # # Test code # def test(): PROCESSES = 4 print('Creating pool with %d processes\n' % PROCESSES) with multiprocessing.Pool(PROCESSES) as pool: # # Tests # TASKS = [(mul, (i, 7)) for i in range(10)] + \ [(plus, (i, 8)) for i in range(10)] results = [pool.apply_async(calculate, t) for t in TASKS] imap_it = pool.imap(calculatestar, TASKS) imap_unordered_it = pool.imap_unordered(calculatestar, TASKS) print('Ordered results using pool.apply_async():') for r in results: print('\t', r.get()) print() print('Ordered results using pool.imap():') for x in imap_it: print('\t', x) print() print('Unordered results using pool.imap_unordered():') for x in imap_unordered_it: print('\t', x) print() print('Ordered results using pool.map() --- will block till complete:') for x in pool.map(calculatestar, TASKS): print('\t', x) print() # # Test error handling # print('Testing error handling:') try: print(pool.apply(f, (5,))) except ZeroDivisionError: print('\tGot ZeroDivisionError as expected from pool.apply()') else: raise AssertionError('expected ZeroDivisionError') try: print(pool.map(f, list(range(10)))) except ZeroDivisionError: print('\tGot ZeroDivisionError as expected from pool.map()') else: raise AssertionError('expected ZeroDivisionError') try: print(list(pool.imap(f, list(range(10))))) except ZeroDivisionError: print('\tGot ZeroDivisionError as expected from list(pool.imap())') else: raise AssertionError('expected ZeroDivisionError') it = pool.imap(f, list(range(10))) for i in range(10): try: x = next(it) except ZeroDivisionError: if i == 5: pass except StopIteration: break else: if i == 5: raise AssertionError('expected ZeroDivisionError') assert i == 9 print('\tGot ZeroDivisionError as expected from IMapIterator.next()') print() # # Testing timeouts # print('Testing ApplyResult.get() with timeout:', end=' ') res = pool.apply_async(calculate, TASKS[0]) while 1: sys.stdout.flush() try: sys.stdout.write('\n\t%s' % res.get(0.02)) break except multiprocessing.TimeoutError: sys.stdout.write('.') print() print() print('Testing IMapIterator.next() with timeout:', end=' ') it = pool.imap(calculatestar, TASKS) while 1: sys.stdout.flush() try: sys.stdout.write('\n\t%s' % it.next(0.02)) except StopIteration: break except multiprocessing.TimeoutError: sys.stdout.write('.') print() print() if __name__ == '__main__': multiprocessing.freeze_support() test() ``` An example showing how to use queues to feed tasks to a collection of worker processes and collect the results: ``` import time import random from multiprocessing import Process, Queue, current_process, freeze_support # # Function run by worker processes # def worker(input, output): for func, args in iter(input.get, 'STOP'): result = calculate(func, args) output.put(result) # # Function used to calculate result # def calculate(func, args): result = func(*args) return '%s says that %s%s = %s' % \ (current_process().name, func.__name__, args, result) # # Functions referenced by tasks # def mul(a, b): time.sleep(0.5*random.random()) return a * b def plus(a, b): time.sleep(0.5*random.random()) return a + b # # # def test(): NUMBER_OF_PROCESSES = 4 TASKS1 = [(mul, (i, 7)) for i in range(20)] TASKS2 = [(plus, (i, 8)) for i in range(10)] # Create queues task_queue = Queue() done_queue = Queue() # Submit tasks for task in TASKS1: task_queue.put(task) # Start worker processes for i in range(NUMBER_OF_PROCESSES): Process(target=worker, args=(task_queue, done_queue)).start() # Get and print results print('Unordered results:') for i in range(len(TASKS1)): print('\t', done_queue.get()) # Add more tasks using `put()` for task in TASKS2: task_queue.put(task) # Get and print some more results for i in range(len(TASKS2)): print('\t', done_queue.get()) # Tell child processes to stop for i in range(NUMBER_OF_PROCESSES): task_queue.put('STOP') if __name__ == '__main__': freeze_support() test() ```
programming_docs
python urllib.parse — Parse URLs into components urllib.parse — Parse URLs into components ========================================= **Source code:** [Lib/urllib/parse.py](https://github.com/python/cpython/tree/3.9/Lib/urllib/parse.py) This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.” The module has been designed to match the Internet RFC on Relative Uniform Resource Locators. It supports the following URL schemes: `file`, `ftp`, `gopher`, `hdl`, `http`, `https`, `imap`, `mailto`, `mms`, `news`, `nntp`, `prospero`, `rsync`, `rtsp`, `rtspu`, `sftp`, `shttp`, `sip`, `sips`, `snews`, `svn`, `svn+ssh`, `telnet`, `wais`, `ws`, `wss`. The [`urllib.parse`](#module-urllib.parse "urllib.parse: Parse URLs into or assemble them from components.") module defines functions that fall into two broad categories: URL parsing and URL quoting. These are covered in detail in the following sections. URL Parsing ----------- The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string. `urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)` Parse a URL into six components, returning a 6-item [named tuple](../glossary#term-named-tuple). This corresponds to the general structure of a URL: `scheme://netloc/path;parameters?query#fragment`. Each tuple item is a string, possibly empty. The components are not broken up into smaller parts (for example, the network location is a single string), and % escapes are not expanded. The delimiters as shown above are not part of the result, except for a leading slash in the *path* component, which is retained if present. For example: ``` >>> from urllib.parse import urlparse >>> urlparse("scheme://netloc/path;parameters?query#fragment") ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', params='', query='query', fragment='fragment') >>> o = urlparse("http://docs.python.org:80/3/library/urllib.parse.html?" ... "highlight=params#url-parsing") >>> o ParseResult(scheme='http', netloc='docs.python.org:80', path='/3/library/urllib.parse.html', params='', query='highlight=params', fragment='url-parsing') >>> o.scheme 'http' >>> o.netloc 'docs.python.org:80' >>> o.hostname 'docs.python.org' >>> o.port 80 >>> o._replace(fragment="").geturl() 'http://docs.python.org:80/3/library/urllib.parse.html?highlight=params' ``` Following the syntax specifications in [**RFC 1808**](https://tools.ietf.org/html/rfc1808.html), urlparse recognizes a netloc only if it is properly introduced by ‘//’. Otherwise the input is presumed to be a relative URL and thus to start with a path component. ``` >>> from urllib.parse import urlparse >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html') ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='') >>> urlparse('www.cwi.nl/%7Eguido/Python.html') ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html', params='', query='', fragment='') >>> urlparse('help/Python.html') ParseResult(scheme='', netloc='', path='help/Python.html', params='', query='', fragment='') ``` The *scheme* argument gives the default addressing scheme, to be used only if the URL does not specify one. It should be the same type (text or bytes) as *urlstring*, except that the default value `''` is always allowed, and is automatically converted to `b''` if appropriate. If the *allow\_fragments* argument is false, fragment identifiers are not recognized. Instead, they are parsed as part of the path, parameters or query component, and `fragment` is set to the empty string in the return value. The return value is a [named tuple](../glossary#term-named-tuple), which means that its items can be accessed by index or as named attributes, which are: | Attribute | Index | Value | Value if not present | | --- | --- | --- | --- | | `scheme` | 0 | URL scheme specifier | *scheme* parameter | | `netloc` | 1 | Network location part | empty string | | `path` | 2 | Hierarchical path | empty string | | `params` | 3 | No longer used | always an empty string | | `query` | 4 | Query component | empty string | | `fragment` | 5 | Fragment identifier | empty string | | `username` | | User name | [`None`](constants#None "None") | | `password` | | Password | [`None`](constants#None "None") | | `hostname` | | Host name (lower case) | [`None`](constants#None "None") | | `port` | | Port number as integer, if present | [`None`](constants#None "None") | Reading the `port` attribute will raise a [`ValueError`](exceptions#ValueError "ValueError") if an invalid port is specified in the URL. See section [Structured Parse Results](#urlparse-result-object) for more information on the result object. Unmatched square brackets in the `netloc` attribute will raise a [`ValueError`](exceptions#ValueError "ValueError"). Characters in the `netloc` attribute that decompose under NFKC normalization (as used by the IDNA encoding) into any of `/`, `?`, `#`, `@`, or `:` will raise a [`ValueError`](exceptions#ValueError "ValueError"). If the URL is decomposed before parsing, no error will be raised. As is the case with all named tuples, the subclass has a few additional methods and attributes that are particularly useful. One such method is `_replace()`. The `_replace()` method will return a new ParseResult object replacing specified fields with new values. ``` >>> from urllib.parse import urlparse >>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html') >>> u ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='') >>> u._replace(scheme='http') ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='') ``` Changed in version 3.2: Added IPv6 URL parsing capabilities. Changed in version 3.3: The fragment is now parsed for all URL schemes (unless *allow\_fragment* is false), in accordance with [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html). Previously, a whitelist of schemes that support fragments existed. Changed in version 3.6: Out-of-range port numbers now raise [`ValueError`](exceptions#ValueError "ValueError"), instead of returning [`None`](constants#None "None"). Changed in version 3.8: Characters that affect netloc parsing under NFKC normalization will now raise [`ValueError`](exceptions#ValueError "ValueError"). `urllib.parse.parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')` Parse a query string given as a string argument (data of type *application/x-www-form-urlencoded*). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name. The optional argument *keep\_blank\_values* is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. The optional argument *strict\_parsing* is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a [`ValueError`](exceptions#ValueError "ValueError") exception. The optional *encoding* and *errors* parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the [`bytes.decode()`](stdtypes#bytes.decode "bytes.decode") method. The optional argument *max\_num\_fields* is the maximum number of fields to read. If set, then throws a [`ValueError`](exceptions#ValueError "ValueError") if there are more than *max\_num\_fields* fields read. The optional argument *separator* is the symbol to use for separating the query arguments. It defaults to `&`. Use the [`urllib.parse.urlencode()`](#urllib.parse.urlencode "urllib.parse.urlencode") function (with the `doseq` parameter set to `True`) to convert such dictionaries into query strings. Changed in version 3.2: Add *encoding* and *errors* parameters. Changed in version 3.8: Added *max\_num\_fields* parameter. Changed in version 3.9.2: Added *separator* parameter with the default value of `&`. Python versions earlier than Python 3.9.2 allowed using both `;` and `&` as query parameter separator. This has been changed to allow only a single separator key, with `&` as the default separator. `urllib.parse.parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')` Parse a query string given as a string argument (data of type *application/x-www-form-urlencoded*). Data are returned as a list of name, value pairs. The optional argument *keep\_blank\_values* is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. The optional argument *strict\_parsing* is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a [`ValueError`](exceptions#ValueError "ValueError") exception. The optional *encoding* and *errors* parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the [`bytes.decode()`](stdtypes#bytes.decode "bytes.decode") method. The optional argument *max\_num\_fields* is the maximum number of fields to read. If set, then throws a [`ValueError`](exceptions#ValueError "ValueError") if there are more than *max\_num\_fields* fields read. The optional argument *separator* is the symbol to use for separating the query arguments. It defaults to `&`. Use the [`urllib.parse.urlencode()`](#urllib.parse.urlencode "urllib.parse.urlencode") function to convert such lists of pairs into query strings. Changed in version 3.2: Add *encoding* and *errors* parameters. Changed in version 3.8: Added *max\_num\_fields* parameter. Changed in version 3.9.2: Added *separator* parameter with the default value of `&`. Python versions earlier than Python 3.9.2 allowed using both `;` and `&` as query parameter separator. This has been changed to allow only a single separator key, with `&` as the default separator. `urllib.parse.urlunparse(parts)` Construct a URL from a tuple as returned by `urlparse()`. The *parts* argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a `?` with an empty query; the RFC states that these are equivalent). `urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True)` This is similar to [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse"), but does not split the params from the URL. This should generally be used instead of [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse") if the more recent URL syntax allowing parameters to be applied to each segment of the *path* portion of the URL (see [**RFC 2396**](https://tools.ietf.org/html/rfc2396.html)) is wanted. A separate function is needed to separate the path segments and parameters. This function returns a 5-item [named tuple](../glossary#term-named-tuple): ``` (addressing scheme, network location, path, query, fragment identifier). ``` The return value is a [named tuple](../glossary#term-named-tuple), its items can be accessed by index or as named attributes: | Attribute | Index | Value | Value if not present | | --- | --- | --- | --- | | `scheme` | 0 | URL scheme specifier | *scheme* parameter | | `netloc` | 1 | Network location part | empty string | | `path` | 2 | Hierarchical path | empty string | | `query` | 3 | Query component | empty string | | `fragment` | 4 | Fragment identifier | empty string | | `username` | | User name | [`None`](constants#None "None") | | `password` | | Password | [`None`](constants#None "None") | | `hostname` | | Host name (lower case) | [`None`](constants#None "None") | | `port` | | Port number as integer, if present | [`None`](constants#None "None") | Reading the `port` attribute will raise a [`ValueError`](exceptions#ValueError "ValueError") if an invalid port is specified in the URL. See section [Structured Parse Results](#urlparse-result-object) for more information on the result object. Unmatched square brackets in the `netloc` attribute will raise a [`ValueError`](exceptions#ValueError "ValueError"). Characters in the `netloc` attribute that decompose under NFKC normalization (as used by the IDNA encoding) into any of `/`, `?`, `#`, `@`, or `:` will raise a [`ValueError`](exceptions#ValueError "ValueError"). If the URL is decomposed before parsing, no error will be raised. Following the [WHATWG spec](https://url.spec.whatwg.org/#concept-basic-url-parser) that updates RFC 3986, ASCII newline `\n`, `\r` and tab `\t` characters are stripped from the URL. Changed in version 3.6: Out-of-range port numbers now raise [`ValueError`](exceptions#ValueError "ValueError"), instead of returning [`None`](constants#None "None"). Changed in version 3.8: Characters that affect netloc parsing under NFKC normalization will now raise [`ValueError`](exceptions#ValueError "ValueError"). Changed in version 3.9.5: ASCII newline and tab characters are stripped from the URL. `urllib.parse.urlunsplit(parts)` Combine the elements of a tuple as returned by [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") into a complete URL as a string. The *parts* argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). `urllib.parse.urljoin(base, url, allow_fragments=True)` Construct a full (“absolute”) URL by combining a “base URL” (*base*) with another URL (*url*). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL. For example: ``` >>> from urllib.parse import urljoin >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') 'http://www.cwi.nl/%7Eguido/FAQ.html' ``` The *allow\_fragments* argument has the same meaning and default as for [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse"). Note If *url* is an absolute URL (that is, it starts with `//` or `scheme://`), the *url*’s hostname and/or scheme will be present in the result. For example: ``` >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', ... '//www.python.org/%7Eguido') 'http://www.python.org/%7Eguido' ``` If you do not want that behavior, preprocess the *url* with [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") and [`urlunsplit()`](#urllib.parse.urlunsplit "urllib.parse.urlunsplit"), removing possible *scheme* and *netloc* parts. Changed in version 3.5: Behavior updated to match the semantics defined in [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html). `urllib.parse.urldefrag(url)` If *url* contains a fragment identifier, return a modified version of *url* with no fragment identifier, and the fragment identifier as a separate string. If there is no fragment identifier in *url*, return *url* unmodified and an empty string. The return value is a [named tuple](../glossary#term-named-tuple), its items can be accessed by index or as named attributes: | Attribute | Index | Value | Value if not present | | --- | --- | --- | --- | | `url` | 0 | URL with no fragment | empty string | | `fragment` | 1 | Fragment identifier | empty string | See section [Structured Parse Results](#urlparse-result-object) for more information on the result object. Changed in version 3.2: Result is a structured object rather than a simple 2-tuple. `urllib.parse.unwrap(url)` Extract the url from a wrapped URL (that is, a string formatted as `<URL:scheme://host/path>`, `<scheme://host/path>`, `URL:scheme://host/path` or `scheme://host/path`). If *url* is not a wrapped URL, it is returned without changes. Parsing ASCII Encoded Bytes --------------------------- The URL parsing functions were originally designed to operate on character strings only. In practice, it is useful to be able to manipulate properly quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the URL parsing functions in this module all operate on [`bytes`](stdtypes#bytes "bytes") and [`bytearray`](stdtypes#bytearray "bytearray") objects in addition to [`str`](stdtypes#str "str") objects. If [`str`](stdtypes#str "str") data is passed in, the result will also contain only [`str`](stdtypes#str "str") data. If [`bytes`](stdtypes#bytes "bytes") or [`bytearray`](stdtypes#bytearray "bytearray") data is passed in, the result will contain only [`bytes`](stdtypes#bytes "bytes") data. Attempting to mix [`str`](stdtypes#str "str") data with [`bytes`](stdtypes#bytes "bytes") or [`bytearray`](stdtypes#bytearray "bytearray") in a single function call will result in a [`TypeError`](exceptions#TypeError "TypeError") being raised, while attempting to pass in non-ASCII byte values will trigger [`UnicodeDecodeError`](exceptions#UnicodeDecodeError "UnicodeDecodeError"). To support easier conversion of result objects between [`str`](stdtypes#str "str") and [`bytes`](stdtypes#bytes "bytes"), all return values from URL parsing functions provide either an `encode()` method (when the result contains [`str`](stdtypes#str "str") data) or a `decode()` method (when the result contains [`bytes`](stdtypes#bytes "bytes") data). The signatures of these methods match those of the corresponding [`str`](stdtypes#str "str") and [`bytes`](stdtypes#bytes "bytes") methods (except that the default encoding is `'ascii'` rather than `'utf-8'`). Each produces a value of a corresponding type that contains either [`bytes`](stdtypes#bytes "bytes") data (for `encode()` methods) or [`str`](stdtypes#str "str") data (for `decode()` methods). Applications that need to operate on potentially improperly quoted URLs that may contain non-ASCII data will need to do their own decoding from bytes to characters before invoking the URL parsing methods. The behaviour described in this section applies only to the URL parsing functions. The URL quoting functions use their own rules when producing or consuming byte sequences as detailed in the documentation of the individual URL quoting functions. Changed in version 3.2: URL parsing functions now accept ASCII encoded byte sequences Structured Parse Results ------------------------ The result objects from the [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse"), [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") and [`urldefrag()`](#urllib.parse.urldefrag "urllib.parse.urldefrag") functions are subclasses of the [`tuple`](stdtypes#tuple "tuple") type. These subclasses add the attributes listed in the documentation for those functions, the encoding and decoding support described in the previous section, as well as an additional method: `urllib.parse.SplitResult.geturl()` Return the re-combined version of the original URL as a string. This may differ from the original URL in that the scheme may be normalized to lower case and empty components may be dropped. Specifically, empty parameters, queries, and fragment identifiers will be removed. For [`urldefrag()`](#urllib.parse.urldefrag "urllib.parse.urldefrag") results, only empty fragment identifiers will be removed. For [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") and [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse") results, all noted changes will be made to the URL returned by this method. The result of this method remains unchanged if passed back through the original parsing function: ``` >>> from urllib.parse import urlsplit >>> url = 'HTTP://www.Python.org/doc/#' >>> r1 = urlsplit(url) >>> r1.geturl() 'http://www.Python.org/doc/' >>> r2 = urlsplit(r1.geturl()) >>> r2.geturl() 'http://www.Python.org/doc/' ``` The following classes provide the implementations of the structured parse results when operating on [`str`](stdtypes#str "str") objects: `class urllib.parse.DefragResult(url, fragment)` Concrete class for [`urldefrag()`](#urllib.parse.urldefrag "urllib.parse.urldefrag") results containing [`str`](stdtypes#str "str") data. The `encode()` method returns a [`DefragResultBytes`](#urllib.parse.DefragResultBytes "urllib.parse.DefragResultBytes") instance. New in version 3.2. `class urllib.parse.ParseResult(scheme, netloc, path, params, query, fragment)` Concrete class for [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse") results containing [`str`](stdtypes#str "str") data. The `encode()` method returns a [`ParseResultBytes`](#urllib.parse.ParseResultBytes "urllib.parse.ParseResultBytes") instance. `class urllib.parse.SplitResult(scheme, netloc, path, query, fragment)` Concrete class for [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") results containing [`str`](stdtypes#str "str") data. The `encode()` method returns a [`SplitResultBytes`](#urllib.parse.SplitResultBytes "urllib.parse.SplitResultBytes") instance. The following classes provide the implementations of the parse results when operating on [`bytes`](stdtypes#bytes "bytes") or [`bytearray`](stdtypes#bytearray "bytearray") objects: `class urllib.parse.DefragResultBytes(url, fragment)` Concrete class for [`urldefrag()`](#urllib.parse.urldefrag "urllib.parse.urldefrag") results containing [`bytes`](stdtypes#bytes "bytes") data. The `decode()` method returns a [`DefragResult`](#urllib.parse.DefragResult "urllib.parse.DefragResult") instance. New in version 3.2. `class urllib.parse.ParseResultBytes(scheme, netloc, path, params, query, fragment)` Concrete class for [`urlparse()`](#urllib.parse.urlparse "urllib.parse.urlparse") results containing [`bytes`](stdtypes#bytes "bytes") data. The `decode()` method returns a [`ParseResult`](#urllib.parse.ParseResult "urllib.parse.ParseResult") instance. New in version 3.2. `class urllib.parse.SplitResultBytes(scheme, netloc, path, query, fragment)` Concrete class for [`urlsplit()`](#urllib.parse.urlsplit "urllib.parse.urlsplit") results containing [`bytes`](stdtypes#bytes "bytes") data. The `decode()` method returns a [`SplitResult`](#urllib.parse.SplitResult "urllib.parse.SplitResult") instance. New in version 3.2. URL Quoting ----------- The URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component if that task isn’t already covered by the URL parsing functions above. `urllib.parse.quote(string, safe='/', encoding=None, errors=None)` Replace special characters in *string* using the `%xx` escape. Letters, digits, and the characters `'_.-~'` are never quoted. By default, this function is intended for quoting the path section of a URL. The optional *safe* parameter specifies additional ASCII characters that should not be quoted — its default value is `'/'`. *string* may be either a [`str`](stdtypes#str "str") or a [`bytes`](stdtypes#bytes "bytes") object. Changed in version 3.7: Moved from [**RFC 2396**](https://tools.ietf.org/html/rfc2396.html) to [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html) for quoting URL strings. “~” is now included in the set of unreserved characters. The optional *encoding* and *errors* parameters specify how to deal with non-ASCII characters, as accepted by the [`str.encode()`](stdtypes#str.encode "str.encode") method. *encoding* defaults to `'utf-8'`. *errors* defaults to `'strict'`, meaning unsupported characters raise a [`UnicodeEncodeError`](exceptions#UnicodeEncodeError "UnicodeEncodeError"). *encoding* and *errors* must not be supplied if *string* is a [`bytes`](stdtypes#bytes "bytes"), or a [`TypeError`](exceptions#TypeError "TypeError") is raised. Note that `quote(string, safe, encoding, errors)` is equivalent to `quote_from_bytes(string.encode(encoding, errors), safe)`. Example: `quote('/El Niño/')` yields `'/El%20Ni%C3%B1o/'`. `urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)` Like [`quote()`](#urllib.parse.quote "urllib.parse.quote"), but also replace spaces with plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in *safe*. It also does not have *safe* default to `'/'`. Example: `quote_plus('/El Niño/')` yields `'%2FEl+Ni%C3%B1o%2F'`. `urllib.parse.quote_from_bytes(bytes, safe='/')` Like [`quote()`](#urllib.parse.quote "urllib.parse.quote"), but accepts a [`bytes`](stdtypes#bytes "bytes") object rather than a [`str`](stdtypes#str "str"), and does not perform string-to-bytes encoding. Example: `quote_from_bytes(b'a&\xef')` yields `'a%26%EF'`. `urllib.parse.unquote(string, encoding='utf-8', errors='replace')` Replace `%xx` escapes with their single-character equivalent. The optional *encoding* and *errors* parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the [`bytes.decode()`](stdtypes#bytes.decode "bytes.decode") method. *string* may be either a [`str`](stdtypes#str "str") or a [`bytes`](stdtypes#bytes "bytes") object. *encoding* defaults to `'utf-8'`. *errors* defaults to `'replace'`, meaning invalid sequences are replaced by a placeholder character. Example: `unquote('/El%20Ni%C3%B1o/')` yields `'/El Niño/'`. Changed in version 3.9: *string* parameter supports bytes and str objects (previously only str). `urllib.parse.unquote_plus(string, encoding='utf-8', errors='replace')` Like [`unquote()`](#urllib.parse.unquote "urllib.parse.unquote"), but also replace plus signs with spaces, as required for unquoting HTML form values. *string* must be a [`str`](stdtypes#str "str"). Example: `unquote_plus('/El+Ni%C3%B1o/')` yields `'/El Niño/'`. `urllib.parse.unquote_to_bytes(string)` Replace `%xx` escapes with their single-octet equivalent, and return a [`bytes`](stdtypes#bytes "bytes") object. *string* may be either a [`str`](stdtypes#str "str") or a [`bytes`](stdtypes#bytes "bytes") object. If it is a [`str`](stdtypes#str "str"), unescaped non-ASCII characters in *string* are encoded into UTF-8 bytes. Example: `unquote_to_bytes('a%26%EF')` yields `b'a&\xef'`. `urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)` Convert a mapping object or a sequence of two-element tuples, which may contain [`str`](stdtypes#str "str") or [`bytes`](stdtypes#bytes "bytes") objects, to a percent-encoded ASCII text string. If the resultant string is to be used as a *data* for POST operation with the [`urlopen()`](urllib.request#urllib.request.urlopen "urllib.request.urlopen") function, then it should be encoded to bytes, otherwise it would result in a [`TypeError`](exceptions#TypeError "TypeError"). The resulting string is a series of `key=value` pairs separated by `'&'` characters, where both *key* and *value* are quoted using the *quote\_via* function. By default, [`quote_plus()`](#urllib.parse.quote_plus "urllib.parse.quote_plus") is used to quote the values, which means spaces are quoted as a `'+'` character and ‘/’ characters are encoded as `%2F`, which follows the standard for GET requests (`application/x-www-form-urlencoded`). An alternate function that can be passed as *quote\_via* is [`quote()`](#urllib.parse.quote "urllib.parse.quote"), which will encode spaces as `%20` and not encode ‘/’ characters. For maximum control of what is quoted, use `quote` and specify a value for *safe*. When a sequence of two-element tuples is used as the *query* argument, the first element of each tuple is a key and the second is a value. The value element in itself can be a sequence and in that case, if the optional parameter *doseq* evaluates to `True`, individual `key=value` pairs separated by `'&'` are generated for each element of the value sequence for the key. The order of parameters in the encoded string will match the order of parameter tuples in the sequence. The *safe*, *encoding*, and *errors* parameters are passed down to *quote\_via* (the *encoding* and *errors* parameters are only passed when a query element is a [`str`](stdtypes#str "str")). To reverse this encoding process, [`parse_qs()`](#urllib.parse.parse_qs "urllib.parse.parse_qs") and [`parse_qsl()`](#urllib.parse.parse_qsl "urllib.parse.parse_qsl") are provided in this module to parse query strings into Python data structures. Refer to [urllib examples](urllib.request#urllib-examples) to find out how the [`urllib.parse.urlencode()`](#urllib.parse.urlencode "urllib.parse.urlencode") method can be used for generating the query string of a URL or data for a POST request. Changed in version 3.2: *query* supports bytes and string objects. New in version 3.5: *quote\_via* parameter. See also [WHATWG](https://url.spec.whatwg.org/) - URL Living standard Working Group for the URL Standard that defines URLs, domains, IP addresses, the application/x-www-form-urlencoded format, and their API. [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html) - Uniform Resource Identifiers This is the current standard (STD66). Any changes to urllib.parse module should conform to this. Certain deviations could be observed, which are mostly for backward compatibility purposes and for certain de-facto parsing requirements as commonly observed in major browsers. [**RFC 2732**](https://tools.ietf.org/html/rfc2732.html) - Format for Literal IPv6 Addresses in URL’s. This specifies the parsing requirements of IPv6 URLs. [**RFC 2396**](https://tools.ietf.org/html/rfc2396.html) - Uniform Resource Identifiers (URI): Generic Syntax Document describing the generic syntactic requirements for both Uniform Resource Names (URNs) and Uniform Resource Locators (URLs). [**RFC 2368**](https://tools.ietf.org/html/rfc2368.html) - The mailto URL scheme. Parsing requirements for mailto URL schemes. [**RFC 1808**](https://tools.ietf.org/html/rfc1808.html) - Relative Uniform Resource Locators This Request For Comments includes the rules for joining an absolute and a relative URL, including a fair number of “Abnormal Examples” which govern the treatment of border cases. [**RFC 1738**](https://tools.ietf.org/html/rfc1738.html) - Uniform Resource Locators (URL) This specifies the formal syntax and semantics of absolute URLs.
programming_docs
python Unix Specific Services Unix Specific Services ====================== The modules described in this chapter provide interfaces to features that are unique to the Unix operating system, or in some cases to some or many variants of it. Here’s an overview: * [`posix` — The most common POSIX system calls](posix) + [Large File Support](posix#large-file-support) + [Notable Module Contents](posix#notable-module-contents) * [`pwd` — The password database](pwd) * [`grp` — The group database](grp) * [`termios` — POSIX style tty control](termios) + [Example](termios#example) * [`tty` — Terminal control functions](tty) * [`pty` — Pseudo-terminal utilities](pty) + [Example](pty#example) * [`fcntl` — The `fcntl` and `ioctl` system calls](fcntl) * [`resource` — Resource usage information](resource) + [Resource Limits](resource#resource-limits) + [Resource Usage](resource#resource-usage) * [`syslog` — Unix syslog library routines](syslog) + [Examples](syslog#examples) - [Simple example](syslog#simple-example) python Binary Data Services Binary Data Services ==================== The modules described in this chapter provide some basic services operations for manipulation of binary data. Other operations on binary data, specifically in relation to file formats and network protocols, are described in the relevant sections. Some libraries described under [Text Processing Services](text#textservices) also work with either ASCII-compatible binary formats (for example, [`re`](re#module-re "re: Regular expression operations.")) or all binary data (for example, [`difflib`](difflib#module-difflib "difflib: Helpers for computing differences between objects.")). In addition, see the documentation for Python’s built-in binary data types in [Binary Sequence Types — bytes, bytearray, memoryview](stdtypes#binaryseq). * [`struct` — Interpret bytes as packed binary data](struct) + [Functions and Exceptions](struct#functions-and-exceptions) + [Format Strings](struct#format-strings) - [Byte Order, Size, and Alignment](struct#byte-order-size-and-alignment) - [Format Characters](struct#format-characters) - [Examples](struct#examples) + [Classes](struct#classes) * [`codecs` — Codec registry and base classes](codecs) + [Codec Base Classes](codecs#codec-base-classes) - [Error Handlers](codecs#error-handlers) - [Stateless Encoding and Decoding](codecs#stateless-encoding-and-decoding) - [Incremental Encoding and Decoding](codecs#incremental-encoding-and-decoding) * [IncrementalEncoder Objects](codecs#incrementalencoder-objects) * [IncrementalDecoder Objects](codecs#incrementaldecoder-objects) - [Stream Encoding and Decoding](codecs#stream-encoding-and-decoding) * [StreamWriter Objects](codecs#streamwriter-objects) * [StreamReader Objects](codecs#streamreader-objects) * [StreamReaderWriter Objects](codecs#streamreaderwriter-objects) * [StreamRecoder Objects](codecs#streamrecoder-objects) + [Encodings and Unicode](codecs#encodings-and-unicode) + [Standard Encodings](codecs#standard-encodings) + [Python Specific Encodings](codecs#python-specific-encodings) - [Text Encodings](codecs#text-encodings) - [Binary Transforms](codecs#binary-transforms) - [Text Transforms](codecs#text-transforms) + [`encodings.idna` — Internationalized Domain Names in Applications](codecs#module-encodings.idna) + [`encodings.mbcs` — Windows ANSI codepage](codecs#module-encodings.mbcs) + [`encodings.utf_8_sig` — UTF-8 codec with BOM signature](codecs#module-encodings.utf_8_sig) python The Python Standard Library The Python Standard Library =========================== While [The Python Language Reference](../reference/index#reference-index) describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions. Python’s standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs. The Python installers for the Windows platform usually include the entire standard library and often also include many additional components. For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components. In addition to the standard library, there is a growing collection of several thousand components (from individual programs and modules to packages and entire application development frameworks), available from the [Python Package Index](https://pypi.org). * [Introduction](https://docs.python.org/3.9/library/intro.html) + [Notes on availability](https://docs.python.org/3.9/library/intro.html#notes-on-availability) * [Built-in Functions](functions) * [Built-in Constants](constants) + [Constants added by the `site` module](constants#constants-added-by-the-site-module) * [Built-in Types](stdtypes) + [Truth Value Testing](stdtypes#truth-value-testing) + [Boolean Operations — `and`, `or`, `not`](stdtypes#boolean-operations-and-or-not) + [Comparisons](stdtypes#comparisons) + [Numeric Types — `int`, `float`, `complex`](stdtypes#numeric-types-int-float-complex) + [Iterator Types](stdtypes#iterator-types) + [Sequence Types — `list`, `tuple`, `range`](stdtypes#sequence-types-list-tuple-range) + [Text Sequence Type — `str`](stdtypes#text-sequence-type-str) + [Binary Sequence Types — `bytes`, `bytearray`, `memoryview`](stdtypes#binary-sequence-types-bytes-bytearray-memoryview) + [Set Types — `set`, `frozenset`](stdtypes#set-types-set-frozenset) + [Mapping Types — `dict`](stdtypes#mapping-types-dict) + [Context Manager Types](stdtypes#context-manager-types) + [Generic Alias Type](stdtypes#generic-alias-type) + [Other Built-in Types](stdtypes#other-built-in-types) + [Special Attributes](stdtypes#special-attributes) + [Integer string conversion length limitation](stdtypes#integer-string-conversion-length-limitation) * [Built-in Exceptions](exceptions) + [Exception context](exceptions#exception-context) + [Inheriting from built-in exceptions](exceptions#inheriting-from-built-in-exceptions) + [Base classes](exceptions#base-classes) + [Concrete exceptions](exceptions#concrete-exceptions) + [Warnings](exceptions#warnings) + [Exception hierarchy](exceptions#exception-hierarchy) * [Text Processing Services](text) + [`string` — Common string operations](string) + [`re` — Regular expression operations](re) + [`difflib` — Helpers for computing deltas](difflib) + [`textwrap` — Text wrapping and filling](textwrap) + [`unicodedata` — Unicode Database](unicodedata) + [`stringprep` — Internet String Preparation](stringprep) + [`readline` — GNU readline interface](readline) + [`rlcompleter` — Completion function for GNU readline](rlcompleter) * [Binary Data Services](binary) + [`struct` — Interpret bytes as packed binary data](struct) + [`codecs` — Codec registry and base classes](codecs) * [Data Types](datatypes) + [`datetime` — Basic date and time types](datetime) + [`zoneinfo` — IANA time zone support](zoneinfo) + [`calendar` — General calendar-related functions](calendar) + [`collections` — Container datatypes](collections) + [`collections.abc` — Abstract Base Classes for Containers](collections.abc) + [`heapq` — Heap queue algorithm](heapq) + [`bisect` — Array bisection algorithm](bisect) + [`array` — Efficient arrays of numeric values](array) + [`weakref` — Weak references](weakref) + [`types` — Dynamic type creation and names for built-in types](types) + [`copy` — Shallow and deep copy operations](copy) + [`pprint` — Data pretty printer](pprint) + [`reprlib` — Alternate `repr()` implementation](reprlib) + [`enum` — Support for enumerations](enum) + [`graphlib` — Functionality to operate with graph-like structures](graphlib) * [Numeric and Mathematical Modules](numeric) + [`numbers` — Numeric abstract base classes](numbers) + [`math` — Mathematical functions](math) + [`cmath` — Mathematical functions for complex numbers](cmath) + [`decimal` — Decimal fixed point and floating point arithmetic](decimal) + [`fractions` — Rational numbers](fractions) + [`random` — Generate pseudo-random numbers](random) + [`statistics` — Mathematical statistics functions](statistics) * [Functional Programming Modules](functional) + [`itertools` — Functions creating iterators for efficient looping](itertools) + [`functools` — Higher-order functions and operations on callable objects](functools) + [`operator` — Standard operators as functions](operator) * [File and Directory Access](filesys) + [`pathlib` — Object-oriented filesystem paths](pathlib) + [`os.path` — Common pathname manipulations](os.path) + [`fileinput` — Iterate over lines from multiple input streams](fileinput) + [`stat` — Interpreting `stat()` results](stat) + [`filecmp` — File and Directory Comparisons](filecmp) + [`tempfile` — Generate temporary files and directories](tempfile) + [`glob` — Unix style pathname pattern expansion](glob) + [`fnmatch` — Unix filename pattern matching](fnmatch) + [`linecache` — Random access to text lines](linecache) + [`shutil` — High-level file operations](shutil) * [Data Persistence](persistence) + [`pickle` — Python object serialization](pickle) + [`copyreg` — Register `pickle` support functions](copyreg) + [`shelve` — Python object persistence](shelve) + [`marshal` — Internal Python object serialization](marshal) + [`dbm` — Interfaces to Unix “databases”](dbm) + [`sqlite3` — DB-API 2.0 interface for SQLite databases](sqlite3) * [Data Compression and Archiving](archiving) + [`zlib` — Compression compatible with **gzip**](zlib) + [`gzip` — Support for **gzip** files](gzip) + [`bz2` — Support for **bzip2** compression](bz2) + [`lzma` — Compression using the LZMA algorithm](lzma) + [`zipfile` — Work with ZIP archives](zipfile) + [`tarfile` — Read and write tar archive files](tarfile) * [File Formats](fileformats) + [`csv` — CSV File Reading and Writing](csv) + [`configparser` — Configuration file parser](configparser) + [`netrc` — netrc file processing](netrc) + [`plistlib` — Generate and parse Apple `.plist` files](plistlib) * [Cryptographic Services](crypto) + [`hashlib` — Secure hashes and message digests](hashlib) + [`hmac` — Keyed-Hashing for Message Authentication](hmac) + [`secrets` — Generate secure random numbers for managing secrets](secrets) * [Generic Operating System Services](allos) + [`os` — Miscellaneous operating system interfaces](os) + [`io` — Core tools for working with streams](io) + [`time` — Time access and conversions](time) + [`argparse` — Parser for command-line options, arguments and sub-commands](argparse) + [`getopt` — C-style parser for command line options](getopt) + [`logging` — Logging facility for Python](logging) + [`logging.config` — Logging configuration](logging.config) + [`logging.handlers` — Logging handlers](logging.handlers) + [`getpass` — Portable password input](getpass) + [`curses` — Terminal handling for character-cell displays](curses) + [`curses.textpad` — Text input widget for curses programs](curses#module-curses.textpad) + [`curses.ascii` — Utilities for ASCII characters](curses.ascii) + [`curses.panel` — A panel stack extension for curses](curses.panel) + [`platform` — Access to underlying platform’s identifying data](platform) + [`errno` — Standard errno system symbols](errno) + [`ctypes` — A foreign function library for Python](ctypes) * [Concurrent Execution](concurrency) + [`threading` — Thread-based parallelism](threading) + [`multiprocessing` — Process-based parallelism](multiprocessing) + [`multiprocessing.shared_memory` — Provides shared memory for direct access across processes](multiprocessing.shared_memory) + [The `concurrent` package](concurrent) + [`concurrent.futures` — Launching parallel tasks](concurrent.futures) + [`subprocess` — Subprocess management](subprocess) + [`sched` — Event scheduler](sched) + [`queue` — A synchronized queue class](queue) + [`contextvars` — Context Variables](contextvars) + [`_thread` — Low-level threading API](_thread) * [Networking and Interprocess Communication](ipc) + [`asyncio` — Asynchronous I/O](asyncio) + [`socket` — Low-level networking interface](socket) + [`ssl` — TLS/SSL wrapper for socket objects](ssl) + [`select` — Waiting for I/O completion](select) + [`selectors` — High-level I/O multiplexing](selectors) + [`signal` — Set handlers for asynchronous events](signal) + [`mmap` — Memory-mapped file support](mmap) * [Internet Data Handling](netdata) + [`email` — An email and MIME handling package](email) + [`json` — JSON encoder and decoder](json) + [`mailbox` — Manipulate mailboxes in various formats](mailbox) + [`mimetypes` — Map filenames to MIME types](mimetypes) + [`base64` — Base16, Base32, Base64, Base85 Data Encodings](base64) + [`binhex` — Encode and decode binhex4 files](binhex) + [`binascii` — Convert between binary and ASCII](binascii) + [`quopri` — Encode and decode MIME quoted-printable data](quopri) * [Structured Markup Processing Tools](markup) + [`html` — HyperText Markup Language support](html) + [`html.parser` — Simple HTML and XHTML parser](html.parser) + [`html.entities` — Definitions of HTML general entities](html.entities) + [XML Processing Modules](xml) + [`xml.etree.ElementTree` — The ElementTree XML API](xml.etree.elementtree) + [`xml.dom` — The Document Object Model API](xml.dom) + [`xml.dom.minidom` — Minimal DOM implementation](xml.dom.minidom) + [`xml.dom.pulldom` — Support for building partial DOM trees](xml.dom.pulldom) + [`xml.sax` — Support for SAX2 parsers](xml.sax) + [`xml.sax.handler` — Base classes for SAX handlers](xml.sax.handler) + [`xml.sax.saxutils` — SAX Utilities](xml.sax.utils) + [`xml.sax.xmlreader` — Interface for XML parsers](xml.sax.reader) + [`xml.parsers.expat` — Fast XML parsing using Expat](pyexpat) * [Internet Protocols and Support](internet) + [`webbrowser` — Convenient Web-browser controller](webbrowser) + [`wsgiref` — WSGI Utilities and Reference Implementation](wsgiref) + [`urllib` — URL handling modules](urllib) + [`urllib.request` — Extensible library for opening URLs](urllib.request) + [`urllib.response` — Response classes used by urllib](urllib.request#module-urllib.response) + [`urllib.parse` — Parse URLs into components](urllib.parse) + [`urllib.error` — Exception classes raised by urllib.request](urllib.error) + [`urllib.robotparser` — Parser for robots.txt](urllib.robotparser) + [`http` — HTTP modules](http) + [`http.client` — HTTP protocol client](http.client) + [`ftplib` — FTP protocol client](ftplib) + [`poplib` — POP3 protocol client](poplib) + [`imaplib` — IMAP4 protocol client](imaplib) + [`smtplib` — SMTP protocol client](smtplib) + [`uuid` — UUID objects according to **RFC 4122**](uuid) + [`socketserver` — A framework for network servers](socketserver) + [`http.server` — HTTP servers](http.server) + [`http.cookies` — HTTP state management](http.cookies) + [`http.cookiejar` — Cookie handling for HTTP clients](http.cookiejar) + [`xmlrpc` — XMLRPC server and client modules](xmlrpc) + [`xmlrpc.client` — XML-RPC client access](xmlrpc.client) + [`xmlrpc.server` — Basic XML-RPC servers](xmlrpc.server) + [`ipaddress` — IPv4/IPv6 manipulation library](ipaddress) * [Multimedia Services](mm) + [`wave` — Read and write WAV files](wave) + [`colorsys` — Conversions between color systems](colorsys) * [Internationalization](i18n) + [`gettext` — Multilingual internationalization services](gettext) + [`locale` — Internationalization services](locale) * [Program Frameworks](frameworks) + [`turtle` — Turtle graphics](turtle) + [`cmd` — Support for line-oriented command interpreters](cmd) + [`shlex` — Simple lexical analysis](shlex) * [Graphical User Interfaces with Tk](tk) + [`tkinter` — Python interface to Tcl/Tk](tkinter) + [`tkinter.colorchooser` — Color choosing dialog](tkinter.colorchooser) + [`tkinter.font` — Tkinter font wrapper](tkinter.font) + [Tkinter Dialogs](dialog) + [`tkinter.messagebox` — Tkinter message prompts](tkinter.messagebox) + [`tkinter.scrolledtext` — Scrolled Text Widget](tkinter.scrolledtext) + [`tkinter.dnd` — Drag and drop support](tkinter.dnd) + [`tkinter.ttk` — Tk themed widgets](tkinter.ttk) + [`tkinter.tix` — Extension widgets for Tk](tkinter.tix) + [IDLE](idle) * [Development Tools](development) + [`typing` — Support for type hints](typing) + [`pydoc` — Documentation generator and online help system](pydoc) + [Python Development Mode](devmode) + [Effects of the Python Development Mode](devmode#effects-of-the-python-development-mode) + [ResourceWarning Example](devmode#resourcewarning-example) + [Bad file descriptor error example](devmode#bad-file-descriptor-error-example) + [`doctest` — Test interactive Python examples](doctest) + [`unittest` — Unit testing framework](unittest) + [`unittest.mock` — mock object library](unittest.mock) + [`unittest.mock` — getting started](https://docs.python.org/3.9/library/unittest.mock-examples.html) + [2to3 - Automated Python 2 to 3 code translation](https://docs.python.org/3.9/library/2to3.html) + [`test` — Regression tests package for Python](test) + [`test.support` — Utilities for the Python test suite](test#module-test.support) + [`test.support.socket_helper` — Utilities for socket tests](test#module-test.support.socket_helper) + [`test.support.script_helper` — Utilities for the Python execution tests](test#module-test.support.script_helper) + [`test.support.bytecode_helper` — Support tools for testing correct bytecode generation](test#module-test.support.bytecode_helper) * [Debugging and Profiling](debug) + [Audit events table](audit_events) + [`bdb` — Debugger framework](bdb) + [`faulthandler` — Dump the Python traceback](faulthandler) + [`pdb` — The Python Debugger](pdb) + [The Python Profilers](profile) + [`timeit` — Measure execution time of small code snippets](timeit) + [`trace` — Trace or track Python statement execution](trace) + [`tracemalloc` — Trace memory allocations](tracemalloc) * [Software Packaging and Distribution](distribution) + [`distutils` — Building and installing Python modules](distutils) + [`ensurepip` — Bootstrapping the `pip` installer](ensurepip) + [`venv` — Creation of virtual environments](venv) + [`zipapp` — Manage executable Python zip archives](zipapp) * [Python Runtime Services](python) + [`sys` — System-specific parameters and functions](sys) + [`sysconfig` — Provide access to Python’s configuration information](sysconfig) + [`builtins` — Built-in objects](builtins) + [`__main__` — Top-level script environment](__main__) + [`warnings` — Warning control](warnings) + [`dataclasses` — Data Classes](dataclasses) + [`contextlib` — Utilities for `with`-statement contexts](contextlib) + [`abc` — Abstract Base Classes](abc) + [`atexit` — Exit handlers](atexit) + [`traceback` — Print or retrieve a stack traceback](traceback) + [`__future__` — Future statement definitions](__future__) + [`gc` — Garbage Collector interface](gc) + [`inspect` — Inspect live objects](inspect) + [`site` — Site-specific configuration hook](site) * [Custom Python Interpreters](custominterp) + [`code` — Interpreter base classes](code) + [`codeop` — Compile Python code](codeop) * [Importing Modules](modules) + [`zipimport` — Import modules from Zip archives](zipimport) + [`pkgutil` — Package extension utility](pkgutil) + [`modulefinder` — Find modules used by a script](modulefinder) + [`runpy` — Locating and executing Python modules](runpy) + [`importlib` — The implementation of `import`](importlib) + [Using `importlib.metadata`](importlib.metadata) * [Python Language Services](language) + [`parser` — Access Python parse trees](parser) + [`ast` — Abstract Syntax Trees](ast) + [`symtable` — Access to the compiler’s symbol tables](symtable) + [`symbol` — Constants used with Python parse trees](symbol) + [`token` — Constants used with Python parse trees](token) + [`keyword` — Testing for Python keywords](keyword) + [`tokenize` — Tokenizer for Python source](tokenize) + [`tabnanny` — Detection of ambiguous indentation](tabnanny) + [`pyclbr` — Python module browser support](pyclbr) + [`py_compile` — Compile Python source files](py_compile) + [`compileall` — Byte-compile Python libraries](compileall) + [`dis` — Disassembler for Python bytecode](dis) + [`pickletools` — Tools for pickle developers](pickletools) * [Miscellaneous Services](misc) + [`formatter` — Generic output formatting](https://docs.python.org/3.9/library/formatter.html) * [MS Windows Specific Services](windows) + [`msvcrt` — Useful routines from the MS VC++ runtime](msvcrt) + [`winreg` — Windows registry access](winreg) + [`winsound` — Sound-playing interface for Windows](winsound) * [Unix Specific Services](unix) + [`posix` — The most common POSIX system calls](posix) + [`pwd` — The password database](pwd) + [`grp` — The group database](grp) + [`termios` — POSIX style tty control](termios) + [`tty` — Terminal control functions](tty) + [`pty` — Pseudo-terminal utilities](pty) + [`fcntl` — The `fcntl` and `ioctl` system calls](fcntl) + [`resource` — Resource usage information](resource) + [`syslog` — Unix syslog library routines](syslog) * [Superseded Modules](superseded) + [`aifc` — Read and write AIFF and AIFC files](aifc) + [`asynchat` — Asynchronous socket command/response handler](asynchat) + [`asyncore` — Asynchronous socket handler](asyncore) + [`audioop` — Manipulate raw audio data](audioop) + [`cgi` — Common Gateway Interface support](cgi) + [`cgitb` — Traceback manager for CGI scripts](cgitb) + [`chunk` — Read IFF chunked data](chunk) + [`crypt` — Function to check Unix passwords](crypt) + [`imghdr` — Determine the type of an image](imghdr) + [`imp` — Access the import internals](imp) + [`mailcap` — Mailcap file handling](mailcap) + [`msilib` — Read and write Microsoft Installer files](msilib) + [`nis` — Interface to Sun’s NIS (Yellow Pages)](nis) + [`nntplib` — NNTP protocol client](nntplib) + [`optparse` — Parser for command line options](optparse) + [`ossaudiodev` — Access to OSS-compatible audio devices](ossaudiodev) + [`pipes` — Interface to shell pipelines](pipes) + [`smtpd` — SMTP Server](smtpd) + [`sndhdr` — Determine type of sound file](sndhdr) + [`spwd` — The shadow password database](spwd) + [`sunau` — Read and write Sun AU files](https://docs.python.org/3.9/library/sunau.html) + [`telnetlib` — Telnet client](telnetlib) + [`uu` — Encode and decode uuencode files](uu) + [`xdrlib` — Encode and decode XDR data](xdrlib) * [Security Considerations](security_warnings)
programming_docs
python unicodedata — Unicode Database unicodedata — Unicode Database ============================== This module provides access to the Unicode Character Database (UCD) which defines character properties for all Unicode characters. The data contained in this database is compiled from the [UCD version 13.0.0](https://www.unicode.org/Public/13.0.0/ucd). The module uses the same names and symbols as defined by Unicode Standard Annex #44, [“Unicode Character Database”](https://www.unicode.org/reports/tr44/). It defines the following functions: `unicodedata.lookup(name)` Look up character by name. If a character with the given name is found, return the corresponding character. If not found, [`KeyError`](exceptions#KeyError "KeyError") is raised. Changed in version 3.3: Support for name aliases [1](#id3) and named sequences [2](#id4) has been added. `unicodedata.name(chr[, default])` Returns the name assigned to the character *chr* as a string. If no name is defined, *default* is returned, or, if not given, [`ValueError`](exceptions#ValueError "ValueError") is raised. `unicodedata.decimal(chr[, default])` Returns the decimal value assigned to the character *chr* as integer. If no such value is defined, *default* is returned, or, if not given, [`ValueError`](exceptions#ValueError "ValueError") is raised. `unicodedata.digit(chr[, default])` Returns the digit value assigned to the character *chr* as integer. If no such value is defined, *default* is returned, or, if not given, [`ValueError`](exceptions#ValueError "ValueError") is raised. `unicodedata.numeric(chr[, default])` Returns the numeric value assigned to the character *chr* as float. If no such value is defined, *default* is returned, or, if not given, [`ValueError`](exceptions#ValueError "ValueError") is raised. `unicodedata.category(chr)` Returns the general category assigned to the character *chr* as string. `unicodedata.bidirectional(chr)` Returns the bidirectional class assigned to the character *chr* as string. If no such value is defined, an empty string is returned. `unicodedata.combining(chr)` Returns the canonical combining class assigned to the character *chr* as integer. Returns `0` if no combining class is defined. `unicodedata.east_asian_width(chr)` Returns the east asian width assigned to the character *chr* as string. `unicodedata.mirrored(chr)` Returns the mirrored property assigned to the character *chr* as integer. Returns `1` if the character has been identified as a “mirrored” character in bidirectional text, `0` otherwise. `unicodedata.decomposition(chr)` Returns the character decomposition mapping assigned to the character *chr* as string. An empty string is returned in case no such mapping is defined. `unicodedata.normalize(form, unistr)` Return the normal form *form* for the Unicode string *unistr*. Valid values for *form* are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’. The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA). For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again. In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312). The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition. Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal. `unicodedata.is_normalized(form, unistr)` Return whether the Unicode string *unistr* is in the normal form *form*. Valid values for *form* are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’. New in version 3.8. In addition, the module exposes the following constant: `unicodedata.unidata_version` The version of the Unicode database used in this module. `unicodedata.ucd_3_2_0` This is an object that has the same methods as the entire module, but uses the Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA). Examples: ``` >>> import unicodedata >>> unicodedata.lookup('LEFT CURLY BRACKET') '{' >>> unicodedata.name('/') 'SOLIDUS' >>> unicodedata.decimal('9') 9 >>> unicodedata.decimal('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: not a decimal >>> unicodedata.category('A') # 'L'etter, 'u'ppercase 'Lu' >>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber 'AN' ``` #### Footnotes `1` <https://www.unicode.org/Public/13.0.0/ucd/NameAliases.txt> `2` <https://www.unicode.org/Public/13.0.0/ucd/NamedSequences.txt> python parser — Access Python parse trees parser — Access Python parse trees ================================== The [`parser`](#module-parser "parser: Access parse trees for Python source code.") module provides an interface to Python’s internal parser and byte-code compiler. The primary purpose for this interface is to allow Python code to edit the parse tree of a Python expression and create executable code from this. This is better than trying to parse and modify an arbitrary Python code fragment as a string because parsing is performed in a manner identical to the code forming the application. It is also faster. Warning The parser module is deprecated and will be removed in future versions of Python. For the majority of use cases you can leverage the Abstract Syntax Tree (AST) generation and compilation stage, using the [`ast`](ast#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module. There are a few things to note about this module which are important to making use of the data structures created. This is not a tutorial on editing the parse trees for Python code, but some examples of using the [`parser`](#module-parser "parser: Access parse trees for Python source code.") module are presented. Most importantly, a good understanding of the Python grammar processed by the internal parser is required. For full information on the language syntax, refer to [The Python Language Reference](../reference/index#reference-index). The parser itself is created from a grammar specification defined in the file `Grammar/Grammar` in the standard Python distribution. The parse trees stored in the ST objects created by this module are the actual output from the internal parser when created by the [`expr()`](#parser.expr "parser.expr") or [`suite()`](#parser.suite "parser.suite") functions, described below. The ST objects created by [`sequence2st()`](#parser.sequence2st "parser.sequence2st") faithfully simulate those structures. Be aware that the values of the sequences which are considered “correct” will vary from one version of Python to another as the formal grammar for the language is revised. However, transporting code from one Python version to another as source text will always allow correct parse trees to be created in the target version, with the only restriction being that migrating to an older version of the interpreter will not support more recent language constructs. The parse trees are not typically compatible from one version to another, though source code has usually been forward-compatible within a major release series. Each element of the sequences returned by [`st2list()`](#parser.st2list "parser.st2list") or [`st2tuple()`](#parser.st2tuple "parser.st2tuple") has a simple form. Sequences representing non-terminal elements in the grammar always have a length greater than one. The first element is an integer which identifies a production in the grammar. These integers are given symbolic names in the C header file `Include/graminit.h` and the Python module [`symbol`](symbol#module-symbol "symbol: Constants representing internal nodes of the parse tree."). Each additional element of the sequence represents a component of the production as recognized in the input string: these are always sequences which have the same form as the parent. An important aspect of this structure which should be noted is that keywords used to identify the parent node type, such as the keyword [`if`](../reference/compound_stmts#if) in an `if_stmt`, are included in the node tree without any special treatment. For example, the `if` keyword is represented by the tuple `(1, 'if')`, where `1` is the numeric value associated with all `NAME` tokens, including variable and function names defined by the user. In an alternate form returned when line number information is requested, the same token might be represented as `(1, 'if', 12)`, where the `12` represents the line number at which the terminal symbol was found. Terminal elements are represented in much the same way, but without any child elements and the addition of the source text which was identified. The example of the [`if`](../reference/compound_stmts#if) keyword above is representative. The various types of terminal symbols are defined in the C header file `Include/token.h` and the Python module [`token`](token#module-token "token: Constants representing terminal nodes of the parse tree."). The ST objects are not required to support the functionality of this module, but are provided for three purposes: to allow an application to amortize the cost of processing complex parse trees, to provide a parse tree representation which conserves memory space when compared to the Python list or tuple representation, and to ease the creation of additional modules in C which manipulate parse trees. A simple “wrapper” class may be created in Python to hide the use of ST objects. The [`parser`](#module-parser "parser: Access parse trees for Python source code.") module defines functions for a few distinct purposes. The most important purposes are to create ST objects and to convert ST objects to other representations such as parse trees and compiled code objects, but there are also functions which serve to query the type of parse tree represented by an ST object. See also `Module` [`symbol`](symbol#module-symbol "symbol: Constants representing internal nodes of the parse tree.") Useful constants representing internal nodes of the parse tree. `Module` [`token`](token#module-token "token: Constants representing terminal nodes of the parse tree.") Useful constants representing leaf nodes of the parse tree and functions for testing node values. Creating ST Objects ------------------- ST objects may be created from source code or from a parse tree. When creating an ST object from source, different functions are used to create the `'eval'` and `'exec'` forms. `parser.expr(source)` The [`expr()`](#parser.expr "parser.expr") function parses the parameter *source* as if it were an input to `compile(source, 'file.py', 'eval')`. If the parse succeeds, an ST object is created to hold the internal parse tree representation, otherwise an appropriate exception is raised. `parser.suite(source)` The [`suite()`](#parser.suite "parser.suite") function parses the parameter *source* as if it were an input to `compile(source, 'file.py', 'exec')`. If the parse succeeds, an ST object is created to hold the internal parse tree representation, otherwise an appropriate exception is raised. `parser.sequence2st(sequence)` This function accepts a parse tree represented as a sequence and builds an internal representation if possible. If it can validate that the tree conforms to the Python grammar and all nodes are valid node types in the host version of Python, an ST object is created from the internal representation and returned to the called. If there is a problem creating the internal representation, or if the tree cannot be validated, a [`ParserError`](#parser.ParserError "parser.ParserError") exception is raised. An ST object created this way should not be assumed to compile correctly; normal exceptions raised by compilation may still be initiated when the ST object is passed to [`compilest()`](#parser.compilest "parser.compilest"). This may indicate problems not related to syntax (such as a [`MemoryError`](exceptions#MemoryError "MemoryError") exception), but may also be due to constructs such as the result of parsing `del f(0)`, which escapes the Python parser but is checked by the bytecode compiler. Sequences representing terminal tokens may be represented as either two-element lists of the form `(1, 'name')` or as three-element lists of the form `(1, 'name', 56)`. If the third element is present, it is assumed to be a valid line number. The line number may be specified for any subset of the terminal symbols in the input tree. `parser.tuple2st(sequence)` This is the same function as [`sequence2st()`](#parser.sequence2st "parser.sequence2st"). This entry point is maintained for backward compatibility. Converting ST Objects --------------------- ST objects, regardless of the input used to create them, may be converted to parse trees represented as list- or tuple- trees, or may be compiled into executable code objects. Parse trees may be extracted with or without line numbering information. `parser.st2list(st, line_info=False, col_info=False)` This function accepts an ST object from the caller in *st* and returns a Python list representing the equivalent parse tree. The resulting list representation can be used for inspection or the creation of a new parse tree in list form. This function does not fail so long as memory is available to build the list representation. If the parse tree will only be used for inspection, [`st2tuple()`](#parser.st2tuple "parser.st2tuple") should be used instead to reduce memory consumption and fragmentation. When the list representation is required, this function is significantly faster than retrieving a tuple representation and converting that to nested lists. If *line\_info* is true, line number information will be included for all terminal tokens as a third element of the list representing the token. Note that the line number provided specifies the line on which the token *ends*. This information is omitted if the flag is false or omitted. `parser.st2tuple(st, line_info=False, col_info=False)` This function accepts an ST object from the caller in *st* and returns a Python tuple representing the equivalent parse tree. Other than returning a tuple instead of a list, this function is identical to [`st2list()`](#parser.st2list "parser.st2list"). If *line\_info* is true, line number information will be included for all terminal tokens as a third element of the list representing the token. This information is omitted if the flag is false or omitted. `parser.compilest(st, filename='<syntax-tree>')` The Python byte compiler can be invoked on an ST object to produce code objects which can be used as part of a call to the built-in [`exec()`](functions#exec "exec") or [`eval()`](functions#eval "eval") functions. This function provides the interface to the compiler, passing the internal parse tree from *st* to the parser, using the source file name specified by the *filename* parameter. The default value supplied for *filename* indicates that the source was an ST object. Compiling an ST object may result in exceptions related to compilation; an example would be a [`SyntaxError`](exceptions#SyntaxError "SyntaxError") caused by the parse tree for `del f(0)`: this statement is considered legal within the formal grammar for Python but is not a legal language construct. The [`SyntaxError`](exceptions#SyntaxError "SyntaxError") raised for this condition is actually generated by the Python byte-compiler normally, which is why it can be raised at this point by the [`parser`](#module-parser "parser: Access parse trees for Python source code.") module. Most causes of compilation failure can be diagnosed programmatically by inspection of the parse tree. Queries on ST Objects --------------------- Two functions are provided which allow an application to determine if an ST was created as an expression or a suite. Neither of these functions can be used to determine if an ST was created from source code via [`expr()`](#parser.expr "parser.expr") or [`suite()`](#parser.suite "parser.suite") or from a parse tree via [`sequence2st()`](#parser.sequence2st "parser.sequence2st"). `parser.isexpr(st)` When *st* represents an `'eval'` form, this function returns `True`, otherwise it returns `False`. This is useful, since code objects normally cannot be queried for this information using existing built-in functions. Note that the code objects created by [`compilest()`](#parser.compilest "parser.compilest") cannot be queried like this either, and are identical to those created by the built-in [`compile()`](functions#compile "compile") function. `parser.issuite(st)` This function mirrors [`isexpr()`](#parser.isexpr "parser.isexpr") in that it reports whether an ST object represents an `'exec'` form, commonly known as a “suite.” It is not safe to assume that this function is equivalent to `not isexpr(st)`, as additional syntactic fragments may be supported in the future. Exceptions and Error Handling ----------------------------- The parser module defines a single exception, but may also pass other built-in exceptions from other portions of the Python runtime environment. See each function for information about the exceptions it can raise. `exception parser.ParserError` Exception raised when a failure occurs within the parser module. This is generally produced for validation failures rather than the built-in [`SyntaxError`](exceptions#SyntaxError "SyntaxError") raised during normal parsing. The exception argument is either a string describing the reason of the failure or a tuple containing a sequence causing the failure from a parse tree passed to [`sequence2st()`](#parser.sequence2st "parser.sequence2st") and an explanatory string. Calls to [`sequence2st()`](#parser.sequence2st "parser.sequence2st") need to be able to handle either type of exception, while calls to other functions in the module will only need to be aware of the simple string values. Note that the functions [`compilest()`](#parser.compilest "parser.compilest"), [`expr()`](#parser.expr "parser.expr"), and [`suite()`](#parser.suite "parser.suite") may raise exceptions which are normally raised by the parsing and compilation process. These include the built in exceptions [`MemoryError`](exceptions#MemoryError "MemoryError"), [`OverflowError`](exceptions#OverflowError "OverflowError"), [`SyntaxError`](exceptions#SyntaxError "SyntaxError"), and [`SystemError`](exceptions#SystemError "SystemError"). In these cases, these exceptions carry all the meaning normally associated with them. Refer to the descriptions of each function for detailed information. ST Objects ---------- Ordered and equality comparisons are supported between ST objects. Pickling of ST objects (using the [`pickle`](pickle#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module) is also supported. `parser.STType` The type of the objects returned by [`expr()`](#parser.expr "parser.expr"), [`suite()`](#parser.suite "parser.suite") and [`sequence2st()`](#parser.sequence2st "parser.sequence2st"). ST objects have the following methods: `ST.compile(filename='<syntax-tree>')` Same as `compilest(st, filename)`. `ST.isexpr()` Same as `isexpr(st)`. `ST.issuite()` Same as `issuite(st)`. `ST.tolist(line_info=False, col_info=False)` Same as `st2list(st, line_info, col_info)`. `ST.totuple(line_info=False, col_info=False)` Same as `st2tuple(st, line_info, col_info)`. Example: Emulation of compile() ------------------------------- While many useful operations may take place between parsing and bytecode generation, the simplest operation is to do nothing. For this purpose, using the [`parser`](#module-parser "parser: Access parse trees for Python source code.") module to produce an intermediate data structure is equivalent to the code ``` >>> code = compile('a + 5', 'file.py', 'eval') >>> a = 5 >>> eval(code) 10 ``` The equivalent operation using the [`parser`](#module-parser "parser: Access parse trees for Python source code.") module is somewhat longer, and allows the intermediate internal parse tree to be retained as an ST object: ``` >>> import parser >>> st = parser.expr('a + 5') >>> code = st.compile('file.py') >>> a = 5 >>> eval(code) 10 ``` An application which needs both ST and code objects can package this code into readily available functions: ``` import parser def load_suite(source_string): st = parser.suite(source_string) return st, st.compile() def load_expression(source_string): st = parser.expr(source_string) return st, st.compile() ```
programming_docs
python Internet Protocols and Support Internet Protocols and Support ============================== The modules described in this chapter implement Internet protocols and support for related technology. They are all implemented in Python. Most of these modules require the presence of the system-dependent module [`socket`](socket#module-socket "socket: Low-level networking interface."), which is currently supported on most popular platforms. Here is an overview: * [`webbrowser` — Convenient Web-browser controller](webbrowser) + [Browser Controller Objects](webbrowser#browser-controller-objects) * [`wsgiref` — WSGI Utilities and Reference Implementation](wsgiref) + [`wsgiref.util` – WSGI environment utilities](wsgiref#module-wsgiref.util) + [`wsgiref.headers` – WSGI response header tools](wsgiref#module-wsgiref.headers) + [`wsgiref.simple_server` – a simple WSGI HTTP server](wsgiref#module-wsgiref.simple_server) + [`wsgiref.validate` — WSGI conformance checker](wsgiref#module-wsgiref.validate) + [`wsgiref.handlers` – server/gateway base classes](wsgiref#module-wsgiref.handlers) + [Examples](wsgiref#examples) * [`urllib` — URL handling modules](urllib) * [`urllib.request` — Extensible library for opening URLs](urllib.request) + [Request Objects](urllib.request#request-objects) + [OpenerDirector Objects](urllib.request#openerdirector-objects) + [BaseHandler Objects](urllib.request#basehandler-objects) + [HTTPRedirectHandler Objects](urllib.request#httpredirecthandler-objects) + [HTTPCookieProcessor Objects](urllib.request#httpcookieprocessor-objects) + [ProxyHandler Objects](urllib.request#proxyhandler-objects) + [HTTPPasswordMgr Objects](urllib.request#httppasswordmgr-objects) + [HTTPPasswordMgrWithPriorAuth Objects](urllib.request#httppasswordmgrwithpriorauth-objects) + [AbstractBasicAuthHandler Objects](urllib.request#abstractbasicauthhandler-objects) + [HTTPBasicAuthHandler Objects](urllib.request#httpbasicauthhandler-objects) + [ProxyBasicAuthHandler Objects](urllib.request#proxybasicauthhandler-objects) + [AbstractDigestAuthHandler Objects](urllib.request#abstractdigestauthhandler-objects) + [HTTPDigestAuthHandler Objects](urllib.request#httpdigestauthhandler-objects) + [ProxyDigestAuthHandler Objects](urllib.request#proxydigestauthhandler-objects) + [HTTPHandler Objects](urllib.request#httphandler-objects) + [HTTPSHandler Objects](urllib.request#httpshandler-objects) + [FileHandler Objects](urllib.request#filehandler-objects) + [DataHandler Objects](urllib.request#datahandler-objects) + [FTPHandler Objects](urllib.request#ftphandler-objects) + [CacheFTPHandler Objects](urllib.request#cacheftphandler-objects) + [UnknownHandler Objects](urllib.request#unknownhandler-objects) + [HTTPErrorProcessor Objects](urllib.request#httperrorprocessor-objects) + [Examples](urllib.request#examples) + [Legacy interface](urllib.request#legacy-interface) + [`urllib.request` Restrictions](urllib.request#urllib-request-restrictions) * [`urllib.response` — Response classes used by urllib](urllib.request#module-urllib.response) * [`urllib.parse` — Parse URLs into components](urllib.parse) + [URL Parsing](urllib.parse#url-parsing) + [Parsing ASCII Encoded Bytes](urllib.parse#parsing-ascii-encoded-bytes) + [Structured Parse Results](urllib.parse#structured-parse-results) + [URL Quoting](urllib.parse#url-quoting) * [`urllib.error` — Exception classes raised by urllib.request](urllib.error) * [`urllib.robotparser` — Parser for robots.txt](urllib.robotparser) * [`http` — HTTP modules](http) + [HTTP status codes](http#http-status-codes) * [`http.client` — HTTP protocol client](http.client) + [HTTPConnection Objects](http.client#httpconnection-objects) + [HTTPResponse Objects](http.client#httpresponse-objects) + [Examples](http.client#examples) + [HTTPMessage Objects](http.client#httpmessage-objects) * [`ftplib` — FTP protocol client](ftplib) + [FTP Objects](ftplib#ftp-objects) + [FTP\_TLS Objects](ftplib#ftp-tls-objects) * [`poplib` — POP3 protocol client](poplib) + [POP3 Objects](poplib#pop3-objects) + [POP3 Example](poplib#pop3-example) * [`imaplib` — IMAP4 protocol client](imaplib) + [IMAP4 Objects](imaplib#imap4-objects) + [IMAP4 Example](imaplib#imap4-example) * [`smtplib` — SMTP protocol client](smtplib) + [SMTP Objects](smtplib#smtp-objects) + [SMTP Example](smtplib#smtp-example) * [`uuid` — UUID objects according to **RFC 4122**](uuid) + [Example](uuid#example) * [`socketserver` — A framework for network servers](socketserver) + [Server Creation Notes](socketserver#server-creation-notes) + [Server Objects](socketserver#server-objects) + [Request Handler Objects](socketserver#request-handler-objects) + [Examples](socketserver#examples) - [`socketserver.TCPServer` Example](socketserver#socketserver-tcpserver-example) - [`socketserver.UDPServer` Example](socketserver#socketserver-udpserver-example) - [Asynchronous Mixins](socketserver#asynchronous-mixins) * [`http.server` — HTTP servers](http.server) + [Security Considerations](http.server#security-considerations) * [`http.cookies` — HTTP state management](http.cookies) + [Cookie Objects](http.cookies#cookie-objects) + [Morsel Objects](http.cookies#morsel-objects) + [Example](http.cookies#example) * [`http.cookiejar` — Cookie handling for HTTP clients](http.cookiejar) + [CookieJar and FileCookieJar Objects](http.cookiejar#cookiejar-and-filecookiejar-objects) + [FileCookieJar subclasses and co-operation with web browsers](http.cookiejar#filecookiejar-subclasses-and-co-operation-with-web-browsers) + [CookiePolicy Objects](http.cookiejar#cookiepolicy-objects) + [DefaultCookiePolicy Objects](http.cookiejar#defaultcookiepolicy-objects) + [Cookie Objects](http.cookiejar#cookie-objects) + [Examples](http.cookiejar#examples) * [`xmlrpc` — XMLRPC server and client modules](xmlrpc) * [`xmlrpc.client` — XML-RPC client access](xmlrpc.client) + [ServerProxy Objects](xmlrpc.client#serverproxy-objects) + [DateTime Objects](xmlrpc.client#datetime-objects) + [Binary Objects](xmlrpc.client#binary-objects) + [Fault Objects](xmlrpc.client#fault-objects) + [ProtocolError Objects](xmlrpc.client#protocolerror-objects) + [MultiCall Objects](xmlrpc.client#multicall-objects) + [Convenience Functions](xmlrpc.client#convenience-functions) + [Example of Client Usage](xmlrpc.client#example-of-client-usage) + [Example of Client and Server Usage](xmlrpc.client#example-of-client-and-server-usage) * [`xmlrpc.server` — Basic XML-RPC servers](xmlrpc.server) + [SimpleXMLRPCServer Objects](xmlrpc.server#simplexmlrpcserver-objects) - [SimpleXMLRPCServer Example](xmlrpc.server#simplexmlrpcserver-example) + [CGIXMLRPCRequestHandler](xmlrpc.server#cgixmlrpcrequesthandler) + [Documenting XMLRPC server](xmlrpc.server#documenting-xmlrpc-server) + [DocXMLRPCServer Objects](xmlrpc.server#docxmlrpcserver-objects) + [DocCGIXMLRPCRequestHandler](xmlrpc.server#doccgixmlrpcrequesthandler) * [`ipaddress` — IPv4/IPv6 manipulation library](ipaddress) + [Convenience factory functions](ipaddress#convenience-factory-functions) + [IP Addresses](ipaddress#ip-addresses) - [Address objects](ipaddress#address-objects) - [Conversion to Strings and Integers](ipaddress#conversion-to-strings-and-integers) - [Operators](ipaddress#operators) * [Comparison operators](ipaddress#comparison-operators) * [Arithmetic operators](ipaddress#arithmetic-operators) + [IP Network definitions](ipaddress#ip-network-definitions) - [Prefix, net mask and host mask](ipaddress#prefix-net-mask-and-host-mask) - [Network objects](ipaddress#network-objects) - [Operators](ipaddress#id1) * [Logical operators](ipaddress#logical-operators) * [Iteration](ipaddress#iteration) * [Networks as containers of addresses](ipaddress#networks-as-containers-of-addresses) + [Interface objects](ipaddress#interface-objects) - [Operators](ipaddress#id2) * [Logical operators](ipaddress#id3) + [Other Module Level Functions](ipaddress#other-module-level-functions) + [Custom Exceptions](ipaddress#custom-exceptions) python Built-in Functions Built-in Functions ================== The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. | | | Built-in Functions | | | | --- | --- | --- | --- | --- | | [`abs()`](#abs "abs") | [`delattr()`](#delattr "delattr") | [`hash()`](#hash "hash") | [`memoryview()`](#func-memoryview) | [`set()`](#func-set) | | [`all()`](#all "all") | [`dict()`](#func-dict) | [`help()`](#help "help") | [`min()`](#min "min") | [`setattr()`](#setattr "setattr") | | [`any()`](#any "any") | [`dir()`](#dir "dir") | [`hex()`](#hex "hex") | [`next()`](#next "next") | [`slice()`](#slice "slice") | | [`ascii()`](#ascii "ascii") | [`divmod()`](#divmod "divmod") | [`id()`](#id "id") | [`object()`](#object "object") | [`sorted()`](#sorted "sorted") | | [`bin()`](#bin "bin") | [`enumerate()`](#enumerate "enumerate") | [`input()`](#input "input") | [`oct()`](#oct "oct") | [`staticmethod()`](#staticmethod "staticmethod") | | [`bool()`](#bool "bool") | [`eval()`](#eval "eval") | [`int()`](#int "int") | [`open()`](#open "open") | [`str()`](#func-str) | | [`breakpoint()`](#breakpoint "breakpoint") | [`exec()`](#exec "exec") | [`isinstance()`](#isinstance "isinstance") | [`ord()`](#ord "ord") | [`sum()`](#sum "sum") | | [`bytearray()`](#func-bytearray) | [`filter()`](#filter "filter") | [`issubclass()`](#issubclass "issubclass") | [`pow()`](#pow "pow") | [`super()`](#super "super") | | [`bytes()`](#func-bytes) | [`float()`](#float "float") | [`iter()`](#iter "iter") | [`print()`](#print "print") | [`tuple()`](#func-tuple) | | [`callable()`](#callable "callable") | [`format()`](#format "format") | [`len()`](#len "len") | [`property()`](#property "property") | [`type()`](#type "type") | | [`chr()`](#chr "chr") | [`frozenset()`](#func-frozenset) | [`list()`](#func-list) | [`range()`](#func-range) | [`vars()`](#vars "vars") | | [`classmethod()`](#classmethod "classmethod") | [`getattr()`](#getattr "getattr") | [`locals()`](#locals "locals") | [`repr()`](#repr "repr") | [`zip()`](#zip "zip") | | [`compile()`](#compile "compile") | [`globals()`](#globals "globals") | [`map()`](#map "map") | [`reversed()`](#reversed "reversed") | [`__import__()`](#__import__ "__import__") | | [`complex()`](#complex "complex") | [`hasattr()`](#hasattr "hasattr") | [`max()`](#max "max") | [`round()`](#round "round") | | `abs(x)` Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing [`__abs__()`](../reference/datamodel#object.__abs__ "object.__abs__"). If the argument is a complex number, its magnitude is returned. `all(iterable)` Return `True` if all elements of the *iterable* are true (or if the iterable is empty). Equivalent to: ``` def all(iterable): for element in iterable: if not element: return False return True ``` `any(iterable)` Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to: ``` def any(iterable): for element in iterable: if element: return True return False ``` `ascii(object)` As [`repr()`](#repr "repr"), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by [`repr()`](#repr "repr") using `\x`, `\u` or `\U` escapes. This generates a string similar to that returned by [`repr()`](#repr "repr") in Python 2. `bin(x)` Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If *x* is not a Python [`int`](#int "int") object, it has to define an [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") method that returns an integer. Some examples: ``` >>> bin(3) '0b11' >>> bin(-10) '-0b1010' ``` If prefix “0b” is desired or not, you can use either of the following ways. ``` >>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') ``` See also [`format()`](#format "format") for more information. `class bool([x])` Return a Boolean value, i.e. one of `True` or `False`. *x* is converted using the standard [truth testing procedure](stdtypes#truth). If *x* is false or omitted, this returns `False`; otherwise it returns `True`. The [`bool`](#bool "bool") class is a subclass of [`int`](#int "int") (see [Numeric Types — int, float, complex](stdtypes#typesnumeric)). It cannot be subclassed further. Its only instances are `False` and `True` (see [Boolean Values](stdtypes#bltin-boolean-values)). Changed in version 3.7: *x* is now a positional-only parameter. `breakpoint(*args, **kws)` This function drops you into the debugger at the call site. Specifically, it calls [`sys.breakpointhook()`](sys#sys.breakpointhook "sys.breakpointhook"), passing `args` and `kws` straight through. By default, `sys.breakpointhook()` calls [`pdb.set_trace()`](pdb#pdb.set_trace "pdb.set_trace") expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import [`pdb`](pdb#module-pdb "pdb: The Python debugger for interactive interpreters.") or type as much code to enter the debugger. However, [`sys.breakpointhook()`](sys#sys.breakpointhook "sys.breakpointhook") can be set to some other function and [`breakpoint()`](#breakpoint "breakpoint") will automatically call that, allowing you to drop into the debugger of choice. Raises an [auditing event](sys#auditing) `builtins.breakpoint` with argument `breakpointhook`. New in version 3.7. `class bytearray([source[, encoding[, errors]]])` Return a new array of bytes. The [`bytearray`](stdtypes#bytearray "bytearray") class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in [Mutable Sequence Types](stdtypes#typesseq-mutable), as well as most methods that the [`bytes`](stdtypes#bytes "bytes") type has, see [Bytes and Bytearray Operations](stdtypes#bytes-methods). The optional *source* parameter can be used to initialize the array in a few different ways: * If it is a *string*, you must also give the *encoding* (and optionally, *errors*) parameters; [`bytearray()`](stdtypes#bytearray "bytearray") then converts the string to bytes using [`str.encode()`](stdtypes#str.encode "str.encode"). * If it is an *integer*, the array will have that size and will be initialized with null bytes. * If it is an object conforming to the [buffer interface](../c-api/buffer#bufferobjects), a read-only buffer of the object will be used to initialize the bytes array. * If it is an *iterable*, it must be an iterable of integers in the range `0 <= x < 256`, which are used as the initial contents of the array. Without an argument, an array of size 0 is created. See also [Binary Sequence Types — bytes, bytearray, memoryview](stdtypes#binaryseq) and [Bytearray Objects](stdtypes#typebytearray). `class bytes([source[, encoding[, errors]]])` Return a new “bytes” object, which is an immutable sequence of integers in the range `0 <= x < 256`. [`bytes`](stdtypes#bytes "bytes") is an immutable version of [`bytearray`](stdtypes#bytearray "bytearray") – it has the same non-mutating methods and the same indexing and slicing behavior. Accordingly, constructor arguments are interpreted as for [`bytearray()`](stdtypes#bytearray "bytearray"). Bytes objects can also be created with literals, see [String and Bytes literals](../reference/lexical_analysis#strings). See also [Binary Sequence Types — bytes, bytearray, memoryview](stdtypes#binaryseq), [Bytes Objects](stdtypes#typebytes), and [Bytes and Bytearray Operations](stdtypes#bytes-methods). `callable(object)` Return [`True`](constants#True "True") if the *object* argument appears callable, [`False`](constants#False "False") if not. If this returns `True`, it is still possible that a call fails, but if it is `False`, calling *object* will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a [`__call__()`](../reference/datamodel#object.__call__ "object.__call__") method. New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2. `chr(i)` Return the string representing a character whose Unicode code point is the integer *i*. For example, `chr(97)` returns the string `'a'`, while `chr(8364)` returns the string `'€'`. This is the inverse of [`ord()`](#ord "ord"). The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). [`ValueError`](exceptions#ValueError "ValueError") will be raised if *i* is outside that range. `@classmethod` Transform a method into a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: ``` class C: @classmethod def f(cls, arg1, arg2): ... ``` The `@classmethod` form is a function [decorator](../glossary#term-decorator) – see [Function definitions](../reference/compound_stmts#function) for details. A class method can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see [`staticmethod()`](#staticmethod "staticmethod") in this section. For more information on class methods, see [The standard type hierarchy](../reference/datamodel#types). Changed in version 3.9: Class methods can now wrap other [descriptors](../glossary#term-descriptor) such as [`property()`](#property "property"). `compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)` Compile the *source* into a code or AST object. Code objects can be executed by [`exec()`](#exec "exec") or [`eval()`](#eval "eval"). *source* can either be a normal string, a byte string, or an AST object. Refer to the [`ast`](ast#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module documentation for information on how to work with AST objects. The *filename* argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file (`'<string>'` is commonly used). The *mode* argument specifies what kind of code must be compiled; it can be `'exec'` if *source* consists of a sequence of statements, `'eval'` if it consists of a single expression, or `'single'` if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than `None` will be printed). The optional arguments *flags* and *dont\_inherit* control which [compiler options](ast#ast-compiler-flags) should be activated and which [future features](../reference/simple_stmts#future) should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling [`compile()`](#compile "compile"). If the *flags* argument is given and *dont\_inherit* is not (or is zero) then the compiler options and the future statements specified by the *flags* argument are used in addition to those that would be used anyway. If *dont\_inherit* is a non-zero integer then the *flags* argument is it – the flags (future features and compiler options) in the surrounding code are ignored. Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the `compiler_flag` attribute on the `_Feature` instance in the [`__future__`](__future__#module-__future__ "__future__: Future statement definitions") module. [Compiler flags](ast#ast-compiler-flags) can be found in [`ast`](ast#module-ast "ast: Abstract Syntax Tree classes and manipulation.") module, with `PyCF_` prefix. The argument *optimize* specifies the optimization level of the compiler; the default value of `-1` selects the optimization level of the interpreter as given by [`-O`](../using/cmdline#cmdoption-o) options. Explicit levels are `0` (no optimization; `__debug__` is true), `1` (asserts are removed, `__debug__` is false) or `2` (docstrings are removed too). This function raises [`SyntaxError`](exceptions#SyntaxError "SyntaxError") if the compiled source is invalid, and [`ValueError`](exceptions#ValueError "ValueError") if the source contains null bytes. If you want to parse Python code into its AST representation, see [`ast.parse()`](ast#ast.parse "ast.parse"). Raises an [auditing event](sys#auditing) `compile` with arguments `source` and `filename`. This event may also be raised by implicit compilation. Note When compiling a string with multi-line code in `'single'` or `'eval'` mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the [`code`](code#module-code "code: Facilities to implement read-eval-print loops.") module. Warning It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler. Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in `'exec'` mode does not have to end in a newline anymore. Added the *optimize* parameter. Changed in version 3.5: Previously, [`TypeError`](exceptions#TypeError "TypeError") was raised when null bytes were encountered in *source*. New in version 3.8: `ast.PyCF_ALLOW_TOP_LEVEL_AWAIT` can now be passed in flags to enable support for top-level `await`, `async for`, and `async with`. `class complex([real[, imag]])` Return a complex number with the value *real* + *imag*\*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If *imag* is omitted, it defaults to zero and the constructor serves as a numeric conversion like [`int`](#int "int") and [`float`](#float "float"). If both arguments are omitted, returns `0j`. For a general Python object `x`, `complex(x)` delegates to `x.__complex__()`. If `__complex__()` is not defined then it falls back to [`__float__()`](../reference/datamodel#object.__float__ "object.__float__"). If `__float__()` is not defined then it falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__"). Note When converting from a string, the string must not contain whitespace around the central `+` or `-` operator. For example, `complex('1+2j')` is fine, but `complex('1 + 2j')` raises [`ValueError`](exceptions#ValueError "ValueError"). The complex type is described in [Numeric Types — int, float, complex](stdtypes#typesnumeric). Changed in version 3.6: Grouping digits with underscores as in code literals is allowed. Changed in version 3.8: Falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if [`__complex__()`](../reference/datamodel#object.__complex__ "object.__complex__") and [`__float__()`](../reference/datamodel#object.__float__ "object.__float__") are not defined. `delattr(object, name)` This is a relative of [`setattr()`](#setattr "setattr"). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, `delattr(x, 'foobar')` is equivalent to `del x.foobar`. `class dict(**kwarg)` `class dict(mapping, **kwarg)` `class dict(iterable, **kwarg)` Create a new dictionary. The [`dict`](stdtypes#dict "dict") object is the dictionary class. See [`dict`](stdtypes#dict "dict") and [Mapping Types — dict](stdtypes#typesmapping) for documentation about this class. For other containers see the built-in [`list`](stdtypes#list "list"), [`set`](stdtypes#set "set"), and [`tuple`](stdtypes#tuple "tuple") classes, as well as the [`collections`](collections#module-collections "collections: Container datatypes") module. `dir([object])` Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. If the object has a method named [`__dir__()`](../reference/datamodel#object.__dir__ "object.__dir__"), this method will be called and must return the list of attributes. This allows objects that implement a custom [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__") or [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") function to customize the way [`dir()`](#dir "dir") reports their attributes. If the object does not provide [`__dir__()`](../reference/datamodel#object.__dir__ "object.__dir__"), the function tries its best to gather information from the object’s [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom [`__getattr__()`](../reference/datamodel#object.__getattr__ "object.__getattr__"). The default [`dir()`](#dir "dir") mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information: * If the object is a module object, the list contains the names of the module’s attributes. * If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. * Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes. The resulting list is sorted alphabetically. For example: ``` >>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter'] ``` Note Because [`dir()`](#dir "dir") is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class. `divmod(a, b)` Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as `(a // b, a % b)`. For floating point numbers the result is `(q, a % b)`, where *q* is usually `math.floor(a / b)` but may be 1 less than that. In any case `q * b + a % b` is very close to *a*, if `a % b` is non-zero it has the same sign as *b*, and `0 <= abs(a % b) < abs(b)`. `enumerate(iterable, start=0)` Return an enumerate object. *iterable* must be a sequence, an [iterator](../glossary#term-iterator), or some other object which supports iteration. The [`__next__()`](stdtypes#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*. ``` >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] ``` Equivalent to: ``` def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ``` `eval(expression[, globals[, locals]])` The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object. The *expression* argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the *globals* and *locals* dictionaries as global and local namespace. If the *globals* dictionary is present and does not contain a value for the key `__builtins__`, a reference to the dictionary of the built-in module [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") is inserted under that key before *expression* is parsed. This means that *expression* normally has full access to the standard [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") module and restricted environments are propagated. If the *locals* dictionary is omitted it defaults to the *globals* dictionary. If both dictionaries are omitted, the expression is executed with the *globals* and *locals* in the environment where [`eval()`](#eval "eval") is called. Note, *eval()* does not have access to the [nested scopes](../glossary#term-nested-scope) (non-locals) in the enclosing environment. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example: ``` >>> x = 1 >>> eval('x+1') 2 ``` This function can also be used to execute arbitrary code objects (such as those created by [`compile()`](#compile "compile")). In this case pass a code object instead of a string. If the code object has been compiled with `'exec'` as the *mode* argument, [`eval()`](#eval "eval")’s return value will be `None`. Hints: dynamic execution of statements is supported by the [`exec()`](#exec "exec") function. The [`globals()`](#globals "globals") and [`locals()`](#locals "locals") functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by [`eval()`](#eval "eval") or [`exec()`](#exec "exec"). See [`ast.literal_eval()`](ast#ast.literal_eval "ast.literal_eval") for a function that can safely evaluate strings with expressions containing only literals. Raises an [auditing event](sys#auditing) `exec` with the code object as the argument. Code compilation events may also be raised. `exec(object[, globals[, locals]])` This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](../reference/toplevel_components#file-input) in the Reference Manual). Be aware that the [`nonlocal`](../reference/simple_stmts#nonlocal), [`yield`](../reference/simple_stmts#yield), and [`return`](../reference/simple_stmts#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](#exec "exec") function. The return value is `None`. In all cases, if the optional parts are omitted, the code is executed in the current scope. If only *globals* is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If *globals* and *locals* are given, they are used for the global and local variables, respectively. If provided, *locals* can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as *globals* and *locals*, the code will be executed as if it were embedded in a class definition. If the *globals* dictionary does not contain a value for the key `__builtins__`, a reference to the dictionary of the built-in module [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own `__builtins__` dictionary into *globals* before passing it to [`exec()`](#exec "exec"). Raises an [auditing event](sys#auditing) `exec` with the code object as the argument. Code compilation events may also be raised. Note The built-in functions [`globals()`](#globals "globals") and [`locals()`](#locals "locals") return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to [`exec()`](#exec "exec"). Note The default *locals* act as described for function [`locals()`](#locals "locals") below: modifications to the default *locals* dictionary should not be attempted. Pass an explicit *locals* dictionary if you need to see effects of the code on *locals* after function [`exec()`](#exec "exec") returns. `filter(function, iterable)` Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed. Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`. See [`itertools.filterfalse()`](itertools#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false. `class float([x])` Return a floating point number constructed from a number or string *x*. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be `'+'` or `'-'`; a `'+'` sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed: ``` **sign** ::= "+" | "-" **infinity** ::= "Infinity" | "inf" **nan** ::= "nan" **numeric\_value** ::= [floatnumber](../reference/lexical_analysis#grammar-token-floatnumber) | [infinity](#grammar-token-infinity) | [nan](#grammar-token-nan) **numeric\_string** ::= [[sign](string#grammar-token-sign)] [numeric\_value](#grammar-token-numeric-value) ``` Here `floatnumber` is the form of a Python floating-point literal, described in [Floating point literals](../reference/lexical_analysis#floating). Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity. Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an [`OverflowError`](exceptions#OverflowError "OverflowError") will be raised. For a general Python object `x`, `float(x)` delegates to `x.__float__()`. If `__float__()` is not defined then it falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__"). If no argument is given, `0.0` is returned. Examples: ``` >>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf ``` The float type is described in [Numeric Types — int, float, complex](stdtypes#typesnumeric). Changed in version 3.6: Grouping digits with underscores as in code literals is allowed. Changed in version 3.7: *x* is now a positional-only parameter. Changed in version 3.8: Falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if [`__float__()`](../reference/datamodel#object.__float__ "object.__float__") is not defined. `format(value[, format_spec])` Convert a *value* to a “formatted” representation, as controlled by *format\_spec*. The interpretation of *format\_spec* will depend on the type of the *value* argument, however there is a standard formatting syntax that is used by most built-in types: [Format Specification Mini-Language](string#formatspec). The default *format\_spec* is an empty string which usually gives the same effect as calling [`str(value)`](stdtypes#str "str"). A call to `format(value, format_spec)` is translated to `type(value).__format__(value, format_spec)` which bypasses the instance dictionary when searching for the value’s [`__format__()`](../reference/datamodel#object.__format__ "object.__format__") method. A [`TypeError`](exceptions#TypeError "TypeError") exception is raised if the method search reaches [`object`](#object "object") and the *format\_spec* is non-empty, or if either the *format\_spec* or the return value are not strings. Changed in version 3.4: `object().__format__(format_spec)` raises [`TypeError`](exceptions#TypeError "TypeError") if *format\_spec* is not an empty string. `class frozenset([iterable])` Return a new [`frozenset`](stdtypes#frozenset "frozenset") object, optionally with elements taken from *iterable*. `frozenset` is a built-in class. See [`frozenset`](stdtypes#frozenset "frozenset") and [Set Types — set, frozenset](stdtypes#types-set) for documentation about this class. For other containers see the built-in [`set`](stdtypes#set "set"), [`list`](stdtypes#list "list"), [`tuple`](stdtypes#tuple "tuple"), and [`dict`](stdtypes#dict "dict") classes, as well as the [`collections`](collections#module-collections "collections: Container datatypes") module. `getattr(object, name[, default])` Return the value of the named attribute of *object*. *name* must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. If the named attribute does not exist, *default* is returned if provided, otherwise [`AttributeError`](exceptions#AttributeError "AttributeError") is raised. Note Since [private name mangling](../reference/expressions#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with [`getattr()`](#getattr "getattr"). `globals()` Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called. `hasattr(object, name)` The arguments are an object and a string. The result is `True` if the string is the name of one of the object’s attributes, `False` if not. (This is implemented by calling `getattr(object, name)` and seeing whether it raises an [`AttributeError`](exceptions#AttributeError "AttributeError") or not.) `hash(object)` Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0). Note For objects with custom [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") methods, note that [`hash()`](#hash "hash") truncates the return value based on the bit width of the host machine. See [`__hash__()`](../reference/datamodel#object.__hash__ "object.__hash__") for details. `help([object])` Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated. Note that if a slash(/) appears in the parameter list of a function, when invoking [`help()`](#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](../faq/programming#faq-positional-only-arguments). This function is added to the built-in namespace by the [`site`](site#module-site "site: Module responsible for site-specific configuration.") module. Changed in version 3.4: Changes to [`pydoc`](pydoc#module-pydoc "pydoc: Documentation generator and online help system.") and [`inspect`](inspect#module-inspect "inspect: Extract information and source code from live objects.") mean that the reported signatures for callables are now more comprehensive and consistent. `hex(x)` Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If *x* is not a Python [`int`](#int "int") object, it has to define an [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") method that returns an integer. Some examples: ``` >>> hex(255) '0xff' >>> hex(-42) '-0x2a' ``` If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways: ``` >>> '%#x' % 255, '%x' % 255, '%X' % 255 ('0xff', 'ff', 'FF') >>> format(255, '#x'), format(255, 'x'), format(255, 'X') ('0xff', 'ff', 'FF') >>> f'{255:#x}', f'{255:x}', f'{255:X}' ('0xff', 'ff', 'FF') ``` See also [`format()`](#format "format") for more information. See also [`int()`](#int "int") for converting a hexadecimal string to an integer using a base of 16. Note To obtain a hexadecimal string representation for a float, use the [`float.hex()`](stdtypes#float.hex "float.hex") method. `id(object)` Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same [`id()`](#id "id") value. **CPython implementation detail:** This is the address of the object in memory. Raises an [auditing event](sys#auditing) `builtins.id` with argument `id`. `input([prompt])` If the *prompt* argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, [`EOFError`](exceptions#EOFError "EOFError") is raised. Example: ``` >>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus" ``` If the [`readline`](readline#module-readline "readline: GNU readline support for Python. (Unix)") module was loaded, then [`input()`](#input "input") will use it to provide elaborate line editing and history features. Raises an [auditing event](sys#auditing) `builtins.input` with argument `prompt` before reading input Raises an auditing event `builtins.input/result` with the result after successfully reading input. `class int([x])` `class int(x, base=10)` Return an integer object constructed from a number or string *x*, or return `0` if no arguments are given. If *x* defines [`__int__()`](../reference/datamodel#object.__int__ "object.__int__"), `int(x)` returns `x.__int__()`. If *x* defines [`__index__()`](../reference/datamodel#object.__index__ "object.__index__"), it returns `x.__index__()`. If *x* defines [`__trunc__()`](../reference/datamodel#object.__trunc__ "object.__trunc__"), it returns `x.__trunc__()`. For floating point numbers, this truncates towards zero. If *x* is not a number or if *base* is given, then *x* must be a string, [`bytes`](stdtypes#bytes "bytes"), or [`bytearray`](stdtypes#bytearray "bytearray") instance representing an [integer literal](../reference/lexical_analysis#integers) in radix *base*. Optionally, the literal can be preceded by `+` or `-` (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with `a` to `z` (or `A` to `Z`) having values 10 to 35. The default *base* is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with `0b`/`0B`, `0o`/`0O`, or `0x`/`0X`, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that `int('010', 0)` is not legal, while `int('010')` is, as well as `int('010', 8)`. The integer type is described in [Numeric Types — int, float, complex](stdtypes#typesnumeric). Changed in version 3.4: If *base* is not an instance of [`int`](#int "int") and the *base* object has a [`base.__index__`](../reference/datamodel#object.__index__ "object.__index__") method, that method is called to obtain an integer for the base. Previous versions used [`base.__int__`](../reference/datamodel#object.__int__ "object.__int__") instead of [`base.__index__`](../reference/datamodel#object.__index__ "object.__index__"). Changed in version 3.6: Grouping digits with underscores as in code literals is allowed. Changed in version 3.7: *x* is now a positional-only parameter. Changed in version 3.8: Falls back to [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") if [`__int__()`](../reference/datamodel#object.__int__ "object.__int__") is not defined. Changed in version 3.9.14: [`int`](#int "int") string inputs and string representations can be limited to help avoid denial of service attacks. A [`ValueError`](exceptions#ValueError "ValueError") is raised when the limit is exceeded while converting a string *x* to an [`int`](#int "int") or when converting an [`int`](#int "int") into a string would exceed the limit. See the [integer string conversion length limitation](stdtypes#int-max-str-digits) documentation. `isinstance(object, classinfo)` Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect or [virtual](../glossary#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples), return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](exceptions#TypeError "TypeError") exception is raised. `issubclass(class, classinfo)` Return `True` if *class* is a subclass (direct, indirect or [virtual](../glossary#term-abstract-base-class)) of *classinfo*. A class is considered a subclass of itself. *classinfo* may be a tuple of class objects (or recursively, other such tuples), in which case return `True` if *class* is a subclass of any entry in *classinfo*. In any other case, a [`TypeError`](exceptions#TypeError "TypeError") exception is raised. `iter(object[, sentinel])` Return an [iterator](../glossary#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the iteration protocol (the [`__iter__()`](../reference/datamodel#object.__iter__ "object.__iter__") method), or it must support the sequence protocol (the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](exceptions#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object. The iterator created in this case will call *object* with no arguments for each call to its [`__next__()`](stdtypes#iterator.__next__ "iterator.__next__") method; if the value returned is equal to *sentinel*, [`StopIteration`](exceptions#StopIteration "StopIteration") will be raised, otherwise the value will be returned. See also [Iterator Types](stdtypes#typeiter). One useful application of the second form of [`iter()`](#iter "iter") is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached: ``` from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block) ``` `len(s)` Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). **CPython implementation detail:** `len` raises [`OverflowError`](exceptions#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](sys#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](stdtypes#range "range"). `class list([iterable])` Rather than being a function, [`list`](stdtypes#list "list") is actually a mutable sequence type, as documented in [Lists](stdtypes#typesseq-list) and [Sequence Types — list, tuple, range](stdtypes#typesseq). `locals()` Update and return a dictionary representing the current local symbol table. Free variables are returned by [`locals()`](#locals "locals") when it is called in function blocks, but not in class blocks. Note that at the module level, [`locals()`](#locals "locals") and [`globals()`](#globals "globals") are the same dictionary. Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. `map(function, iterable, ...)` Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](itertools#itertools.starmap "itertools.starmap"). `max(iterable, *[, key, default])` `max(arg1, arg2, *args[, key])` Return the largest item in an iterable or the largest of two or more arguments. If one positional argument is provided, it should be an [iterable](../glossary#term-iterable). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. There are two optional keyword-only arguments. The *key* argument specifies a one-argument ordering function like that used for [`list.sort()`](stdtypes#list.sort "list.sort"). The *default* argument specifies an object to return if the provided iterable is empty. If the iterable is empty and *default* is not provided, a [`ValueError`](exceptions#ValueError "ValueError") is raised. If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as `sorted(iterable, key=keyfunc, reverse=True)[0]` and `heapq.nlargest(1, iterable, key=keyfunc)`. New in version 3.4: The *default* keyword-only argument. Changed in version 3.8: The *key* can be `None`. `class memoryview(object)` Return a “memory view” object created from the given argument. See [Memory Views](stdtypes#typememoryview) for more information. `min(iterable, *[, key, default])` `min(arg1, arg2, *args[, key])` Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an [iterable](../glossary#term-iterable). The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. There are two optional keyword-only arguments. The *key* argument specifies a one-argument ordering function like that used for [`list.sort()`](stdtypes#list.sort "list.sort"). The *default* argument specifies an object to return if the provided iterable is empty. If the iterable is empty and *default* is not provided, a [`ValueError`](exceptions#ValueError "ValueError") is raised. If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as `sorted(iterable, key=keyfunc)[0]` and `heapq.nsmallest(1, iterable, key=keyfunc)`. New in version 3.4: The *default* keyword-only argument. Changed in version 3.8: The *key* can be `None`. `next(iterator[, default])` Retrieve the next item from the *iterator* by calling its [`__next__()`](stdtypes#iterator.__next__ "iterator.__next__") method. If *default* is given, it is returned if the iterator is exhausted, otherwise [`StopIteration`](exceptions#StopIteration "StopIteration") is raised. `class object` Return a new featureless object. [`object`](#object "object") is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments. Note [`object`](#object "object") does *not* have a [`__dict__`](stdtypes#object.__dict__ "object.__dict__"), so you can’t assign arbitrary attributes to an instance of the [`object`](#object "object") class. `oct(x)` Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If *x* is not a Python [`int`](#int "int") object, it has to define an [`__index__()`](../reference/datamodel#object.__index__ "object.__index__") method that returns an integer. For example: ``` >>> oct(8) '0o10' >>> oct(-56) '-0o70' ``` If you want to convert an integer number to octal string either with prefix “0o” or not, you can use either of the following ways. ``` >>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12') ``` See also [`format()`](#format "format") for more information. `open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)` Open *file* and return a corresponding [file object](../glossary#term-file-object). If the file cannot be opened, an [`OSError`](exceptions#OSError "OSError") is raised. See [Reading and Writing Files](../tutorial/inputoutput#tut-files) for more examples of how to use this function. *file* is a [path-like object](../glossary#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless *closefd* is set to `False`.) *mode* is an optional string that specifies the mode in which the file is opened. It defaults to `'r'` which means open for reading in text mode. Other common values are `'w'` for writing (truncating the file if it already exists), `'x'` for exclusive creation and `'a'` for appending (which on *some* Unix systems, means that *all* writes append to the end of the file regardless of the current seek position). In text mode, if *encoding* is not specified the encoding used is platform dependent: `locale.getpreferredencoding(False)` is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave *encoding* unspecified.) The available modes are: | Character | Meaning | | --- | --- | | `'r'` | open for reading (default) | | `'w'` | open for writing, truncating the file first | | `'x'` | open for exclusive creation, failing if the file already exists | | `'a'` | open for writing, appending to the end of the file if it exists | | `'b'` | binary mode | | `'t'` | text mode (default) | | `'+'` | open for updating (reading and writing) | The default mode is `'r'` (open for reading text, synonym of `'rt'`). Modes `'w+'` and `'w+b'` open and truncate the file. Modes `'r+'` and `'r+b'` open the file with no truncation. As mentioned in the [Overview](io#io-overview), Python distinguishes between binary and text I/O. Files opened in binary mode (including `'b'` in the *mode* argument) return contents as [`bytes`](stdtypes#bytes "bytes") objects without any decoding. In text mode (the default, or when `'t'` is included in the *mode* argument), the contents of the file are returned as [`str`](stdtypes#str "str"), the bytes having been first decoded using a platform-dependent encoding or using the specified *encoding* if given. There is an additional mode character permitted, `'U'`, which no longer has any effect, and is considered deprecated. It previously enabled [universal newlines](../glossary#term-universal-newlines) in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the [newline](#open-newline-parameter) parameter for further details. Note Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent. *buffering* is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but `TextIOWrapper` (i.e., files opened with `mode='r+'`) would have another buffering. To disable buffering in `TextIOWrapper`, consider using the `write_through` flag for [`io.TextIOWrapper.reconfigure()`](io#io.TextIOWrapper.reconfigure "io.TextIOWrapper.reconfigure"). When no *buffering* argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on [`io.DEFAULT_BUFFER_SIZE`](io#io.DEFAULT_BUFFER_SIZE "io.DEFAULT_BUFFER_SIZE"). On many systems, the buffer will typically be 4096 or 8192 bytes long. * “Interactive” text files (files for which [`isatty()`](io#io.IOBase.isatty "io.IOBase.isatty") returns `True`) use line buffering. Other text files use the policy described above for binary files. *encoding* is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever [`locale.getpreferredencoding()`](locale#locale.getpreferredencoding "locale.getpreferredencoding") returns), but any [text encoding](../glossary#term-text-encoding) supported by Python can be used. See the [`codecs`](codecs#module-codecs "codecs: Encode and decode data and streams.") module for the list of supported encodings. *errors* is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under [Error Handlers](codecs#error-handlers)), though any error handling name that has been registered with [`codecs.register_error()`](codecs#codecs.register_error "codecs.register_error") is also valid. The standard names include: * `'strict'` to raise a [`ValueError`](exceptions#ValueError "ValueError") exception if there is an encoding error. The default value of `None` has the same effect. * `'ignore'` ignores errors. Note that ignoring encoding errors can lead to data loss. * `'replace'` causes a replacement marker (such as `'?'`) to be inserted where there is malformed data. * `'surrogateescape'` will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the `surrogateescape` error handler is used when writing data. This is useful for processing files in an unknown encoding. * `'xmlcharrefreplace'` is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference `&#nnn;`. * `'backslashreplace'` replaces malformed data by Python’s backslashed escape sequences. * `'namereplace'` (also only supported when writing) replaces unsupported characters with `\N{...}` escape sequences. *newline* controls how [universal newlines](../glossary#term-universal-newlines) mode works (it only applies to text mode). It can be `None`, `''`, `'\n'`, `'\r'`, and `'\r\n'`. It works as follows: * When reading input from the stream, if *newline* is `None`, universal newlines mode is enabled. Lines in the input can end in `'\n'`, `'\r'`, or `'\r\n'`, and these are translated into `'\n'` before being returned to the caller. If it is `''`, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * When writing output to the stream, if *newline* is `None`, any `'\n'` characters written are translated to the system default line separator, [`os.linesep`](os#os.linesep "os.linesep"). If *newline* is `''` or `'\n'`, no translation takes place. If *newline* is any of the other legal values, any `'\n'` characters written are translated to the given string. If *closefd* is `False` and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given *closefd* must be `True` (the default) otherwise an error will be raised. A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing [`os.open`](os#os.open "os.open") as *opener* results in functionality similar to passing `None`). The newly created file is [non-inheritable](os#fd-inheritance). The following example uses the [dir\_fd](os#dir-fd) parameter of the [`os.open()`](os#os.open "os.open") function to open a file relative to a given directory: ``` >>> import os >>> dir_fd = os.open('somedir', os.O_RDONLY) >>> def opener(path, flags): ... return os.open(path, flags, dir_fd=dir_fd) ... >>> with open('spamspam.txt', 'w', opener=opener) as f: ... print('This will be written to somedir/spamspam.txt', file=f) ... >>> os.close(dir_fd) # don't leak a file descriptor ``` The type of [file object](../glossary#term-file-object) returned by the [`open()`](#open "open") function depends on the mode. When [`open()`](#open "open") is used to open a file in a text mode (`'w'`, `'r'`, `'wt'`, `'rt'`, etc.), it returns a subclass of [`io.TextIOBase`](io#io.TextIOBase "io.TextIOBase") (specifically [`io.TextIOWrapper`](io#io.TextIOWrapper "io.TextIOWrapper")). When used to open a file in a binary mode with buffering, the returned class is a subclass of [`io.BufferedIOBase`](io#io.BufferedIOBase "io.BufferedIOBase"). The exact class varies: in read binary mode, it returns an [`io.BufferedReader`](io#io.BufferedReader "io.BufferedReader"); in write binary and append binary modes, it returns an [`io.BufferedWriter`](io#io.BufferedWriter "io.BufferedWriter"), and in read/write mode, it returns an [`io.BufferedRandom`](io#io.BufferedRandom "io.BufferedRandom"). When buffering is disabled, the raw stream, a subclass of [`io.RawIOBase`](io#io.RawIOBase "io.RawIOBase"), [`io.FileIO`](io#io.FileIO "io.FileIO"), is returned. See also the file handling modules, such as, [`fileinput`](fileinput#module-fileinput "fileinput: Loop over standard input or a list of files."), [`io`](io#module-io "io: Core tools for working with streams.") (where [`open()`](#open "open") is declared), [`os`](os#module-os "os: Miscellaneous operating system interfaces."), [`os.path`](os.path#module-os.path "os.path: Operations on pathnames."), [`tempfile`](tempfile#module-tempfile "tempfile: Generate temporary files and directories."), and [`shutil`](shutil#module-shutil "shutil: High-level file operations, including copying."). Raises an [auditing event](sys#auditing) `open` with arguments `file`, `mode`, `flags`. The `mode` and `flags` arguments may have been modified or inferred from the original call. Changed in version 3.3: * The *opener* parameter was added. * The `'x'` mode was added. * [`IOError`](exceptions#IOError "IOError") used to be raised, it is now an alias of [`OSError`](exceptions#OSError "OSError"). * [`FileExistsError`](exceptions#FileExistsError "FileExistsError") is now raised if the file opened in exclusive creation mode (`'x'`) already exists. Changed in version 3.4: * The file is now non-inheritable. Deprecated since version 3.4, will be removed in version 3.10: The `'U'` mode. Changed in version 3.5: * If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an [`InterruptedError`](exceptions#InterruptedError "InterruptedError") exception (see [**PEP 475**](https://www.python.org/dev/peps/pep-0475) for the rationale). * The `'namereplace'` error handler was added. Changed in version 3.6: * Support added to accept objects implementing [`os.PathLike`](os#os.PathLike "os.PathLike"). * On Windows, opening a console buffer may return a subclass of [`io.RawIOBase`](io#io.RawIOBase "io.RawIOBase") other than [`io.FileIO`](io#io.FileIO "io.FileIO"). `ord(c)` Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, `ord('a')` returns the integer `97` and `ord('€')` (Euro sign) returns `8364`. This is the inverse of [`chr()`](#chr "chr"). `pow(base, exp[, mod])` Return *base* to the power *exp*; if *mod* is present, return *base* to the power *exp*, modulo *mod* (computed more efficiently than `pow(base, exp) % mod`). The two-argument form `pow(base, exp)` is equivalent to using the power operator: `base**exp`. The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For [`int`](#int "int") operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, `pow(10, 2)` returns `100`, but `pow(10, -2)` returns `0.01`. For a negative base of type [`int`](#int "int") or [`float`](#float "float") and a non-integral exponent, a complex result is delivered. For example, `pow(-9, 0.5)` returns a value close to `3j`. For [`int`](#int "int") operands *base* and *exp*, if *mod* is present, *mod* must also be of integer type and *mod* must be nonzero. If *mod* is present and *exp* is negative, *base* must be relatively prime to *mod*. In that case, `pow(inv_base, -exp, mod)` is returned, where *inv\_base* is an inverse to *base* modulo *mod*. Here’s an example of computing an inverse for `38` modulo `97`: ``` >>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True ``` Changed in version 3.8: For [`int`](#int "int") operands, the three-argument form of `pow` now allows the second argument to be negative, permitting computation of modular inverses. Changed in version 3.8: Allow keyword arguments. Formerly, only positional arguments were supported. `print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)` Print *objects* to the text stream *file*, separated by *sep* and followed by *end*. *sep*, *end*, *file* and *flush*, if present, must be given as keyword arguments. All non-keyword arguments are converted to strings like [`str()`](stdtypes#str "str") does and written to the stream, separated by *sep* and followed by *end*. Both *sep* and *end* must be strings; they can also be `None`, which means to use the default values. If no *objects* are given, [`print()`](#print "print") will just write *end*. The *file* argument must be an object with a `write(string)` method; if it is not present or `None`, [`sys.stdout`](sys#sys.stdout "sys.stdout") will be used. Since printed arguments are converted to text strings, [`print()`](#print "print") cannot be used with binary mode file objects. For these, use `file.write(...)` instead. Whether output is buffered is usually determined by *file*, but if the *flush* keyword argument is true, the stream is forcibly flushed. Changed in version 3.3: Added the *flush* keyword argument. `class property(fget=None, fset=None, fdel=None, doc=None)` Return a property attribute. *fget* is a function for getting an attribute value. *fset* is a function for setting an attribute value. *fdel* is a function for deleting an attribute value. And *doc* creates a docstring for the attribute. A typical use is to define a managed attribute `x`: ``` class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") ``` If *c* is an instance of *C*, `c.x` will invoke the getter, `c.x = value` will invoke the setter and `del c.x` the deleter. If given, *doc* will be the docstring of the property attribute. Otherwise, the property will copy *fget*’s docstring (if it exists). This makes it possible to create read-only properties easily using [`property()`](#property "property") as a [decorator](../glossary#term-decorator): ``` class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage ``` The `@property` decorator turns the `voltage()` method into a “getter” for a read-only attribute with the same name, and it sets the docstring for *voltage* to “Get the current voltage.” A property object has `getter`, `setter`, and `deleter` methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example: ``` class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x ``` This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (`x` in this case.) The returned property object also has the attributes `fget`, `fset`, and `fdel` corresponding to the constructor arguments. Changed in version 3.5: The docstrings of property objects are now writeable. `class range(stop)` `class range(start, stop[, step])` Rather than being a function, [`range`](stdtypes#range "range") is actually an immutable sequence type, as documented in [Ranges](stdtypes#typesseq-range) and [Sequence Types — list, tuple, range](stdtypes#typesseq). `repr(object)` Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to [`eval()`](#eval "eval"), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a [`__repr__()`](../reference/datamodel#object.__repr__ "object.__repr__") method. `reversed(seq)` Return a reverse [iterator](../glossary#term-iterator). *seq* must be an object which has a [`__reversed__()`](../reference/datamodel#object.__reversed__ "object.__reversed__") method or supports the sequence protocol (the [`__len__()`](../reference/datamodel#object.__len__ "object.__len__") method and the [`__getitem__()`](../reference/datamodel#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). `round(number[, ndigits])` Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input. For the built-in types supporting [`round()`](#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise the return value has the same type as *number*. For a general Python object `number`, `round` delegates to `number.__round__`. Note The behavior of [`round()`](#round "round") for floats can be surprising: for example, `round(2.675, 2)` gives `2.67` instead of the expected `2.68`. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See [Floating Point Arithmetic: Issues and Limitations](../tutorial/floatingpoint#tut-fp-issues) for more information. `class set([iterable])` Return a new [`set`](stdtypes#set "set") object, optionally with elements taken from *iterable*. `set` is a built-in class. See [`set`](stdtypes#set "set") and [Set Types — set, frozenset](stdtypes#types-set) for documentation about this class. For other containers see the built-in [`frozenset`](stdtypes#frozenset "frozenset"), [`list`](stdtypes#list "list"), [`tuple`](stdtypes#tuple "tuple"), and [`dict`](stdtypes#dict "dict") classes, as well as the [`collections`](collections#module-collections "collections: Container datatypes") module. `setattr(object, name, value)` This is the counterpart of [`getattr()`](#getattr "getattr"). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, `setattr(x, 'foobar', 123)` is equivalent to `x.foobar = 123`. Note Since [private name mangling](../reference/expressions#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to set it with [`setattr()`](#setattr "setattr"). `class slice(stop)` `class slice(start, stop[, step])` Return a [slice](../glossary#term-slice) object representing the set of indices specified by `range(start, stop, step)`. The *start* and *step* arguments default to `None`. Slice objects have read-only data attributes `start`, `stop` and `step` which merely return the argument values (or their default). They have no other explicit functionality; however they are used by NumPy and other third party packages. Slice objects are also generated when extended indexing syntax is used. For example: `a[start:stop:step]` or `a[start:stop, i]`. See [`itertools.islice()`](itertools#itertools.islice "itertools.islice") for an alternate version that returns an iterator. `sorted(iterable, /, *, key=None, reverse=False)` Return a new sorted list from the items in *iterable*. Has two optional arguments which must be specified as keyword arguments. *key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly). *reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed. Use [`functools.cmp_to_key()`](functools#functools.cmp_to_key "functools.cmp_to_key") to convert an old-style *cmp* function to a *key* function. The built-in [`sorted()`](#sorted "sorted") function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). The sort algorithm uses only `<` comparisons between items. While defining an [`__lt__()`](../reference/datamodel#object.__lt__ "object.__lt__") method will suffice for sorting, [**PEP 8**](https://www.python.org/dev/peps/pep-0008) recommends that all six [rich comparisons](../reference/expressions#comparisons) be implemented. This will help avoid bugs when using the same data with other ordering tools such as [`max()`](#max "max") that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the [`__gt__()`](../reference/datamodel#object.__gt__ "object.__gt__") method. For sorting examples and a brief sorting tutorial, see [Sorting HOW TO](../howto/sorting#sortinghowto). `@staticmethod` Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom: ``` class C: @staticmethod def f(arg1, arg2, ...): ... ``` The `@staticmethod` form is a function [decorator](../glossary#term-decorator) – see [Function definitions](../reference/compound_stmts#function) for details. A static method can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). Static methods in Python are similar to those found in Java or C++. Also see [`classmethod()`](#classmethod "classmethod") for a variant that is useful for creating alternate class constructors. Like all decorators, it is also possible to call `staticmethod` as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom: ``` class C: builtin_open = staticmethod(open) ``` For more information on static methods, see [The standard type hierarchy](../reference/datamodel#types). `class str(object='')` `class str(object=b'', encoding='utf-8', errors='strict')` Return a [`str`](stdtypes#str "str") version of *object*. See [`str()`](stdtypes#str "str") for details. `str` is the built-in string [class](../glossary#term-class). For general information about strings, see [Text Sequence Type — str](stdtypes#textseq). `sum(iterable, /, start=0)` Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string. For some use cases, there are good alternatives to [`sum()`](#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](math#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](itertools#itertools.chain "itertools.chain"). Changed in version 3.8: The *start* parameter can be specified as a keyword argument. `super([type[, object-or-type]])` Return a proxy object that delegates method calls to a parent or sibling class of *type*. This is useful for accessing inherited methods that have been overridden in a class. The *object-or-type* determines the [method resolution order](../glossary#term-method-resolution-order) to be searched. The search starts from the class right after the *type*. For example, if [`__mro__`](stdtypes#class.__mro__ "class.__mro__") of *object-or-type* is `D -> B -> C -> A -> object` and the value of *type* is `B`, then [`super()`](#super "super") searches `C -> A -> object`. The [`__mro__`](stdtypes#class.__mro__ "class.__mro__") attribute of the *object-or-type* lists the method resolution search order used by both [`getattr()`](#getattr "getattr") and [`super()`](#super "super"). The attribute is dynamic and can change whenever the inheritance hierarchy is updated. If the second argument is omitted, the super object returned is unbound. If the second argument is an object, `isinstance(obj, type)` must be true. If the second argument is a type, `issubclass(type2, type)` must be true (this is useful for classmethods). There are two typical use cases for *super*. In a class hierarchy with single inheritance, *super* can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of *super* in other programming languages. The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime). For both use cases, a typical superclass call looks like this: ``` class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg) ``` In addition to method lookups, [`super()`](#super "super") also works for attribute lookups. One possible use case for this is calling [descriptors](../glossary#term-descriptor) in a parent or sibling class. Note that [`super()`](#super "super") is implemented as part of the binding process for explicit dotted attribute lookups such as `super().__getitem__(name)`. It does so by implementing its own [`__getattribute__()`](../reference/datamodel#object.__getattribute__ "object.__getattribute__") method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, [`super()`](#super "super") is undefined for implicit lookups using statements or operators such as `super()[name]`. Also note that, aside from the zero argument form, [`super()`](#super "super") is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods. For practical suggestions on how to design cooperative classes using [`super()`](#super "super"), see [guide to using super()](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/). `class tuple([iterable])` Rather than being a function, [`tuple`](stdtypes#tuple "tuple") is actually an immutable sequence type, as documented in [Tuples](stdtypes#typesseq-tuple) and [Sequence Types — list, tuple, range](stdtypes#typesseq). `class type(object)` `class type(name, bases, dict, **kwds)` With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](stdtypes#instance.__class__ "instance.__class__"). The [`isinstance()`](#isinstance "isinstance") built-in function is recommended for testing the type of an object, because it takes subclasses into account. With three arguments, return a new type object. This is essentially a dynamic form of the [`class`](../reference/compound_stmts#class) statement. The *name* string is the class name and becomes the [`__name__`](stdtypes#definition.__name__ "definition.__name__") attribute. The *bases* tuple contains the base classes and becomes the [`__bases__`](stdtypes#class.__bases__ "class.__bases__") attribute; if empty, [`object`](#object "object"), the ultimate base of all classes, is added. The *dict* dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute. The following two statements create identical [`type`](#type "type") objects: ``` >>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1)) ``` See also [Type Objects](stdtypes#bltin-type-objects). Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually [`__init_subclass__()`](../reference/datamodel#object.__init_subclass__ "object.__init_subclass__")) in the same way that keywords in a class definition (besides *metaclass*) would. See also [Customizing class creation](../reference/datamodel#class-customization). Changed in version 3.6: Subclasses of [`type`](#type "type") which don’t override `type.__new__` may no longer use the one-argument form to get the type of an object. `vars([object])` Return the [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute for a module, class, instance, or any other object with a [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute. Objects such as modules and instances have an updateable [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute; however, other objects may have write restrictions on their [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attributes (for example, classes use a [`types.MappingProxyType`](types#types.MappingProxyType "types.MappingProxyType") to prevent direct dictionary updates). Without an argument, [`vars()`](#vars "vars") acts like [`locals()`](#locals "locals"). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. A [`TypeError`](exceptions#TypeError "TypeError") exception is raised if an object is specified but it doesn’t have a [`__dict__`](stdtypes#object.__dict__ "object.__dict__") attribute (for example, if its class defines the [`__slots__`](../reference/datamodel#object.__slots__ "object.__slots__") attribute). `zip(*iterables)` Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the *i*-th tuple contains the *i*-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to: ``` def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result) ``` The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using `zip(*[iter(s)]*n)`. This repeats the *same* iterator `n` times so that each output tuple has the result of `n` calls to the iterator. This has the effect of dividing the input into n-length chunks. [`zip()`](#zip "zip") should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use [`itertools.zip_longest()`](itertools#itertools.zip_longest "itertools.zip_longest") instead. [`zip()`](#zip "zip") in conjunction with the `*` operator can be used to unzip a list: ``` >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True ``` `__import__(name, globals=None, locals=None, fromlist=(), level=0)` Note This is an advanced function that is not needed in everyday Python programming, unlike [`importlib.import_module()`](importlib#importlib.import_module "importlib.import_module"). This function is invoked by the [`import`](../reference/simple_stmts#import) statement. It can be replaced (by importing the [`builtins`](builtins#module-builtins "builtins: The module that provides the built-in namespace.") module and assigning to `builtins.__import__`) in order to change semantics of the `import` statement, but doing so is **strongly** discouraged as it is usually simpler to use import hooks (see [**PEP 302**](https://www.python.org/dev/peps/pep-0302)) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of [`__import__()`](#__import__ "__import__") is also discouraged in favor of [`importlib.import_module()`](importlib#importlib.import_module "importlib.import_module"). The function imports the module *name*, potentially using the given *globals* and *locals* to determine how to interpret the name in a package context. The *fromlist* gives the names of objects or submodules that should be imported from the module given by *name*. The standard implementation does not use its *locals* argument at all, and uses its *globals* only to determine the package context of the [`import`](../reference/simple_stmts#import) statement. *level* specifies whether to use absolute or relative imports. `0` (the default) means only perform absolute imports. Positive values for *level* indicate the number of parent directories to search relative to the directory of the module calling [`__import__()`](#__import__ "__import__") (see [**PEP 328**](https://www.python.org/dev/peps/pep-0328) for the details). When the *name* variable is of the form `package.module`, normally, the top-level package (the name up till the first dot) is returned, *not* the module named by *name*. However, when a non-empty *fromlist* argument is given, the module named by *name* is returned. For example, the statement `import spam` results in bytecode resembling the following code: ``` spam = __import__('spam', globals(), locals(), [], 0) ``` The statement `import spam.ham` results in this call: ``` spam = __import__('spam.ham', globals(), locals(), [], 0) ``` Note how [`__import__()`](#__import__ "__import__") returns the toplevel module here because this is the object that is bound to a name by the [`import`](../reference/simple_stmts#import) statement. On the other hand, the statement `from spam.ham import eggs, sausage as saus` results in ``` _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage ``` Here, the `spam.ham` module is returned from [`__import__()`](#__import__ "__import__"). From this object, the names to import are retrieved and assigned to their respective names. If you simply want to import a module (potentially within a package) by name, use [`importlib.import_module()`](importlib#importlib.import_module "importlib.import_module"). Changed in version 3.3: Negative values for *level* are no longer supported (which also changes the default value to 0). Changed in version 3.9: When the command line options [`-E`](../using/cmdline#cmdoption-e) or [`-I`](../using/cmdline#id2) are being used, the environment variable [`PYTHONCASEOK`](../using/cmdline#envvar-PYTHONCASEOK) is now ignored. #### Footnotes `1` Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.
programming_docs