sample_id,family_id,text,language,profile,version_context,source_refs dp-pt-click-8.5-documentation.md-0,dp-Click-documentation.md,"# Help Pages ```{currentmodule} click ``` Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not. ## Help Texts Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided. Simple example: ```{eval-rst} .. click:example:: @click.command() @click.argument('name', help='The name to print.') @click.option('--count', default=1, help='number of greetings') def hello(name: str, count: int): """"""This script prints hello and a name one or more times."""""" for x in range(count): if name: click.echo(f""Hello {name}!"") else: click.echo(""Hello!"") .. click:run:: invoke(hello, args=['--help']) ``` ## Command Short Help For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`: ```{eval-rst} .. click:example:: import click @click.group() def cli(): """"""A simple command line tool."""""" @cli.command('init', short_help='init the repo') def init(): """"""Initializes the repository."""""" .. click:run:: invoke(cli, args=['--help']) ``` ## Group Help Page The group help prints sub commands, options, epilog help, and arguments, and prints them together. ```{eval-rst} .. click:example:: import click @click.group( help=""Example Click app with subcommands, options, and positional arguments."", epilog=(""Examples:\n\n\b\n python hello.py greet Alice --count 2\n""), ) def cli() -> None: """"""Run the example CLI."""""" @cli.command() @click.argument(""name"") @click.option( ""--count"", default=1, show_default=True, type=click.IntRange(1, None), help=""Number of greetings to print."", ) @click.option( ""--greeting"", default=""Hello"", show_default=True, help=""Greeting prefix to use."", ) def greet(name: str, count: int, greeting: str) -> None: """"""Greet NAME one or more times."""""" for _ in range(count): click.echo(f""{greeting} {name}!"") .. click:run:: invoke(cli, args=['--help']) ``` ## Command Epilog Help The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources. ```{eval-rst} .. click:example:: import click @click.command( epilog='See https://example.com for more details', ) def init(): """"""Initializes the repository."""""" .. click:run:: invoke(init, args=['--help']) ``` (documenting-arguments)= ## Documenting Arguments {class}`click.argument` accepts an optional `help` parameter that is shown in the `Positional arguments` section of the help page. You can still document arguments in the command docstring, especially when you want to describe them in the main help text by name. A brief example: ```{eval-rst} .. click:example:: @click.command() @click.argument('filename', help='The file to print.') def touch(filename): """"""Print FILENAME."""""" click.echo(filename) .. click:run:: invoke(touch, args=['--help']) ``` Or more explicitly in the docstring: ```{eval-rst} .. click:example:: @click.command() @click.argument('filename') def touch(filename): """"""Print FILENAME. FILENAME is the name of the file to check. """""" click.echo(filename) .. click:run:: invoke(touch, args=['--help']) ``` ",en,software_docs,Click 8.5.0,"[{""license"": ""BSD-3-Clause"", ""locator"": ""click-8.5.0/docs/documentation.md#codepoints:0:3805"", ""revision"": ""8.5.0+sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34"", ""source_id"": ""click-8.5:documentation.md"", ""uri"": ""https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz""}]" dp-pt-click-8.5-documentation.md-1,dp-Click-documentation.md,"## Showing Defaults To control the appearance of defaults pass `show_default`. ```{eval-rst} .. click:example:: @click.command() @click.option('--n', default=1, show_default=False, help='number of dots') def dots(n): click.echo('.' * n) .. click:run:: invoke(dots, args=['--help']) ``` For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true. ```{eval-rst} .. click:example:: @click.command() @click.option('--n', default=1, show_default=True) @click.option(""--gr"", is_flag=True, show_default=True, default=False, help=""Greet the world."") @click.option(""--br"", is_flag=True, show_default=True, default=True, help=""Add a thematic break"") def dots(n, gr, br): if gr: click.echo('Hello world!') click.echo('.' * n) if br: click.echo('-' * n) .. click:run:: invoke(dots, args=['--help']) ``` ## Showing Environment Variables To control the appearance of environment variables pass `show_envvar`. ```{eval-rst} .. click:example:: @click.command() @click.option('--username', envvar='USERNAME', show_envvar=True) def greet(username): click.echo(f'Hello {username}!') .. click:run:: invoke(greet, args=['--help']) ``` ## Click's Wrapping Behavior Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal to a maximum of 80 characters by default, but this can be modified with {attr}`~Context.max_content_width`. In the example notice how the second grouping of three lines is rewrapped into a single paragraph. ```{eval-rst} .. click:example:: import click @click.command() def cli(): """""" This is a very long paragraph and as you can see wrapped very early in the source text but will be rewrapped to the terminal width in the final output. This is a paragraph that is compacted. """""" .. click:run:: invoke(cli, args=['--help']) ``` ## Escaping Click's Wrapping Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text. Example: ```{eval-rst} .. click:example:: import click @click.command() def cli(): """"""First paragraph. \b This is a paragraph without rewrapping. And this is a paragraph that will be rewrapped again. """""" .. click:run:: invoke(cli, args=['--help']) ``` To change the rendering maximum width, pass `max_content_width` when calling the command. ```bash cli(max_content_width=120) ``` ## Truncating Help Texts Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker. Example: ```{eval-rst} .. click:example:: import click @click.command() def cli(): """"""First paragraph. \f Words to not be included. """""" .. click:run:: invoke(cli, args=['--help']) ``` (doc-meta-variables)= ",en,software_docs,Click 8.5.0,"[{""license"": ""BSD-3-Clause"", ""locator"": ""click-8.5.0/docs/documentation.md#codepoints:3805:7110"", ""revision"": ""8.5.0+sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34"", ""source_id"": ""click-8.5:documentation.md"", ""uri"": ""https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz""}]" dp-pt-click-8.5-documentation.md-2,dp-Click-documentation.md,"## Placeholder / Meta Variable The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs. ```{eval-rst} .. click:example:: # This controls entry on the usage line. @click.command(options_metavar='[[options]]') @click.option('--count', default=1, help='number of greetings', metavar='') @click.argument('name', metavar='') def hello(name: str, count: int) -> None: """"""This script prints 'hello ' a total of times."""""" for x in range(count): click.echo(f""Hello {name}!"") # Example usage: .. click:run:: invoke(hello, args=['--help']) ``` ```{admonition} Optional elements are bracketed :class: note The usage line follows a consistent convention: an element is optional when it is enclosed in square brackets and required when it appears outside them. A required argument appears as `FOO` and an optional one as `[FOO]`, with a variadic argument adding a trailing `...` (so `[FOO]...`). A single pair of brackets can group several tokens, so a chained group renders an extra command and its arguments as one optional, repeatable unit: `[COMMAND2 [ARGS]...]...`. A {class}`Group` that can run without naming a subcommand (`invoke_without_command=True`) also brackets the leading command, showing `[COMMAND]` instead of `COMMAND`. The `[OPTIONS]` placeholder is always bracketed, since adding options is itself optional. This mirrors the conventional utility-argument syntax for optional arguments and operands ([POSIX §12.1](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html), [`man-pages(7)`](https://man7.org/linux/man-pages/man7/man-pages.7.html)), where a bracketed expression followed by `...` denotes zero or more occurrences. A subcommand name is a positional operand, so Click brackets it under the same rule. ``` ## Help Parameter Customization Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click resolves conflicts automatically: an option reusing one of the help option names takes it over, and the default help parameter is dropped once all its names are taken. A parameter merely named `help`, like `click.argument(""help"")`, does not disable it: both keep working independently. This example changes the default parameters to `-h` and `--help` instead of just `--help`: ```{eval-rst} .. click:example:: import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) def cli(): pass .. click:run:: invoke(cli, ['-h']) ``` ",en,software_docs,Click 8.5.0,"[{""license"": ""BSD-3-Clause"", ""locator"": ""click-8.5.0/docs/documentation.md#codepoints:7110:10035"", ""revision"": ""8.5.0+sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34"", ""source_id"": ""click-8.5:documentation.md"", ""uri"": ""https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz""}]" dp-pt-flask-3.1-deploying-eventlet.rst-0,dp-Flask-deploying-eventlet.rst,":orphan: eventlet ======== `Eventlet is no longer maintained.`__ Use :doc:`/deploying/gevent` instead. __ https://eventlet.readthedocs.io ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/deploying/eventlet.rst#codepoints:0:141"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:deploying/eventlet.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-deploying-nginx.rst-0,dp-Flask-deploying-nginx.rst,"nginx ===== `nginx`_ is a fast, production level HTTP server. When serving your application with one of the WSGI servers listed in :doc:`index`, it is often good or necessary to put a dedicated HTTP server in front of it. This ""reverse proxy"" can handle incoming requests, TLS, and other security and performance concerns better than the WSGI server. Nginx can be installed using your system package manager, or a pre-built executable for Windows. Installing and running Nginx itself is outside the scope of this doc. This page outlines the basics of configuring Nginx to proxy your application. Be sure to read its documentation to understand what features are available. .. _nginx: https://nginx.org/ Domain Name ----------- Acquiring and configuring a domain name is outside the scope of this doc. In general, you will buy a domain name from a registrar, pay for server space with a hosting provider, and then point your registrar at the hosting provider's name servers. To simulate this, you can also edit your ``hosts`` file, located at ``/etc/hosts`` on Linux. Add a line that associates a name with the local IP. Modern Linux systems may be configured to treat any domain name that ends with ``.localhost`` like this without adding it to the ``hosts`` file. .. code-block:: python :caption: ``/etc/hosts`` 127.0.0.1 hello.localhost Configuration ------------- The nginx configuration is located at ``/etc/nginx/nginx.conf`` on Linux. It may be different depending on your operating system. Check the docs and look for ``nginx.conf``. Remove or comment out any existing ``server`` section. Add a ``server`` section and use the ``proxy_pass`` directive to point to the address the WSGI server is listening on. We'll assume the WSGI server is listening locally at ``http://127.0.0.1:8000``. .. code-block:: nginx :caption: ``/etc/nginx.conf`` server { listen 80; server_name _; location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Prefix /; } } Then :doc:`proxy_fix` so that your application uses these headers. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/deploying/nginx.rst#codepoints:0:2316"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:deploying/nginx.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-deploying-proxy_fix.rst-0,dp-Flask-deploying-proxy_fix.rst,"Tell Flask it is Behind a Proxy =============================== When using a reverse proxy, or many Python hosting platforms, the proxy will intercept and forward all external requests to the local WSGI server. From the WSGI server and Flask application's perspectives, requests are now coming from the HTTP server to the local address, rather than from the remote address to the external server address. HTTP servers should set ``X-Forwarded-`` headers to pass on the real values to the application. The application can then be told to trust and use those values by wrapping it with the :doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug. This middleware should only be used if the application is actually behind a proxy, and should be configured with the number of proxies that are chained in front of it. Not all proxies set all the headers. Since incoming headers can be faked, you must set how many proxies are setting each header so the middleware knows what to trust. .. code-block:: python from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix( app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 ) Remember, only apply this middleware if you are behind a proxy, and set the correct number of proxies that set each header. It can be a security issue if you get this configuration wrong. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/deploying/proxy_fix.rst#codepoints:0:1365"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:deploying/proxy_fix.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-design.rst-0,dp-Flask-design.rst,"Design Decisions in Flask ========================= If you are curious why Flask does certain things the way it does and not differently, this section is for you. This should give you an idea about some of the design decisions that may appear arbitrary and surprising at first, especially in direct comparison with other frameworks. The Explicit Application Object ------------------------------- A Python web application based on WSGI has to have one central callable object that implements the actual application. In Flask this is an instance of the :class:`~flask.Flask` class. Each Flask application has to create an instance of this class itself and pass it the name of the module, but why can't Flask do that itself? Without such an explicit application object the following code:: from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello World!' Would look like this instead:: from hypothetical_flask import route @route('/') def index(): return 'Hello World!' There are three major reasons for this. The most important one is that implicit application objects require that there may only be one instance at the time. There are ways to fake multiple applications with a single application object, like maintaining a stack of applications, but this causes some problems I won't outline here in detail. Now the question is: when does a microframework need more than one application at the same time? A good example for this is unit testing. When you want to test something it can be very helpful to create a minimal application to test specific behavior. When the application object is deleted everything it allocated will be freed again. Another thing that becomes possible when you have an explicit object lying around in your code is that you can subclass the base class (:class:`~flask.Flask`) to alter specific behavior. This would not be possible without hacks if the object were created ahead of time for you based on a class that is not exposed to you. But there is another very important reason why Flask depends on an explicit instantiation of that class: the package name. Whenever you create a Flask instance you usually pass it `__name__` as package name. Flask depends on that information to properly load resources relative to your module. With Python's outstanding support for reflection it can then access the package to figure out where the templates and static files are stored (see :meth:`~flask.Flask.open_resource`). Now obviously there are frameworks around that do not need any configuration and will still be able to load templates relative to your application module. But they have to use the current working directory for that, which is a very unreliable way to determine where the application is. The current working directory is process-wide and if you are running multiple applications in one process (which could happen in a webserver without you knowing) the paths will be off. Worse: many webservers do not set the working directory to the directory of your application but to the document root which does not have to be the same folder. The third reason is ""explicit is better than implicit"". That object is your WSGI application, you don't have to remember anything else. If you want to apply a WSGI middleware, just wrap it and you're done (though there are better ways to do that so that you do not lose the reference to the application object :meth:`~flask.Flask.wsgi_app`). Furthermore this design makes it possible to use a factory function to create the application which is very helpful for unit testing and similar things (:doc:`/patterns/appfactories`). ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/design.rst#codepoints:0:3713"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:design.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-design.rst-1,dp-Flask-design.rst,"The Routing System ------------------ Flask uses the Werkzeug routing system which was designed to automatically order routes by complexity. This means that you can declare routes in arbitrary order and they will still work as expected. This is a requirement if you want to properly implement decorator based routing since decorators could be fired in undefined order when the application is split into multiple modules. Another design decision with the Werkzeug routing system is that routes in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far with that in that it will automatically redirect to a canonical URL if a route is ambiguous. One Template Engine ------------------- Flask decides on one template engine: Jinja. Why doesn't Flask have a pluggable template engine interface? You can obviously use a different template engine, but Flask will still configure Jinja for you. While that limitation that Jinja is *always* configured will probably go away, the decision to bundle one template engine and use that will not. Template engines are like programming languages and each of those engines has a certain understanding about how things work. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. But that's about where similarities end. Jinja for example has an extensive filter system, a certain way to do template inheritance, support for reusable blocks (macros) that can be used from inside templates and also from Python code, supports iterative template rendering, configurable syntax and more. On the other hand an engine like Genshi is based on XML stream evaluation, template inheritance by taking the availability of XPath into account and more. Mako on the other hand treats templates similar to Python modules. When it comes to connecting a template engine with an application or framework there is more than just rendering templates. For instance, Flask uses Jinja's extensive autoescaping support. Also it provides ways to access macros from Jinja templates. A template abstraction layer that would not take the unique features of the template engines away is a science on its own and a too large undertaking for a microframework like Flask. Furthermore extensions can then easily depend on one template language being present. You can easily use your own templating language, but an extension could still depend on Jinja itself. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/design.rst#codepoints:3713:6201"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:design.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-design.rst-2,dp-Flask-design.rst,"What does ""micro"" mean? ----------------------- “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The ""micro"" in microframework means Flask aims to keep the core simple but extensible. Flask won't make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don't. By default, Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be ""micro"", but it's ready for production use on a variety of needs. Why does Flask call itself a microframework and yet it depends on two libraries (namely Werkzeug and Jinja). Why shouldn't it? If we look over to the Ruby side of web development there we have a protocol very similar to WSGI. Just that it's called Rack there, but besides that it looks very much like a WSGI rendition for Ruby. But nearly all applications in Ruby land do not work with Rack directly, but on top of a library with the same name. This Rack library has two equivalents in Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but from my understanding it's sort of deprecated in favour of WebOb. The development of WebOb and Werkzeug started side by side with similar ideas in mind: be a good implementation of WSGI for other applications to take advantage. Flask is a framework that takes advantage of the work already done by Werkzeug to properly interface WSGI (which can be a complex task at times). Thanks to recent developments in the Python package infrastructure, packages with dependencies are no longer an issue and there are very few reasons against having libraries that depend on others. Thread Locals ------------- Flask uses thread local objects (context local objects in fact, they support greenlet contexts as well) for request, session and an extra object you can put your own things on (:data:`~flask.g`). Why is that and isn't that a bad idea? Yes it is usually not such a bright idea to use thread locals. They cause troubles for servers that are not based on the concept of threads and make large applications harder to maintain. However Flask is just not designed for large applications or asynchronous servers. Flask wants to make it quick and easy to write a traditional web application. Async/await and ASGI support ---------------------------- Flask supports ``async`` coroutines for view functions by executing the coroutine on a separate thread instead of using an event loop on the main thread as an async-first (ASGI) framework would. This is necessary for Flask to remain backwards compatible with extensions and code built before ``async`` was introduced into Python. This compromise introduces a performance cost compared with the ASGI frameworks, due to the overhead of the threads. Due to how tied to WSGI Flask's code is, it's not clear if it's possible to make the ``Flask`` class support ASGI and WSGI at the same time. Work is currently being done in Werkzeug to work with ASGI, which may eventually enable support in Flask as well. See :doc:`/async-await` for more discussion. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/design.rst#codepoints:6201:9843"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:design.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-design.rst-3,dp-Flask-design.rst,"What Flask is, What Flask is Not -------------------------------- Flask will never have a database layer. It will not have a form library or anything else in that direction. Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja to handle templating. It also binds to a few common standard library packages such as logging. Everything else is up for extensions. Why is this the case? Because people have different preferences and requirements and Flask could not meet those if it would force any of this into the core. The majority of web applications will need a template engine in some sort. However not every application needs a SQL database. As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in SQLAlchemy or another database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface. The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/design.rst#codepoints:9843:11062"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:design.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-caching.rst-0,dp-Flask-patterns-caching.rst,"Caching ======= When your application runs slow, throw some caches in. Well, at least it's the easiest way to speed up things. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time. Flask itself does not provide caching for you, but `Flask-Caching`_, an extension for Flask does. Flask-Caching supports various backends, and it is even possible to develop your own caching backend. .. _Flask-Caching: https://flask-caching.readthedocs.io/en/latest/ ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/caching.rst#codepoints:0:653"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/caching.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-celery.rst-0,dp-Flask-patterns-celery.rst,"Background Tasks with Celery ============================ If your application has a long running task, such as processing some uploaded data or sending email, you don't want to wait for it to finish during a request. Instead, use a task queue to send the necessary data to another process that will run the task in the background while the request returns immediately. `Celery`_ is a powerful task queue that can be used for simple background tasks as well as complex multi-stage programs and schedules. This guide will show you how to configure Celery using Flask. Read Celery's `First Steps with Celery`_ guide to learn how to use Celery itself. .. _Celery: https://celery.readthedocs.io .. _First Steps with Celery: https://celery.readthedocs.io/en/latest/getting-started/first-steps-with-celery.html The Flask repository contains `an example `_ based on the information on this page, which also shows how to use JavaScript to submit tasks and poll for progress and results. Install ------- Install Celery from PyPI, for example using pip: .. code-block:: text $ pip install celery Integrate Celery with Flask --------------------------- You can use Celery without any integration with Flask, but it's convenient to configure it through Flask's config, and to let tasks access the Flask application. Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration and registers tasks. While creating a Flask app, use the following code to create and configure a Celery app as well. .. code-block:: python from celery import Celery, Task def celery_init_app(app: Flask) -> Celery: class FlaskTask(Task): def __call__(self, *args: object, **kwargs: object) -> object: with app.app_context(): return self.run(*args, **kwargs) celery_app = Celery(app.name, task_cls=FlaskTask) celery_app.config_from_object(app.config[""CELERY""]) celery_app.set_default() app.extensions[""celery""] = celery_app return celery_app This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from the ``CELERY`` key in the Flask configuration. The Celery app is set as the default, so that it is seen during each request. The ``Task`` subclass automatically runs task functions with a Flask app context active, so that services like your database connections are available. .. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html Here's a basic ``example.py`` that configures Celery to use Redis for communication. We enable a result backend, but ignore results by default. This allows us to store results only for tasks where we care about the result. .. code-block:: python from flask import Flask app = Flask(__name__) app.config.from_mapping( CELERY=dict( broker_url=""redis://localhost"", result_backend=""redis://localhost"", task_ignore_result=True, ), ) celery_app = celery_init_app(app) Point the ``celery worker`` command at this and it will find the ``celery_app`` object. .. code-block:: text $ celery -A example worker --loglevel INFO You can also run the ``celery beat`` command to run tasks on a schedule. See Celery's docs for more information about defining schedules. .. code-block:: text $ celery -A example beat --loglevel INFO ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/celery.rst#codepoints:0:3479"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/celery.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-celery.rst-1,dp-Flask-patterns-celery.rst,"Application Factory ------------------- When using the Flask application factory pattern, call the ``celery_init_app`` function inside the factory. It sets ``app.extensions[""celery""]`` to the Celery app object, which can be used to get the Celery app from the Flask app returned by the factory. .. code-block:: python def create_app() -> Flask: app = Flask(__name__) app.config.from_mapping( CELERY=dict( broker_url=""redis://localhost"", result_backend=""redis://localhost"", task_ignore_result=True, ), ) app.config.from_prefixed_env() celery_init_app(app) return app To use ``celery`` commands, Celery needs an app object, but that's no longer directly available. Create a ``make_celery.py`` file that calls the Flask app factory and gets the Celery app from the returned Flask app. .. code-block:: python from example import create_app flask_app = create_app() celery_app = flask_app.extensions[""celery""] Point the ``celery`` command to this file. .. code-block:: text $ celery -A make_celery worker --loglevel INFO $ celery -A make_celery beat --loglevel INFO Defining Tasks -------------- Using ``@celery_app.task`` to decorate task functions requires access to the ``celery_app`` object, which won't be available when using the factory pattern. It also means that the decorated tasks are tied to the specific Flask and Celery app instances, which could be an issue during testing if you change configuration for a test. Instead, use Celery's ``@shared_task`` decorator. This creates task objects that will access whatever the ""current app"" is, which is a similar concept to Flask's blueprints and app context. This is why we called ``celery_app.set_default()`` above. Here's an example task that adds two numbers together and returns the result. .. code-block:: python from celery import shared_task @shared_task(ignore_result=False) def add_together(a: int, b: int) -> int: return a + b Earlier, we configured Celery to ignore task results by default. Since we want to know the return value of this task, we set ``ignore_result=False``. On the other hand, a task that didn't need a result, such as sending an email, wouldn't set this. Calling Tasks ------------- The decorated function becomes a task object with methods to call it in the background. The simplest way is to use the ``delay(*args, **kwargs)`` method. See Celery's docs for more methods. A Celery worker must be running to run the task. Starting a worker is shown in the previous sections. .. code-block:: python from flask import request @app.post(""/add"") def start_add() -> dict[str, object]: a = request.form.get(""a"", type=int) b = request.form.get(""b"", type=int) result = add_together.delay(a, b) return {""result_id"": result.id} The route doesn't get the task's result immediately. That would defeat the purpose by blocking the response. Instead, we return the running task's result id, which we can use later to get the result. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/celery.rst#codepoints:3479:6618"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/celery.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-celery.rst-2,dp-Flask-patterns-celery.rst,"Getting Results --------------- To fetch the result of the task we started above, we'll add another route that takes the result id we returned before. We return whether the task is finished (ready), whether it finished successfully, and what the return value (or error) was if it is finished. .. code-block:: python from celery.result import AsyncResult @app.get(""/result/"") def task_result(id: str) -> dict[str, object]: result = AsyncResult(id) return { ""ready"": result.ready(), ""successful"": result.successful(), ""value"": result.result if result.ready() else None, } Now you can start the task using the first route, then poll for the result using the second route. This keeps the Flask request workers from being blocked waiting for tasks to finish. The Flask repository contains `an example `_ using JavaScript to submit tasks and poll for progress and results. Passing Data to Tasks --------------------- The ""add"" task above took two integers as arguments. To pass arguments to tasks, Celery has to serialize them to a format that it can pass to other processes. Therefore, passing complex objects is not recommended. For example, it would be impossible to pass a SQLAlchemy model object, since that object is probably not serializable and is tied to the session that queried it. Pass the minimal amount of data necessary to fetch or recreate any complex data within the task. Consider a task that will run when the logged in user asks for an archive of their data. The Flask request knows the logged in user, and has the user object queried from the database. It got that by querying the database for a given id, so the task can do the same thing. Pass the user's id rather than the user object. .. code-block:: python @shared_task def generate_user_archive(user_id: str) -> None: user = db.session.get(User, user_id) ... generate_user_archive.delay(current_user.id) ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/celery.rst#codepoints:6618:8670"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/celery.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-sqlalchemy.rst-0,dp-Flask-patterns-sqlalchemy.rst,"SQLAlchemy in Flask =================== Many people prefer `SQLAlchemy`_ for database access. In this case it's encouraged to use a package instead of a module for your flask application and drop the models into a separate module (:doc:`packages`). While that is not necessary, it makes a lot of sense. There are four very common ways to use SQLAlchemy. I will outline each of them here: Flask-SQLAlchemy Extension -------------------------- Because SQLAlchemy is a common database abstraction layer and object relational mapper that requires a little bit of configuration effort, there is a Flask extension that handles that for you. This is recommended if you want to get started quickly. You can download `Flask-SQLAlchemy`_ from `PyPI `_. .. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/ Declarative ----------- The declarative extension in SQLAlchemy is the most recent method of using SQLAlchemy. It allows you to define tables and models in one go, similar to how Django works. In addition to the following text I recommend the official documentation on the `declarative`_ extension. Here's the example :file:`database.py` module for your application:: from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base engine = create_engine('sqlite:////tmp/test.db') db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import yourapplication.models Base.metadata.create_all(bind=engine) To define your models, just subclass the `Base` class that was created by the code above. If you are wondering why we don't have to care about threads here (like we did in the SQLite3 example above with the :data:`~flask.g` object): that's because SQLAlchemy does that for us already with the :class:`~sqlalchemy.orm.scoped_session`. To use SQLAlchemy in a declarative way with your application, you just have to put the following code into your application module. Flask will automatically remove database sessions at the end of the request or when the application shuts down:: from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() Here is an example model (put this into :file:`models.py`, e.g.):: from sqlalchemy import Column, Integer, String from yourapplication.database import Base class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True) email = Column(String(120), unique=True) def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return f'' To create the database you can use the `init_db` function: >>> from yourapplication.database import init_db >>> init_db() You can insert entries into the database like this: >>> from yourapplication.database import db_session >>> from yourapplication.models import User >>> u = User('admin', 'admin@localhost') >>> db_session.add(u) >>> db_session.commit() Querying is simple as well: >>> User.query.all() [] >>> User.query.filter(User.name == 'admin').first() .. _SQLAlchemy: https://www.sqlalchemy.org/ .. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/sqlalchemy.rst#codepoints:0:3892"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/sqlalchemy.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-patterns-sqlalchemy.rst-1,dp-Flask-patterns-sqlalchemy.rst,"Manual Object Relational Mapping -------------------------------- Manual object relational mapping has a few upsides and a few downsides versus the declarative approach from above. The main difference is that you define tables and classes separately and map them together. It's more flexible but a little more to type. In general it works like the declarative approach, so make sure to also split up your application into multiple modules in a package. Here is an example :file:`database.py` module for your application:: from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) def init_db(): metadata.create_all(bind=engine) As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module:: from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() Here is an example table and model (put this into :file:`models.py`):: from sqlalchemy import Table, Column, Integer, String from sqlalchemy.orm import mapper from yourapplication.database import metadata, db_session class User(object): query = db_session.query_property() def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return f'' users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(50), unique=True), Column('email', String(120), unique=True) ) mapper(User, users) Querying and inserting works exactly the same as in the example above. SQL Abstraction Layer --------------------- If you just want to use the database system (and SQL) abstraction layer you basically only need the engine:: from sqlalchemy import create_engine, MetaData, Table engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples above, or automatically load them:: from sqlalchemy import Table users = Table('users', metadata, autoload=True) To insert data you can use the `insert` method. We have to get a connection first so that we can use a transaction: >>> con = engine.connect() >>> con.execute(users.insert(), name='admin', email='admin@localhost') SQLAlchemy will automatically commit for us. To query your database, you use the engine directly or use a connection: >>> users.select(users.c.id == 1).execute().first() (1, 'admin', 'admin@localhost') These results are also dict-like tuples: >>> r = users.select(users.c.id == 1).execute().first() >>> r['name'] 'admin' You can also pass strings of SQL statements to the :meth:`~sqlalchemy.engine.base.Connection.execute` method: >>> engine.execute('select * from users where id = :1', [1]).first() (1, 'admin', 'admin@localhost') For more information about SQLAlchemy, head over to the `website `_. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/patterns/sqlalchemy.rst#codepoints:3892:7294"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:patterns/sqlalchemy.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-0,dp-Flask-quickstart.rst,"Quickstart ========== Eager to get started? This page gives a good introduction to Flask. Follow :doc:`installation` to set up a project and install Flask first. A Minimal Application --------------------- A minimal Flask application looks something like this: .. code-block:: python from flask import Flask app = Flask(__name__) @app.route(""/"") def hello_world(): return ""

Hello, World!

"" So what did that code do? 1. First we imported the :class:`~flask.Flask` class. An instance of this class will be our WSGI application. 2. Next we create an instance of this class. The first argument is the name of the application's module or package. ``__name__`` is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files. 3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL should trigger our function. 4. The function returns the message we want to display in the user's browser. The default content type is HTML, so HTML in the string will be rendered by the browser. Save it as :file:`hello.py` or something similar. Make sure to not call your application :file:`flask.py` because this would conflict with Flask itself. To run the application, use the ``flask`` command or ``python -m flask``. You need to tell the Flask where your application is with the ``--app`` option. .. code-block:: text $ flask --app hello run * Serving Flask app 'hello' * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) .. admonition:: Application Discovery Behavior As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you don't have to use ``--app``. See :doc:`/cli` for more details. This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see :doc:`deploying/index`. Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting. If another program is already using port 5000, you'll see ``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the server tries to start. See :ref:`address-already-in-use` for how to handle that. .. _public-server: .. admonition:: Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding ``--host=0.0.0.0`` to the command line:: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:0:2910"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-1,dp-Flask-quickstart.rst,"Debug Mode ---------- The ``flask run`` command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request. .. image:: _static/debugger.png :align: center :class: screenshot :alt: The interactive debugger in action. .. warning:: The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment. To enable debug mode, use the ``--debug`` option. .. code-block:: text $ flask --app hello run --debug * Serving Flask app 'hello' * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: nnn-nnn-nnn See also: - :doc:`/server` and :doc:`/cli` for information about running in debug mode. - :doc:`/debugging` for information about using the built-in debugger and other debuggers. - :doc:`/logging` and :doc:`/errorhandling` to log errors and display nice error pages. HTML Escaping ------------- When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically. :func:`~markupsafe.escape`, shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you're using untrusted data. .. code-block:: python from flask import request from markupsafe import escape @app.route(""/hello"") def hello(): name = request.args.get(""name"", ""Flask"") return f""Hello, {escape(name)}!"" If a user submits ``/hello?name=``, escaping causes it to be rendered as text, rather than running the script in the user's browser. Routing ------- Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. :: @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' You can do more! You can make parts of the URL dynamic and attach multiple rules to a function. Variable Rules `````````````` You can add variable sections to a URL by marking sections with ````. Your function then receives the ```` as a keyword argument. Optionally, you can use a converter to specify the type of the argument like ````. :: from markupsafe import escape @app.route('/user/') def show_user_profile(username): # show the user profile for that user return f'User {escape(username)}' @app.route('/post/') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {escape(subpath)}' Converter types: ========== ========================================== ``string`` (default) accepts any text without a slash ``int`` accepts positive integers ``float`` accepts positive floating point values ``path`` like ``string`` but also accepts slashes ``uuid`` accepts UUID strings ========== ========================================== ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:2910:6675"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-2,dp-Flask-quickstart.rst,"Unique URLs / Redirection Behavior `````````````````````````````````` The following two rules differ in their use of a trailing slash. :: @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' The canonical URL for the ``projects`` endpoint has a trailing slash. It's similar to a folder in a file system. If you access the URL without a trailing slash (``/projects``), Flask redirects you to the canonical URL with the trailing slash (``/projects/``). The canonical URL for the ``about`` endpoint does not have a trailing slash. It's similar to the pathname of a file. Accessing the URL with a trailing slash (``/about/``) produces a 404 ""Not Found"" error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice. .. _url-building: URL Building ```````````` To build a URL to a specific function, use the :func:`~flask.url_for` function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters. Why would you want to build URLs using the URL reversing function :func:`~flask.url_for` instead of hard-coding them into your templates? 1. Reversing is often more descriptive than hard-coding the URLs. 2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs. 3. URL building handles escaping of special characters transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly handles that for you. For example, here we use the :meth:`~flask.Flask.test_request_context` method to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context` tells Flask to behave as though it's handling a request even while we use a Python shell. See :ref:`context-locals`. .. code-block:: python from flask import url_for @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/') def profile(username): return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) .. code-block:: text / /login /login?next=/ /user/John%20Doe ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:6675:9395"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-3,dp-Flask-quickstart.rst,"HTTP Methods ```````````` Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to ``GET`` requests. You can use the ``methods`` argument of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods. :: from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() The example above keeps all methods for the route within one function, which can be useful if each part uses some common data. You can also separate views for different methods into different functions. Flask provides a shortcut for decorating such routes with :meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each common HTTP method. .. code-block:: python @app.get('/login') def login_get(): return show_the_login_form() @app.post('/login') def login_post(): return do_the_login() If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise, ``OPTIONS`` is automatically implemented for you. .. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt Static Files ------------ Dynamic web applications also need static files. That's usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called :file:`static` in your package or next to your module and it will be available at ``/static`` on the application. To generate URLs for static files, use the special ``'static'`` endpoint name:: url_for('static', filename='style.css') The file has to be stored on the filesystem as :file:`static/style.css`. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:9395:11349"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-4,dp-Flask-quickstart.rst,"Rendering Templates ------------------- Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the `Jinja `_ template engine for you automatically. Templates can be used to generate any type of text file. For web applications, you'll primarily be generating HTML pages, but you can also generate markdown, plain text for emails, and anything else. For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_. .. _MDN Web Docs: https://developer.mozilla.org/ To render a template you can use the :func:`~flask.render_template` method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here's a simple example of how to render a template:: from flask import render_template @app.route('/hello/') @app.route('/hello/') def hello(name=None): return render_template('hello.html', person=name) Flask will look for templates in the :file:`templates` folder. So if your application is a module, this folder is next to that module, if it's a package it's actually inside your package: **Case 1**: a module:: /application.py /templates /hello.html **Case 2**: a package:: /application /__init__.py /templates /hello.html For templates you can use the full power of Jinja templates. Head over to the official `Jinja Template Documentation `_ for more information. Here is an example template: .. sourcecode:: html+jinja Hello from Flask {% if person %}

Hello {{ person }}!

{% else %}

Hello, World!

{% endif %} Inside templates you also have access to the :data:`~flask.Flask.config`, :class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions. Templates are especially useful if inheritance is used. If you want to know how that works, see :doc:`patterns/templateinheritance`. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer). Automatic escaping is enabled, so if ``person`` contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the :class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the template. Head over to the Jinja 2 documentation for more examples. Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:: >>> from markupsafe import Markup >>> Markup('Hello %s!') % 'hacker' Markup('Hello <blink>hacker</blink>!') >>> Markup.escape('hacker') Markup('<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() 'Marked up » HTML' .. versionchanged:: 0.5 Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: ``.html``, ``.htm``, ``.xml``, ``.xhtml``. Templates loaded from a string will have autoescaping disabled. .. [#] Unsure what that :class:`~flask.g` object is? It's something in which you can store information for your own needs. See the documentation for :class:`flask.g` and :doc:`patterns/sqlite3`. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:11349:15092"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-5,dp-Flask-quickstart.rst,"Accessing Request Data ---------------------- For web applications it's crucial to react to the data a client sends to the server. In Flask this information is provided by the global :class:`~flask.request` object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals: .. _context-locals: Context Locals `````````````` .. admonition:: Insider Information If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it. Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand. Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking. So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the :meth:`~flask.Flask.test_request_context` context manager. In combination with the ``with`` statement it will bind a test request so that you can interact with it. Here is an example:: from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == 'POST' The other possibility is passing a whole WSGI environment to the :meth:`~flask.Flask.request_context` method:: with app.request_context(environ): assert request.method == 'POST' ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:15092:17535"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-6,dp-Flask-quickstart.rst,"The Request Object `````````````````` The request object is documented in the API section and we will not cover it here in detail (see :class:`~flask.Request`). Here is a broad overview of some of the most common operations. First of all you have to import it from the ``flask`` module:: from flask import request The current request method is available by using the :attr:`~flask.Request.method` attribute. To access form data (data transmitted in a ``POST`` or ``PUT`` request) you can use the :attr:`~flask.Request.form` attribute. Here is a full example of the two attributes mentioned above:: @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) What happens if the key does not exist in the ``form`` attribute? In that case a special :exc:`KeyError` is raised. You can catch it like a standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don't have to deal with that problem. To access parameters submitted in the URL (``?key=value``) you can use the :attr:`~flask.Request.args` attribute:: searchword = request.args.get('key', '') We recommend accessing URL parameters with `get` or by catching the :exc:`KeyError` because users might change the URL and presenting them a 400 bad request page in that case is not user friendly. For a full list of methods and attributes of the request object, head over to the :class:`~flask.Request` documentation. File Uploads ```````````` You can handle uploaded files with Flask easily. Just make sure not to forget to set the ``enctype=""multipart/form-data""`` attribute on your HTML form, otherwise the browser will not transmit your files at all. Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the :attr:`~flask.request.files` attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python :class:`file` object, but it also has a :meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:: from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ... If you want to know how the file was named on the client before it was uploaded to your application, you can access the :attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the :func:`~werkzeug.utils.secure_filename` function that Werkzeug provides for you:: from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['the_file'] file.save(f""/var/www/uploads/{secure_filename(file.filename)}"") ... For some better examples, see :doc:`patterns/fileuploads`. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:17535:21275"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-7,dp-Flask-quickstart.rst,"Cookies ``````` To access cookies you can use the :attr:`~flask.Request.cookies` attribute. To set cookies you can use the :attr:`~flask.Response.set_cookie` method of response objects. The :attr:`~flask.Request.cookies` attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the :ref:`sessions` in Flask that add some security on top of cookies for you. Reading cookies:: from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. Storing cookies:: from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the :meth:`~flask.make_response` function and then modify it. Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the :doc:`patterns/deferredcallbacks` pattern. For this also see :ref:`about-responses`. Redirects and Errors -------------------- To redirect a user to another endpoint, use the :func:`~flask.redirect` function; to abort a request early with an error code, use the :func:`~flask.abort` function:: from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed() This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works. By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the :meth:`~flask.Flask.errorhandler` decorator:: from flask import render_template @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 Note the ``404`` after the :func:`~flask.render_template` call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well. See :doc:`errorhandling` for more details. .. _about-responses: ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:21275:23928"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-8,dp-Flask-quickstart.rst,"About Responses --------------- The return value from a view function is automatically converted into a response object for you. If the return value is a string it's converted into a response object with the string as response body, a ``200 OK`` status code and a :mimetype:`text/html` mimetype. If the return value is a dict or list, :func:`jsonify` is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows: 1. If a response object of the correct type is returned it's directly returned from the view. 2. If it's a string, a response object is created with that data and the default parameters. 3. If it's an iterator or generator returning strings or bytes, it is treated as a streaming response. 4. If it's a dict or list, a response object is created using :func:`~flask.json.jsonify`. 5. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form ``(response, status)``, ``(response, headers)``, or ``(response, status, headers)``. The ``status`` value will override the status code and ``headers`` can be a list or dictionary of additional header values. 6. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view you can use the :func:`~flask.make_response` function. Imagine you have a view like this:: from flask import render_template @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 You just need to wrap the return expression with :func:`~flask.make_response` and get the response object to modify it, then return it:: from flask import make_response @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp APIs with JSON `````````````` A common response format when writing an API is JSON. It's easy to get started writing such an API with Flask. If you return a ``dict`` or ``list`` from a view, it will be converted to a JSON response. .. code-block:: python @app.route(""/me"") def me_api(): user = get_current_user() return { ""username"": user.username, ""theme"": user.theme, ""image"": url_for(""user_image"", filename=user.image), } @app.route(""/users"") def users_api(): users = get_all_users() return [user.to_json() for user in users] This is a shortcut to passing the data to the :func:`~flask.json.jsonify` function, which will serialize any supported JSON data type. That means that all the data in the dict or list must be JSON serializable. For complex types such as database models, you'll want to use a serialization library to convert the data to valid JSON types first. There are many serialization libraries and Flask API extensions maintained by the community that support more complex applications. .. _sessions: ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:23928:27082"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-9,dp-Flask-quickstart.rst,"Sessions -------- In addition to the request object there is also a second object called :class:`~flask.session` which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing. In order to use sessions you have to set a secret key. Here is how sessions work:: from flask import session # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L""F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return f'Logged in as {session[""username""]}' return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return '''

''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) .. admonition:: How to generate good secret keys A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for :attr:`Flask.secret_key` (or :data:`SECRET_KEY`):: $ python -c 'import secrets; print(secrets.token_hex())' '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers. Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this. Message Flashing ---------------- Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message. To flash a message use the :func:`~flask.flash` method, to get hold of the messages you can use :func:`~flask.get_flashed_messages` which is also available in the templates. See :doc:`patterns/flashing` for a full example. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:27082:30220"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-quickstart.rst-10,dp-Flask-quickstart.rst,"Logging ------- .. versionadded:: 0.3 Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it's obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it's okay to reply with ``400 Bad Request`` in that situation, but sometimes that won't do and the code has to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use. Here are some example log calls:: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') The attached :attr:`~flask.Flask.logger` is a standard logging :class:`~logging.Logger`, so head over to the official :mod:`logging` docs for more information. See :doc:`errorhandling`. Hooking in WSGI Middleware -------------------------- To add WSGI middleware to your Flask application, wrap the application's ``wsgi_app`` attribute. For example, to apply Werkzeug's :class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running behind Nginx: .. code-block:: python from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still points at your Flask application, not at the middleware, so you can continue to use and configure ``app`` directly. Using Flask Extensions ---------------------- Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask. For more on Flask extensions, see :doc:`extensions`. Deploying to a Web Server ------------------------- Ready to deploy your new Flask app? See :doc:`deploying/index`. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/quickstart.rst#codepoints:30220:32219"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:quickstart.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-tutorial-database.rst-0,dp-Flask-tutorial-database.rst,".. currentmodule:: flask Define and Access the Database ============================== The application will use a `SQLite`_ database to store users and posts. Python comes with built-in support for SQLite in the :mod:`sqlite3` module. SQLite is convenient because it doesn't require setting up a separate database server and is built-in to Python. However, if concurrent requests try to write to the database at the same time, they will slow down as each write happens sequentially. Small applications won't notice this. Once you become big, you may want to switch to a different database. The tutorial doesn't go into detail about SQL. If you are not familiar with it, the SQLite docs describe the `language`_. .. _SQLite: https://sqlite.org/about.html .. _language: https://sqlite.org/lang.html Connect to the Database ----------------------- The first thing to do when working with a SQLite database (and most other Python database libraries) is to create a connection to it. Any queries and operations are performed using the connection, which is closed after the work is finished. In web applications this connection is typically tied to the request. It is created at some point when handling a request, and closed before the response is sent. .. code-block:: python :caption: ``flaskr/db.py`` import sqlite3 from datetime import datetime import click from flask import current_app, g def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() :data:`g` is a special object that is unique for each request. It is used to store data that might be accessed by multiple functions during the request. The connection is stored and reused instead of creating a new connection if ``get_db`` is called a second time in the same request. :data:`current_app` is another special object that points to the Flask application handling the request. Since you used an application factory, there is no application object when writing the rest of your code. ``get_db`` will be called when the application has been created and is handling a request, so :data:`current_app` can be used. :func:`sqlite3.connect` establishes a connection to the file pointed at by the ``DATABASE`` configuration key. This file doesn't have to exist yet, and won't until you initialize the database later. :class:`sqlite3.Row` tells the connection to return rows that behave like dicts. This allows accessing the columns by name. ``close_db`` checks if a connection was created by checking if ``g.db`` was set. If the connection exists, it is closed. Further down you will tell your application about the ``close_db`` function in the application factory so that it is called after each request. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/tutorial/database.rst#codepoints:0:3011"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:tutorial/database.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-tutorial-database.rst-1,dp-Flask-tutorial-database.rst,"Create the Tables ----------------- In SQLite, data is stored in *tables* and *columns*. These need to be created before you can store and retrieve data. Flaskr will store users in the ``user`` table, and posts in the ``post`` table. Create a file with the SQL commands needed to create empty tables: .. code-block:: sql :caption: ``flaskr/schema.sql`` DROP TABLE IF EXISTS user; DROP TABLE IF EXISTS post; CREATE TABLE user ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL ); CREATE TABLE post ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, body TEXT NOT NULL, FOREIGN KEY (author_id) REFERENCES user (id) ); Add the Python functions that will run these SQL commands to the ``db.py`` file: .. code-block:: python :caption: ``flaskr/db.py`` def init_db(): db = get_db() with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8')) @click.command('init-db') def init_db_command(): """"""Clear the existing data and create new tables."""""" init_db() click.echo('Initialized the database.') sqlite3.register_converter( ""timestamp"", lambda v: datetime.fromisoformat(v.decode()) ) :meth:`open_resource() ` opens a file relative to the ``flaskr`` package, which is useful since you won't necessarily know where that location is when deploying the application later. ``get_db`` returns a database connection, which is used to execute the commands read from the file. :func:`click.command` defines a command line command called ``init-db`` that calls the ``init_db`` function and shows a success message to the user. You can read :doc:`/cli` to learn more about writing commands. The call to :func:`sqlite3.register_converter` tells Python how to interpret timestamp values in the database. We convert the value to a :class:`datetime.datetime`. Register with the Application ----------------------------- The ``close_db`` and ``init_db_command`` functions need to be registered with the application instance; otherwise, they won't be used by the application. However, since you're using a factory function, that instance isn't available when writing the functions. Instead, write a function that takes an application and does the registration. .. code-block:: python :caption: ``flaskr/db.py`` def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) :meth:`app.teardown_appcontext() ` tells Flask to call that function when cleaning up after returning the response. :meth:`app.cli.add_command() ` adds a new command that can be called with the ``flask`` command. Import and call this function from the factory. Place the new code at the end of the factory function before returning the app. .. code-block:: python :caption: ``flaskr/__init__.py`` def create_app(): app = ... # existing code omitted from . import db db.init_app(app) return app ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/tutorial/database.rst#codepoints:3011:6290"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:tutorial/database.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-flask-3.1-tutorial-database.rst-2,dp-Flask-tutorial-database.rst,"Initialize the Database File ---------------------------- Now that ``init-db`` has been registered with the app, it can be called using the ``flask`` command, similar to the ``run`` command from the previous page. .. note:: If you're still running the server from the previous page, you can either stop the server, or run this command in a new terminal. If you use a new terminal, remember to change to your project directory and activate the env as described in :doc:`/installation`. Run the ``init-db`` command: .. code-block:: none $ flask --app flaskr init-db Initialized the database. There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in your project. Continue to :doc:`views`. ",en,software_docs,Flask 3.1.3,"[{""license"": ""BSD-3-Clause"", ""locator"": ""flask-3.1.3/docs/tutorial/database.rst#codepoints:6290:7025"", ""revision"": ""3.1.3+sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb"", ""source_id"": ""flask-3.1:tutorial/database.rst"", ""uri"": ""https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz""}]" dp-pt-jinja-3.1-switching.rst-0,dp-Jinja-switching.rst,"Switching From Other Template Engines ===================================== This is a brief guide on some of the differences between Jinja syntax and other template languages. See :doc:`/templates` for a comprehensive guide to Jinja syntax and features. Django ------ If you have previously worked with Django templates, you should find Jinja very familiar. Many of the syntax elements look and work the same. However, Jinja provides some more syntax elements, and some work a bit differently. This section covers the template changes. The API, including extension support, is fundamentally different so it won't be covered here. Django supports using Jinja as its template engine, see https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines. Method Calls ~~~~~~~~~~~~ In Django, methods are called implicitly, without parentheses. .. code-block:: django {% for page in user.get_created_pages %} ... {% endfor %} In Jinja, using parentheses is required for calls, like in Python. This allows you to pass variables to the method, which is not possible in Django. This syntax is also used for calling macros. .. code-block:: jinja {% for page in user.get_created_pages() %} ... {% endfor %} Filter Arguments ~~~~~~~~~~~~~~~~ In Django, one literal value can be passed to a filter after a colon. .. code-block:: django {{ items|join:"", "" }} In Jinja, filters can take any number of positional and keyword arguments in parentheses, like function calls. Arguments can also be variables instead of literal values. .. code-block:: jinja {{ items|join("", "") }} Tests ~~~~~ In addition to filters, Jinja also has ""tests"" used with the ``is`` operator. This operator is not the same as the Python operator. .. code-block:: jinja {% if user.user_id is odd %} {{ user.username|e }} is odd {% else %} hmm. {{ user.username|e }} looks pretty normal {% endif %} Loops ~~~~~ In Django, the special variable for the loop context is called ``forloop``, and the ``empty`` is used for no loop items. .. code-block:: django {% for item in items %} {{ forloop.counter }}. {{ item }} {% empty %} No items! {% endfor %} In Jinja, the special variable for the loop context is called ``loop``, and the ``else`` block is used for no loop items. .. code-block:: jinja {% for item in items %} {{ loop.index }}. {{ item }} {% else %} No items! {% endfor %} Cycle ~~~~~ In Django, the ``{% cycle %}`` can be used in a for loop to alternate between values per loop. .. code-block:: django {% for user in users %}
  • {{ user }}
  • {% endfor %} In Jinja, the ``loop`` context has a ``cycle`` method. .. code-block:: jinja {% for user in users %}
  • {{ user }}
  • {% endfor %} A cycler can also be assigned to a variable and used outside or across loops with the ``cycle()`` global function. ",en,software_docs,Jinja 3.1.6,"[{""license"": ""BSD-3-Clause"", ""locator"": ""jinja2-3.1.6/docs/switching.rst#codepoints:0:3069"", ""revision"": ""3.1.6+sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"", ""source_id"": ""jinja-3.1:switching.rst"", ""uri"": ""https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz""}]" dp-pt-jinja-3.1-switching.rst-1,dp-Jinja-switching.rst,"Mako ---- You can configure Jinja to look more like Mako: .. code-block:: python env = Environment( block_start_string=""<%"", block_end_string=""%>"", variable_start_string=""${"", variable_end_string=""}"", comment_start_string=""<%doc>"", commend_end_string="""", line_statement_prefix=""%"", line_comment_prefix=""##"", ) With an environment configured like that, Jinja should be able to interpret a small subset of Mako templates without any changes. Jinja does not support embedded Python code, so you would have to move that out of the template. You could either process the data with the same code before rendering, or add a global function or filter to the Jinja environment. The syntax for defs (which are called macros in Jinja) and template inheritance is different too. The following Mako template: .. code-block:: mako <%inherit file=""layout.html"" /> <%def name=""title()"">Page Title
      % for item in list:
    • ${item}
    • % endfor
    Looks like this in Jinja with the above configuration: .. code-block:: jinja <% extends ""layout.html"" %> <% block title %>Page Title<% endblock %> <% block body %>
      % for item in list:
    • ${item}
    • % endfor
    <% endblock %> ",en,software_docs,Jinja 3.1.6,"[{""license"": ""BSD-3-Clause"", ""locator"": ""jinja2-3.1.6/docs/switching.rst#codepoints:3069:4413"", ""revision"": ""3.1.6+sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"", ""source_id"": ""jinja-3.1:switching.rst"", ""uri"": ""https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz""}]" dp-pt-jinja-3.1-tricks.rst-0,dp-Jinja-tricks.rst,"Tips and Tricks =============== .. highlight:: html+jinja This part of the documentation shows some tips and tricks for Jinja templates. .. _null-default-fallback: Null-Default Fallback --------------------- Jinja supports dynamic inheritance and does not distinguish between parent and child template as long as no `extends` tag is visited. While this leads to the surprising behavior that everything before the first `extends` tag including whitespace is printed out instead of being ignored, it can be used for a neat trick. Usually child templates extend from one template that adds a basic HTML skeleton. However it's possible to put the `extends` tag into an `if` tag to only extend from the layout template if the `standalone` variable evaluates to false, which it does by default if it's not defined. Additionally a very basic skeleton is added to the file so that if it's indeed rendered with `standalone` set to `True` a very basic HTML skeleton is added:: {% if not standalone %}{% extends 'default.html' %}{% endif -%} {% block title %}The Page Title{% endblock %} {% block body %}

    This is the page body.

    {% endblock %} Alternating Rows ---------------- If you want to have different styles for each row of a table or list you can use the `cycle` method on the `loop` object::
      {% for row in rows %}
    • {{ row }}
    • {% endfor %}
    `cycle` can take an unlimited number of strings. Each time this tag is encountered the next item from the list is rendered. Highlighting Active Menu Items ------------------------------ Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of `block`\s in child templates are global and executed before the layout template is evaluated it's possible to define the active menu item in the child template:: {% extends ""layout.html"" %} {% set active_page = ""index"" %} The layout template can then access `active_page`. Additionally it makes sense to define a default for that variable:: {% set navigation_bar = [ ('/', 'index', 'Index'), ('/downloads/', 'downloads', 'Downloads'), ('/about/', 'about', 'About') ] -%} {% set active_page = active_page|default('index') -%} ...
      {% for href, id, caption in navigation_bar %} {{ caption|e }} {% endfor %}
    ... .. _accessing-the-parent-loop: Accessing the parent Loop ------------------------- The special `loop` variable always points to the innermost loop. If it's desired to have access to an outer loop it's possible to alias it:: {% for row in table %} {% set rowloop = loop %} {% for cell in row %} {% endfor %} {% endfor %}
    {{ cell }}
    ",en,software_docs,Jinja 3.1.6,"[{""license"": ""BSD-3-Clause"", ""locator"": ""jinja2-3.1.6/docs/tricks.rst#codepoints:0:3168"", ""revision"": ""3.1.6+sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"", ""source_id"": ""jinja-3.1:tricks.rst"", ""uri"": ""https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz""}]" dp-pt-cpython-3.13-c-api-float.rst-0,dp-Python-c-api-float.rst,".. highlight:: c .. _floatobjects: Floating-Point Objects ====================== .. index:: pair: object; floating-point .. c:type:: PyFloatObject This subtype of :c:type:`PyObject` represents a Python floating-point object. .. c:var:: PyTypeObject PyFloat_Type This instance of :c:type:`PyTypeObject` represents the Python floating-point type. This is the same object as :class:`float` in the Python layer. .. c:function:: int PyFloat_Check(PyObject *p) Return true if its argument is a :c:type:`PyFloatObject` or a subtype of :c:type:`PyFloatObject`. This function always succeeds. .. c:function:: int PyFloat_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of :c:type:`PyFloatObject`. This function always succeeds. .. c:function:: PyObject* PyFloat_FromString(PyObject *str) Create a :c:type:`PyFloatObject` object based on the string value in *str*, or ``NULL`` on failure. .. c:function:: PyObject* PyFloat_FromDouble(double v) Create a :c:type:`PyFloatObject` object from *v*, or ``NULL`` on failure. .. c:function:: double PyFloat_AsDouble(PyObject *pyfloat) Return a C :c:expr:`double` representation of the contents of *pyfloat*. If *pyfloat* is not a Python floating-point object but has a :meth:`~object.__float__` method, this method will first be called to convert *pyfloat* into a float. If :meth:`!__float__` is not defined then it falls back to :meth:`~object.__index__`. This method returns ``-1.0`` upon failure, so one should call :c:func:`PyErr_Occurred` to check for errors. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) Return a C :c:expr:`double` representation of the contents of *pyfloat*, but without error checking. .. c:function:: PyObject* PyFloat_GetInfo(void) Return a structseq instance which contains information about the precision, minimum and maximum values of a float. It's a thin wrapper around the header file :file:`float.h`. .. c:function:: double PyFloat_GetMax() Return the maximum representable finite float *DBL_MAX* as C :c:expr:`double`. .. c:function:: double PyFloat_GetMin() Return the minimum normalized positive float *DBL_MIN* as C :c:expr:`double`. Pack and Unpack functions ------------------------- The pack and unpack functions provide an efficient platform-independent way to store floating-point values as byte strings. The Pack routines produce a bytes string from a C :c:expr:`double`, and the Unpack routines produce a C :c:expr:`double` from such a bytes string. The suffix (2, 4 or 8) specifies the number of bytes in the bytes string. On platforms that appear to use IEEE 754 formats these functions work by copying bits. On other platforms, the 2-byte format is identical to the IEEE 754 binary16 half-precision format, the 4-byte format (32-bit) is identical to the IEEE 754 binary32 single precision format, and the 8-byte format to the IEEE 754 binary64 double precision format, although the packing of INFs and NaNs (if such things exist on the platform) isn't handled correctly, and attempting to unpack a bytes string containing an IEEE INF or NaN will raise an exception. On non-IEEE platforms with more precision, or larger dynamic range, than IEEE 754 supports, not all values can be packed; on non-IEEE platforms with less precision, or smaller dynamic range, not all values can be unpacked. What happens in such cases is partly accidental (alas). .. versionadded:: 3.11 ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/float.rst#codepoints:0:3608"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/float.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-float.rst-1,dp-Python-c-api-float.rst,"Pack functions ^^^^^^^^^^^^^^ The pack routines write 2, 4 or 8 bytes, starting at *p*. *le* is an :c:expr:`int` argument, non-zero if you want the bytes string in little-endian format (exponent last, at ``p+1``, ``p+3``, or ``p+6`` ``p+7``), zero if you want big-endian format (exponent first, at *p*). The :c:macro:`PY_BIG_ENDIAN` constant can be used to use the native endian: it is equal to ``1`` on big endian processor, or ``0`` on little endian processor. Return value: ``0`` if all is OK, ``-1`` if error (and an exception is set, most likely :exc:`OverflowError`). There are two problems on non-IEEE platforms: * What this does is undefined if *x* is a NaN or infinity. * ``-0.0`` and ``+0.0`` produce the same bytes string. .. c:function:: int PyFloat_Pack2(double x, unsigned char *p, int le) Pack a C double as the IEEE 754 binary16 half-precision format. .. c:function:: int PyFloat_Pack4(double x, unsigned char *p, int le) Pack a C double as the IEEE 754 binary32 single precision format. .. c:function:: int PyFloat_Pack8(double x, unsigned char *p, int le) Pack a C double as the IEEE 754 binary64 double precision format. Unpack functions ^^^^^^^^^^^^^^^^ The unpack routines read 2, 4 or 8 bytes, starting at *p*. *le* is an :c:expr:`int` argument, non-zero if the bytes string is in little-endian format (exponent last, at ``p+1``, ``p+3`` or ``p+6`` and ``p+7``), zero if big-endian (exponent first, at *p*). The :c:macro:`PY_BIG_ENDIAN` constant can be used to use the native endian: it is equal to ``1`` on big endian processor, or ``0`` on little endian processor. Return value: The unpacked double. On error, this is ``-1.0`` and :c:func:`PyErr_Occurred` is true (and an exception is set, most likely :exc:`OverflowError`). Note that on a non-IEEE platform this will refuse to unpack a bytes string that represents a NaN or infinity. .. c:function:: double PyFloat_Unpack2(const unsigned char *p, int le) Unpack the IEEE 754 binary16 half-precision format as a C double. .. c:function:: double PyFloat_Unpack4(const unsigned char *p, int le) Unpack the IEEE 754 binary32 single precision format as a C double. .. c:function:: double PyFloat_Unpack8(const unsigned char *p, int le) Unpack the IEEE 754 binary64 double precision format as a C double. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/float.rst#codepoints:3608:5923"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/float.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-gen.rst-0,dp-Python-c-api-gen.rst,".. highlight:: c .. _gen-objects: Generator Objects ----------------- Generator objects are what Python uses to implement generator iterators. They are normally created by iterating over a function that yields values, rather than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`. .. c:type:: PyGenObject The C structure used for generator objects. .. c:var:: PyTypeObject PyGen_Type The type object corresponding to generator objects. .. c:function:: int PyGen_Check(PyObject *ob) Return true if *ob* is a generator object; *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyGen_CheckExact(PyObject *ob) Return true if *ob*'s type is :c:type:`PyGen_Type`; *ob* must not be ``NULL``. This function always succeeds. .. c:function:: PyObject* PyGen_New(PyFrameObject *frame) Create and return a new generator object based on the *frame* object. A reference to *frame* is stolen by this function. The argument must not be ``NULL``. .. c:function:: PyObject* PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname) Create and return a new generator object based on the *frame* object, with ``__name__`` and ``__qualname__`` set to *name* and *qualname*. A reference to *frame* is stolen by this function. The *frame* argument must not be ``NULL``. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/gen.rst#codepoints:0:1383"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/gen.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-long.rst-1,dp-Python-c-api-long.rst,"Integer Objects --------------- .. index:: pair: object; long integer pair: object; integer All integers are implemented as ""long"" integer objects of arbitrary size. On error, most ``PyLong_As*`` APIs return ``(return type)-1`` which cannot be distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:type:: PyLongObject This subtype of :c:type:`PyObject` represents a Python integer object. .. c:var:: PyTypeObject PyLong_Type This instance of :c:type:`PyTypeObject` represents the Python integer type. This is the same object as :class:`int` in the Python layer. .. c:function:: int PyLong_Check(PyObject *p) Return true if its argument is a :c:type:`PyLongObject` or a subtype of :c:type:`PyLongObject`. This function always succeeds. .. c:function:: int PyLong_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of :c:type:`PyLongObject`. This function always succeeds. .. c:function:: PyObject* PyLong_FromLong(long v) Return a new :c:type:`PyLongObject` object from *v*, or ``NULL`` on failure. The current implementation keeps an array of integer objects for all integers between ``-5`` and ``256``. When you create an int in that range you actually just get back a reference to the existing object. .. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromSize_t(size_t v) Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromLongLong(long long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`long long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromDouble(double v) Return a new :c:type:`PyLongObject` object from the integer part of *v*, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base) Return a new :c:type:`PyLongObject` based on the string value in *str*, which is interpreted according to the radix in *base*, or ``NULL`` on failure. If *pend* is non-``NULL``, *\*pend* will point to the end of *str* on success or to the first character that could not be processed on error. If *base* is ``0``, *str* is interpreted using the :ref:`integers` definition; in this case, leading zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing whitespace and single underscores after a base specifier and between digits are ignored. If there are no digits or *str* is not NULL-terminated following the digits and trailing whitespace, :exc:`ValueError` will be raised. .. seealso:: Python methods :meth:`int.to_bytes` and :meth:`int.from_bytes` to convert a :c:type:`PyLongObject` to/from an array of bytes in base ``256``. You can call those from C using :c:func:`PyObject_CallMethod`. .. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base) Convert a sequence of Unicode digits in the string *u* to a Python integer value. .. versionadded:: 3.3 .. c:function:: PyObject* PyLong_FromVoidPtr(void *p) Create a Python integer from the pointer *p*. The pointer value can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. .. c:function:: PyObject* PyLong_FromNativeBytes(const void* buffer, size_t n_bytes, int flags) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/long.rst#codepoints:36:4018"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-long.rst-2,dp-Python-c-api-long.rst," Create a Python integer from the pointer *p*. The pointer value can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. .. c:function:: PyObject* PyLong_FromNativeBytes(const void* buffer, size_t n_bytes, int flags) Create a Python integer from the value contained in the first *n_bytes* of *buffer*, interpreted as a two's-complement signed number. *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select the native endian that CPython was compiled with and assume that the most-significant bit is a sign bit. Passing ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` will produce the same result as calling :c:func:`PyLong_FromUnsignedNativeBytes`. Other flags are ignored. .. versionadded:: 3.13 .. c:function:: PyObject* PyLong_FromUnsignedNativeBytes(const void* buffer, size_t n_bytes, int flags) Create a Python integer from the value contained in the first *n_bytes* of *buffer*, interpreted as an unsigned number. *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select the native endian that CPython was compiled with and assume that the most-significant bit is not a sign bit. Flags other than endian are ignored. .. versionadded:: 3.13 .. c:function:: long PyLong_AsLong(PyObject *obj) .. index:: single: LONG_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:namespace:: NULL .. c:function:: long PyLong_AS_LONG(PyObject *obj) A :term:`soft deprecated` alias. Exactly equivalent to the preferred ``PyLong_AsLong``. In particular, it can fail with :exc:`OverflowError` or another exception. .. deprecated:: 3.14 The function is soft deprecated. .. c:function:: int PyLong_AsInt(PyObject *obj) Similar to :c:func:`PyLong_AsLong`, but store the result in a C :c:expr:`int` instead of a C :c:expr:`long`. .. versionadded:: 3.13 .. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow) Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than :c:macro:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: long long PyLong_AsLongLong(PyObject *obj) .. index:: single: OverflowError (built-in exception) Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long long`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/long.rst#codepoints:3772:7715"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-long.rst-3,dp-Python-c-api-long.rst," Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long long`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow) Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than :c:macro:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionadded:: 3.2 .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) .. index:: single: PY_SSIZE_T_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`Py_ssize_t`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) .. index:: single: ULONG_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:expr:`unsigned long`. Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: size_t PyLong_AsSize_t(PyObject *pylong) .. index:: single: SIZE_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`size_t`. Returns ``(size_t)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong) .. index:: single: OverflowError (built-in exception) Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for an :c:expr:`unsigned long long`. Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.1 A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`. .. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj) Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is out of range for an :c:expr:`unsigned long`, return the reduction of that value modulo ``ULONG_MAX + 1``. Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/long.rst#codepoints:7461:11424"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-long.rst-4,dp-Python-c-api-long.rst," Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj) Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is out of range for an :c:expr:`unsigned long long`, return the reduction of that value modulo ``ULLONG_MAX + 1``. Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: double PyLong_AsDouble(PyObject *pylong) Return a C :c:expr:`double` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:expr:`double`. Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) Convert a Python integer *pylong* to a C :c:expr:`void` pointer. If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This is only assured to produce a usable :c:expr:`void` pointer for values created with :c:func:`PyLong_FromVoidPtr`. Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void* buffer, Py_ssize_t n_bytes, int flags) Copy the Python integer value *pylong* to a native *buffer* of size *n_bytes*. The *flags* can be set to ``-1`` to behave similarly to a C cast, or to values documented below to control the behavior. Returns ``-1`` with an exception raised on error. This may happen if *pylong* cannot be interpreted as an integer, or if *pylong* was negative and the ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` flag was set. Otherwise, returns the number of bytes required to store the value. If this is equal to or less than *n_bytes*, the entire value was copied. All *n_bytes* of the buffer are written: large buffers are padded with zeroes. If the returned value is greater than than *n_bytes*, the value was truncated: as many of the lowest bits of the value as could fit are written, and the higher bits are ignored. This matches the typical behavior of a C-style downcast. .. note:: Overflow is not considered an error. If the returned value is larger than *n_bytes*, most significant bits were discarded. ``0`` will never be returned. Values are always copied as two's-complement. Usage example:: int32_t value; Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1); if (bytes < 0) { // Failed. A Python exception was set with the reason. return NULL; } else if (bytes <= (Py_ssize_t)sizeof(value)) { // Success! } else { // Overflow occurred, but 'value' contains the truncated // lowest bits of pylong. } Passing zero to *n_bytes* will return the size of a buffer that would be large enough to hold the value. This may be larger than technically necessary, but not unreasonably so. If *n_bytes=0*, *buffer* may be ``NULL``. .. note:: Passing *n_bytes=0* to this function is not an accurate way to determine the bit length of the value. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/long.rst#codepoints:11157:14982"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-long.rst-5,dp-Python-c-api-long.rst," be large enough to hold the value. This may be larger than technically necessary, but not unreasonably so. If *n_bytes=0*, *buffer* may be ``NULL``. .. note:: Passing *n_bytes=0* to this function is not an accurate way to determine the bit length of the value. To get at the entire Python value of an unknown size, the function can be called twice: first to determine the buffer size, then to fill it:: // Ask how much space we need. Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1); if (expected < 0) { // Failed. A Python exception was set with the reason. return NULL; } assert(expected != 0); // Impossible per the API definition. uint8_t *bignum = malloc(expected); if (!bignum) { PyErr_SetString(PyExc_MemoryError, ""bignum malloc failed.""); return NULL; } // Safely get the entire value. Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1); if (bytes < 0) { // Exception has been set. free(bignum); return NULL; } else if (bytes > expected) { // This should not be possible. PyErr_SetString(PyExc_RuntimeError, ""Unexpected bignum truncation after a size check.""); free(bignum); return NULL; } // The expected success given the above pre-check. // ... use bignum ... free(bignum); *flags* is either ``-1`` (``Py_ASNATIVEBYTES_DEFAULTS``) to select defaults that behave most like a C cast, or a combintation of the other flags in the table below. Note that ``-1`` cannot be combined with other flags. Currently, ``-1`` corresponds to ``Py_ASNATIVEBYTES_NATIVE_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER``. .. c:namespace:: NULL ============================================= ====== Flag Value ============================================= ====== .. c:macro:: Py_ASNATIVEBYTES_DEFAULTS ``-1`` .. c:macro:: Py_ASNATIVEBYTES_BIG_ENDIAN ``0`` .. c:macro:: Py_ASNATIVEBYTES_LITTLE_ENDIAN ``1`` .. c:macro:: Py_ASNATIVEBYTES_NATIVE_ENDIAN ``3`` .. c:macro:: Py_ASNATIVEBYTES_UNSIGNED_BUFFER ``4`` .. c:macro:: Py_ASNATIVEBYTES_REJECT_NEGATIVE ``8`` .. c:macro:: Py_ASNATIVEBYTES_ALLOW_INDEX ``16`` ============================================= ====== Specifying ``Py_ASNATIVEBYTES_NATIVE_ENDIAN`` will override any other endian flags. Passing ``2`` is reserved. By default, sufficient buffer will be requested to include a sign bit. For example, when converting 128 with *n_bytes=1*, the function will return 2 (or more) in order to store a zero sign bit. If ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` is specified, a zero sign bit will be omitted from size calculations. This allows, for example, 128 to fit in a single-byte buffer. If the destination buffer is later treated as signed, a positive input value may become negative. Note that the flag does not affect handling of negative values: for those, space for a sign bit is always requested. Specifying ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` causes an exception to be set if *pylong* is negative. Without this flag, negative values will be copied provided there is enough space for at least one sign bit, regardless of whether ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` was specified. If ``Py_ASNATIVEBYTES_ALLOW_INDEX`` is specified and a non-integer value is passed, its :meth:`~object.__index__` method will be called first. This may result in Python code executing and other threads being allowed to run, which could cause changes to other objects or values in use. When *flags* is ``-1``, this option is not set, and non-integer values will raise :exc:`TypeError`. .. note:: With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without *REJECT_NEGATIVE*), multiple Python integers can map to a single value without overflow. For example, both ``255`` and ``-1`` fit a single-byte buffer and set all its bits. This matches typical C cast behavior. .. versionadded:: 3.13 .. c:function:: PyObject* PyLong_GetInfo(void) On success, return a read only :term:`named tuple`, that holds information about Python's internal representation of integers. See :data:`sys.int_info` for description of individual fields. On failure, return ``NULL`` with an exception set. .. versionadded:: 3.1 .. c:function:: int PyUnstable_Long_IsCompact(const PyLongObject* op) Return 1 if *op* is compact, 0 otherwise. This function makes it possible for performance-critical code to implement a “fast path” for small integers. For compact values use :c:func:`PyUnstable_Long_CompactValue`; for others fall back to a :c:func:`PyLong_As* ` function or :c:func:`PyLong_AsNativeBytes`. The speedup is expected to be negligible for most users. Exactly what values are considered compact is an implementation detail and is subject to change. .. c:function:: Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject* op) If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`, return its value. Otherwise, the return value is undefined. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/long.rst#codepoints:14694:20050"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-c-api-long.rst-1,dp-Python-c-api-long.rst,"Integer Objects --------------- .. index:: pair: object; long integer pair: object; integer All integers are implemented as ""long"" integer objects of arbitrary size. On error, most ``PyLong_As*`` APIs return ``(return type)-1`` which cannot be distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:type:: PyLongObject This subtype of :c:type:`PyObject` represents a Python integer object. .. c:var:: PyTypeObject PyLong_Type This instance of :c:type:`PyTypeObject` represents the Python integer type. This is the same object as :class:`int` in the Python layer. .. c:function:: int PyLong_Check(PyObject *p) Return true if its argument is a :c:type:`PyLongObject` or a subtype of :c:type:`PyLongObject`. This function always succeeds. .. c:function:: int PyLong_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of :c:type:`PyLongObject`. This function always succeeds. .. c:function:: PyObject* PyLong_FromLong(long v) Return a new :c:type:`PyLongObject` object from *v*, or ``NULL`` on failure. The current implementation keeps an array of integer objects for all integers between ``-5`` and ``256``. When you create an int in that range you actually just get back a reference to the existing object. .. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromSize_t(size_t v) Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromLongLong(long long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`long long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long long`, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromDouble(double v) Return a new :c:type:`PyLongObject` object from the integer part of *v*, or ``NULL`` on failure. .. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base) Return a new :c:type:`PyLongObject` based on the string value in *str*, which is interpreted according to the radix in *base*, or ``NULL`` on failure. If *pend* is non-``NULL``, *\*pend* will point to the end of *str* on success or to the first character that could not be processed on error. If *base* is ``0``, *str* is interpreted using the :ref:`integers` definition; in this case, leading zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing whitespace and single underscores after a base specifier and between digits are ignored. If there are no digits or *str* is not NULL-terminated following the digits and trailing whitespace, :exc:`ValueError` will be raised. .. seealso:: Python methods :meth:`int.to_bytes` and :meth:`int.from_bytes` to convert a :c:type:`PyLongObject` to/from an array of bytes in base ``256``. You can call those from C using :c:func:`PyObject_CallMethod`. .. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base) Convert a sequence of Unicode digits in the string *u* to a Python integer value. .. versionadded:: 3.3 .. c:function:: PyObject* PyLong_FromVoidPtr(void *p) Create a Python integer from the pointer *p*. The pointer value can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. .. XXX alias PyLong_AS_LONG (for now) .. c:function:: long PyLong_AsLong(PyObject *obj) ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/long.rst#codepoints:36:4010"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-c-api-long.rst-2,dp-Python-c-api-long.rst," .. c:function:: PyObject* PyLong_FromVoidPtr(void *p) Create a Python integer from the pointer *p*. The pointer value can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. .. XXX alias PyLong_AS_LONG (for now) .. c:function:: long PyLong_AsLong(PyObject *obj) .. index:: single: LONG_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow) Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than :c:macro:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: long long PyLong_AsLongLong(PyObject *obj) .. index:: single: OverflowError (built-in exception) Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long long`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow) Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than :c:macro:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionadded:: 3.2 .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) .. index:: single: PY_SSIZE_T_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`Py_ssize_t`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/long.rst#codepoints:3716:7638"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-c-api-long.rst-3,dp-Python-c-api-long.rst," be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`Py_ssize_t`. Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) .. index:: single: ULONG_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:expr:`unsigned long`. Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: size_t PyLong_AsSize_t(PyObject *pylong) .. index:: single: SIZE_MAX (C macro) single: OverflowError (built-in exception) Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`size_t`. Returns ``(size_t)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong) .. index:: single: OverflowError (built-in exception) Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for an :c:expr:`unsigned long long`. Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.1 A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`. .. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj) Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is out of range for an :c:expr:`unsigned long`, return the reduction of that value modulo ``ULONG_MAX + 1``. Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj) Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is out of range for an :c:expr:`unsigned long long`, return the reduction of that value modulo ``ULLONG_MAX + 1``. Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. .. versionchanged:: 3.10 This function will no longer use :meth:`~object.__int__`. .. c:function:: double PyLong_AsDouble(PyObject *pylong) Return a C :c:expr:`double` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:expr:`double`. Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) Convert a Python integer *pylong* to a C :c:expr:`void` pointer. If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This is only assured to produce a usable :c:expr:`void` pointer for values created with :c:func:`PyLong_FromVoidPtr`. Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: PyObject* PyLong_GetInfo(void) On success, return a read only :term:`named tuple`, that holds information about Python's internal representation of integers. See :data:`sys.int_info` for description of individual fields. On failure, return ``NULL`` with an exception set. .. versionadded:: 3.1 .. c:function:: int PyUnstable_Long_IsCompact(const PyLongObject* op) Return 1 if *op* is compact, 0 otherwise. This function makes it possible for performance-critical code to implement a “fast path” for small integers. For compact values use :c:func:`PyUnstable_Long_CompactValue`; for others fall back to a :c:func:`PyLong_As* ` function or :c:func:`calling ` :meth:`int.to_bytes`. The speedup is expected to be negligible for most users. Exactly what values are considered compact is an implementation detail and is subject to change. .. c:function:: Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject* op) If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`, return its value. Otherwise, the return value is undefined. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/long.rst#codepoints:7341:12488"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/long.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-0,dp-Python-c-api-memory.rst,".. highlight:: c .. _memory: ***************** Memory Management ***************** .. sectionauthor:: Vladimir Marangozov .. _memoryoverview: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:0:185"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-1,dp-Python-c-api-memory.rst,"Overview ======== Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the *Python memory manager*. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching. At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all Python-related data by interacting with the memory manager of the operating system. On top of the raw memory allocator, several object-specific allocators operate on the same heap and implement distinct memory management policies adapted to the peculiarities of every object type. For example, integer objects are managed differently within the heap than strings, tuples or dictionaries because integers imply different storage requirements and speed/space tradeoffs. The Python memory manager thus delegates some of the work to the object-specific allocators, but ensures that the latter operate within the bounds of the private heap. It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document. .. index:: single: malloc (C function) single: calloc (C function) single: realloc (C function) single: free (C function) To avoid memory corruption, extension writers should never try to operate on Python objects with the functions exported by the C library: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. This will result in mixed calls between the C allocator and the Python memory manager with fatal consequences, because they implement different algorithms and operate on different heaps. However, one may safely allocate and release memory blocks with the C library allocator for individual purposes, as shown in the following example:: PyObject *res; char *buf = (char *) malloc(BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); ...Do some I/O operation involving buf... res = PyBytes_FromString(buf); free(buf); /* malloc'ed */ return res; In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory manager is involved only in the allocation of the bytes object returned as a result. In most situations, however, it is recommended to allocate memory from the Python heap specifically because the latter is under control of the Python memory manager. For example, this is required when the interpreter is extended with new object types written in C. Another reason for using the Python heap is the desire to *inform* the Python memory manager about the memory needs of the extension module. Even when the requested memory is used exclusively for internal, highly specific purposes, delegating all memory requests to the Python memory manager causes the interpreter to have a more accurate image of its memory footprint as a whole. Consequently, under certain circumstances, the Python memory manager may or may not trigger appropriate actions, like garbage collection, memory compaction or other preventive procedures. Note that by using the C library allocator as shown in the previous example, the allocated memory for the I/O buffer escapes completely the Python memory manager. .. seealso:: The :envvar:`PYTHONMALLOC` environment variable can be used to configure the memory allocators used by Python. The :envvar:`PYTHONMALLOCSTATS` environment variable can be used to print statistics of the :ref:`pymalloc memory allocator ` every time a new pymalloc object arena is created, and on shutdown. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:185:4218"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-2,dp-Python-c-api-memory.rst,"Allocator Domains ================= .. _allocator-domains: All allocating functions belong to one of three different ""domains"" (see also :c:type:`PyMemAllocatorDomain`). These domains represent different allocation strategies and are optimized for different purposes. The specific details on how every domain allocates memory or what internal functions each domain calls is considered an implementation detail, but for debugging purposes a simplified table can be found at :ref:`here `. The APIs used to allocate and free a block of memory must be from the same domain. For example, :c:func:`PyMem_Free` must be used to free memory allocated using :c:func:`PyMem_Malloc`. The three allocation domains are: * Raw domain: intended for allocating memory for general-purpose memory buffers where the allocation *must* go to the system allocator or where the allocator can operate without the :term:`GIL`. The memory is requested directly from the system. See :ref:`Raw Memory Interface `. * ""Mem"" domain: intended for allocating memory for Python buffers and general-purpose memory buffers where the allocation must be performed with the :term:`GIL` held. The memory is taken from the Python private heap. See :ref:`Memory Interface `. * Object domain: intended for allocating memory for Python objects. The memory is taken from the Python private heap. See :ref:`Object allocators `. .. note:: The :term:`free-threaded ` build requires that only Python objects are allocated using the ""object"" domain and that all Python objects are allocated using that domain. This differs from the prior Python versions, where this was only a best practice and not a hard requirement. For example, buffers (non-Python objects) should be allocated using :c:func:`PyMem_Malloc`, :c:func:`PyMem_RawMalloc`, or :c:func:`malloc`, but not :c:func:`PyObject_Malloc`. See :ref:`Memory Allocation APIs `. .. _raw-memoryinterface: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:4218:6292"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-3,dp-Python-c-api-memory.rst,"Raw Memory Interface ==================== The following function sets are wrappers to the system allocator. These functions are thread-safe, the :term:`GIL ` does not need to be held. The :ref:`default raw memory allocator ` uses the following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`!free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting zero bytes. .. versionadded:: 3.4 .. c:function:: void* PyMem_RawMalloc(size_t n) Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_RawMalloc(1)`` had been called instead. The memory will not have been initialized in any way. .. c:function:: void* PyMem_RawCalloc(size_t nelem, size_t elsize) Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_RawCalloc(1, 1)`` had been called instead. .. versionadded:: 3.5 .. c:function:: void* PyMem_RawRealloc(void *p, size_t n) Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is ``NULL``, the call is equivalent to ``PyMem_RawMalloc(n)``; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-``NULL``. Unless *p* is ``NULL``, it must have been returned by a previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or :c:func:`PyMem_RawCalloc`. If the request fails, :c:func:`PyMem_RawRealloc` returns ``NULL`` and *p* remains a valid pointer to the previous memory area. .. c:function:: void PyMem_RawFree(void *p) Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or :c:func:`PyMem_RawCalloc`. Otherwise, or if ``PyMem_RawFree(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. .. _memoryinterface: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:6292:8729"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-4,dp-Python-c-api-memory.rst,"Memory Interface ================ The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap. The :ref:`default memory allocator ` uses the :ref:`pymalloc memory allocator `. .. warning:: The :term:`GIL ` must be held when using these functions. .. versionchanged:: 3.6 The default allocator is now pymalloc instead of system :c:func:`malloc`. .. c:function:: void* PyMem_Malloc(size_t n) Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_Malloc(1)`` had been called instead. The memory will not have been initialized in any way. .. c:function:: void* PyMem_Calloc(size_t nelem, size_t elsize) Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been called instead. .. versionadded:: 3.5 .. c:function:: void* PyMem_Realloc(void *p, size_t n) Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-``NULL``. Unless *p* is ``NULL``, it must have been returned by a previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`. If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* remains a valid pointer to the previous memory area. .. c:function:: void PyMem_Free(void *p) Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`. Otherwise, or if ``PyMem_Free(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. The following type-oriented macros are provided for convenience. Note that *TYPE* refers to any C type. .. c:macro:: PyMem_New(TYPE, n) Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of memory. Returns a pointer cast to ``TYPE*``. The memory will not have been initialized in any way. .. c:macro:: PyMem_Resize(p, TYPE, n) Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * sizeof(TYPE))`` bytes. Returns a pointer cast to ``TYPE*``. On return, *p* will be a pointer to the new memory area, or ``NULL`` in the event of failure. This is a C preprocessor macro; *p* is always reassigned. Save the original value of *p* to avoid losing memory when handling errors. .. c:function:: void PyMem_Del(void *p) Same as :c:func:`PyMem_Free`. In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving the C API functions listed above. However, note that their use does not preserve binary compatibility across Python versions and is therefore deprecated in extension modules. * ``PyMem_MALLOC(size)`` * ``PyMem_NEW(type, size)`` * ``PyMem_REALLOC(ptr, size)`` * ``PyMem_RESIZE(ptr, type, size)`` * ``PyMem_FREE(ptr)`` * ``PyMem_DEL(ptr)`` .. _objectinterface: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:8729:12481"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-5,dp-Python-c-api-memory.rst,"Object allocators ================= The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap. .. note:: There is no guarantee that the memory returned by these allocators can be successfully cast to a Python object when intercepting the allocating functions in this domain by the methods described in the :ref:`Customize Memory Allocators ` section. The :ref:`default object allocator ` uses the :ref:`pymalloc memory allocator `. .. warning:: The :term:`GIL ` must be held when using these functions. .. c:function:: void* PyObject_Malloc(size_t n) Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyObject_Malloc(1)`` had been called instead. The memory will not have been initialized in any way. .. c:function:: void* PyObject_Calloc(size_t nelem, size_t elsize) Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyObject_Calloc(1, 1)`` had been called instead. .. versionadded:: 3.5 .. c:function:: void* PyObject_Realloc(void *p, size_t n) Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is ``NULL``, the call is equivalent to ``PyObject_Malloc(n)``; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-``NULL``. Unless *p* is ``NULL``, it must have been returned by a previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`. If the request fails, :c:func:`PyObject_Realloc` returns ``NULL`` and *p* remains a valid pointer to the previous memory area. .. c:function:: void PyObject_Free(void *p) Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`. Otherwise, or if ``PyObject_Free(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. .. _default-memory-allocators: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:12481:15199"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-6,dp-Python-c-api-memory.rst,"Default Memory Allocators ========================= Default memory allocators: =============================== ==================== ================== ===================== ==================== Configuration Name PyMem_RawMalloc PyMem_Malloc PyObject_Malloc =============================== ==================== ================== ===================== ==================== Release build ``""pymalloc""`` ``malloc`` ``pymalloc`` ``pymalloc`` Debug build ``""pymalloc_debug""`` ``malloc`` + debug ``pymalloc`` + debug ``pymalloc`` + debug Release build, without pymalloc ``""malloc""`` ``malloc`` ``malloc`` ``malloc`` Debug build, without pymalloc ``""malloc_debug""`` ``malloc`` + debug ``malloc`` + debug ``malloc`` + debug =============================== ==================== ================== ===================== ==================== Legend: * Name: value for :envvar:`PYTHONMALLOC` environment variable. * ``malloc``: system allocators from the standard C library, C functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. * ``pymalloc``: :ref:`pymalloc memory allocator `. * ``mimalloc``: :ref:`mimalloc memory allocator `. The pymalloc allocator will be used if mimalloc support isn't available. * ""+ debug"": with :ref:`debug hooks on the Python memory allocators `. * ""Debug build"": :ref:`Python build in debug mode `. .. _customize-memory-allocators: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:15199:16821"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-7,dp-Python-c-api-memory.rst,"Customize Memory Allocators =========================== .. versionadded:: 3.4 .. c:type:: PyMemAllocatorEx Structure used to describe a memory block allocator. The structure has the following fields: +----------------------------------------------------------+---------------------------------------+ | Field | Meaning | +==========================================================+=======================================+ | ``void *ctx`` | user context passed as first argument | +----------------------------------------------------------+---------------------------------------+ | ``void* malloc(void *ctx, size_t size)`` | allocate a memory block | +----------------------------------------------------------+---------------------------------------+ | ``void* calloc(void *ctx, size_t nelem, size_t elsize)`` | allocate a memory block initialized | | | with zeros | +----------------------------------------------------------+---------------------------------------+ | ``void* realloc(void *ctx, void *ptr, size_t new_size)`` | allocate or resize a memory block | +----------------------------------------------------------+---------------------------------------+ | ``void free(void *ctx, void *ptr)`` | free a memory block | +----------------------------------------------------------+---------------------------------------+ .. versionchanged:: 3.5 The :c:type:`!PyMemAllocator` structure was renamed to :c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added. .. c:type:: PyMemAllocatorDomain Enum used to identify an allocator domain. Domains: .. c:namespace:: NULL .. c:macro:: PYMEM_DOMAIN_RAW Functions: * :c:func:`PyMem_RawMalloc` * :c:func:`PyMem_RawRealloc` * :c:func:`PyMem_RawCalloc` * :c:func:`PyMem_RawFree` .. c:macro:: PYMEM_DOMAIN_MEM Functions: * :c:func:`PyMem_Malloc`, * :c:func:`PyMem_Realloc` * :c:func:`PyMem_Calloc` * :c:func:`PyMem_Free` .. c:macro:: PYMEM_DOMAIN_OBJ Functions: * :c:func:`PyObject_Malloc` * :c:func:`PyObject_Realloc` * :c:func:`PyObject_Calloc` * :c:func:`PyObject_Free` .. c:function:: void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) Get the memory block allocator of the specified domain. .. c:function:: void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) Set the memory block allocator of the specified domain. The new allocator must return a distinct non-``NULL`` pointer when requesting zero bytes. For the :c:macro:`PYMEM_DOMAIN_RAW` domain, the allocator must be thread-safe: the :term:`GIL ` is not held when the allocator is called. For the remaining domains, the allocator must also be thread-safe: the allocator may be called in different interpreters that do not share a ``GIL``. If the new allocator is not a hook (does not call the previous allocator), the :c:func:`PyMem_SetupDebugHooks` function must be called to reinstall the debug hooks on top on the new allocator. See also :c:member:`PyPreConfig.allocator` and :ref:`Preinitialize Python with PyPreConfig `. .. warning:: :c:func:`PyMem_SetAllocator` does have the following contract: * It can be called after :c:func:`Py_PreInitialize` and before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator. There are no restrictions over the installed allocator other than the ones imposed by the domain (for instance, the Raw Domain allows the allocator to be called without the GIL held). See :ref:`the section on allocator domains ` for more information. * If called after Python has finish initializing (after :c:func:`Py_InitializeFromConfig` has been called) the allocator **must** wrap the existing allocator. Substituting the current allocator for some other arbitrary one is **not supported**. .. versionchanged:: 3.12 All allocators must be thread-safe. .. c:function:: void PyMem_SetupDebugHooks(void) Setup :ref:`debug hooks in the Python memory allocators ` to detect memory errors. .. _pymem-debug-hooks: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:16821:21473"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-8,dp-Python-c-api-memory.rst,"Debug hooks on the Python memory allocators =========================================== When :ref:`Python is built in debug mode `, the :c:func:`PyMem_SetupDebugHooks` function is called at the :ref:`Python preinitialization ` to setup debug hooks on Python memory allocators to detect memory errors. The :envvar:`PYTHONMALLOC` environment variable can be used to install debug hooks on a Python compiled in release mode (ex: ``PYTHONMALLOC=debug``). The :c:func:`PyMem_SetupDebugHooks` function can be used to set debug hooks after calling :c:func:`PyMem_SetAllocator`. These debug hooks fill dynamically allocated memory blocks with special, recognizable bit patterns. Newly allocated memory is filled with the byte ``0xCD`` (``PYMEM_CLEANBYTE``), freed memory is filled with the byte ``0xDD`` (``PYMEM_DEADBYTE``). Memory blocks are surrounded by ""forbidden bytes"" filled with the byte ``0xFD`` (``PYMEM_FORBIDDENBYTE``). Strings of these bytes are unlikely to be valid addresses, floats, or ASCII strings. Runtime checks: - Detect API violations. For example, detect if :c:func:`PyObject_Free` is called on a memory block allocated by :c:func:`PyMem_Malloc`. - Detect write before the start of the buffer (buffer underflow). - Detect write after the end of the buffer (buffer overflow). - Check that the :term:`GIL ` is held when allocator functions of :c:macro:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) and :c:macro:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) domains are called. On error, the debug hooks use the :mod:`tracemalloc` module to get the traceback where a memory block was allocated. The traceback is only displayed if :mod:`tracemalloc` is tracing Python memory allocations and the memory block was traced. Let *S* = ``sizeof(size_t)``. ``2*S`` bytes are added at each end of each block of *N* bytes requested. The memory layout is like so, where p represents the address returned by a malloc-like or realloc-like function (``p[i:j]`` means the slice of bytes from ``*(p+i)`` inclusive up to ``*(p+j)`` exclusive; note that the treatment of negative indices differs from a Python slice): ``p[-2*S:-S]`` Number of bytes originally asked for. This is a size_t, big-endian (easier to read in a memory dump). ``p[-S]`` API identifier (ASCII character): * ``'r'`` for :c:macro:`PYMEM_DOMAIN_RAW`. * ``'m'`` for :c:macro:`PYMEM_DOMAIN_MEM`. * ``'o'`` for :c:macro:`PYMEM_DOMAIN_OBJ`. ``p[-S+1:0]`` Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads. ``p[0:N]`` The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch reference to uninitialized memory. When a realloc-like function is called requesting a larger memory block, the new excess bytes are also filled with PYMEM_CLEANBYTE. When a free-like function is called, these are overwritten with PYMEM_DEADBYTE, to catch reference to freed memory. When a realloc- like function is called requesting a smaller memory block, the excess old bytes are also filled with PYMEM_DEADBYTE. ``p[N:N+S]`` Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads. ``p[N+S:N+2*S]`` Only used if the ``PYMEM_DEBUG_SERIALNO`` macro is defined (not defined by default). A serial number, incremented by 1 on each call to a malloc-like or realloc-like function. Big-endian :c:type:`size_t`. If ""bad memory"" is detected later, the serial number gives an excellent way to set a breakpoint on the next run, to capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is the only place the serial number is incremented, and exists so you can set such a breakpoint easily. A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE bytes at each end are intact. If they've been altered, diagnostic output is written to stderr, and the program is aborted via Py_FatalError(). The other main failure mode is provoking a memory error when a program reads up one of the special bit patterns and tries to use it as an address. If you get in a debugger then and look at the object, you're likely to see that it's entirely filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or PYMEM_CLEANBYTE (meaning uninitialized memory is getting used). .. versionchanged:: 3.6 The :c:func:`PyMem_SetupDebugHooks` function now also works on Python compiled in release mode. On error, the debug hooks now use :mod:`tracemalloc` to get the traceback where a memory block was allocated. The debug hooks now also check if the GIL is held when functions of :c:macro:`PYMEM_DOMAIN_OBJ` and :c:macro:`PYMEM_DOMAIN_MEM` domains are called. .. versionchanged:: 3.8 Byte patterns ``0xCB`` (``PYMEM_CLEANBYTE``), ``0xDB`` (``PYMEM_DEADBYTE``) and ``0xFB`` (``PYMEM_FORBIDDENBYTE``) have been replaced with ``0xCD``, ``0xDD`` and ``0xFD`` to use the same values than Windows CRT debug ``malloc()`` and ``free()``. .. _pymalloc: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:21473:26569"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-9,dp-Python-c-api-memory.rst,"The pymalloc allocator ====================== Python has a *pymalloc* allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses memory mappings called ""arenas"" with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms. It falls back to :c:func:`PyMem_RawMalloc` and :c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes. *pymalloc* is the :ref:`default allocator ` of the :c:macro:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and :c:macro:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains. The arena allocator uses the following functions: * :c:func:`!VirtualAlloc` and :c:func:`!VirtualFree` on Windows, * :c:func:`!mmap` and :c:func:`!munmap` if available, * :c:func:`malloc` and :c:func:`free` otherwise. This allocator is disabled if Python is configured with the :option:`--without-pymalloc` option. It can also be disabled at runtime using the :envvar:`PYTHONMALLOC` environment variable (ex: ``PYTHONMALLOC=malloc``). Customize pymalloc Arena Allocator ---------------------------------- .. versionadded:: 3.4 .. c:type:: PyObjectArenaAllocator Structure used to describe an arena allocator. The structure has three fields: +--------------------------------------------------+---------------------------------------+ | Field | Meaning | +==================================================+=======================================+ | ``void *ctx`` | user context passed as first argument | +--------------------------------------------------+---------------------------------------+ | ``void* alloc(void *ctx, size_t size)`` | allocate an arena of size bytes | +--------------------------------------------------+---------------------------------------+ | ``void free(void *ctx, void *ptr, size_t size)`` | free an arena | +--------------------------------------------------+---------------------------------------+ .. c:function:: void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator) Get the arena allocator. .. c:function:: void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator) Set the arena allocator. .. _mimalloc: The mimalloc allocator ====================== .. versionadded:: 3.13 Python supports the mimalloc allocator when the underlying platform support is available. mimalloc ""is a general purpose allocator with excellent performance characteristics. Initially developed by Daan Leijen for the runtime systems of the Koka and Lean languages."" tracemalloc C API ================= .. versionadded:: 3.7 .. c:function:: int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size) Track an allocated memory block in the :mod:`tracemalloc` module. Return ``0`` on success, return ``-1`` on error (failed to allocate memory to store the trace). Return ``-2`` if tracemalloc is disabled. If memory block is already tracked, update the existing trace. .. c:function:: int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr) Untrack an allocated memory block in the :mod:`tracemalloc` module. Do nothing if the block was not tracked. Return ``-2`` if tracemalloc is disabled, otherwise return ``0``. .. _memoryexamples: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:26569:30000"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-c-api-memory.rst-10,dp-Python-c-api-memory.rst,"Examples ======== Here is the example from section :ref:`memoryoverview`, rewritten so that the I/O buffer is allocated from the Python heap by using the first function set:: PyObject *res; char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); /* ...Do some I/O operation involving buf... */ res = PyBytes_FromString(buf); PyMem_Free(buf); /* allocated with PyMem_Malloc */ return res; The same code using the type-oriented function set:: PyObject *res; char *buf = PyMem_New(char, BUFSIZ); /* for I/O */ if (buf == NULL) return PyErr_NoMemory(); /* ...Do some I/O operation involving buf... */ res = PyBytes_FromString(buf); PyMem_Del(buf); /* allocated with PyMem_New */ return res; Note that in the two examples above, the buffer is always manipulated via functions belonging to the same set. Indeed, it is required to use the same memory API family for a given memory block, so that the risk of mixing different allocators is reduced to a minimum. The following code sequence contains two errors, one of which is labeled as *fatal* because it mixes two different allocators operating on different heaps. :: char *buf1 = PyMem_New(char, BUFSIZ); char *buf2 = (char *) malloc(BUFSIZ); char *buf3 = (char *) PyMem_Malloc(BUFSIZ); ... PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */ free(buf2); /* Right -- allocated via malloc() */ free(buf1); /* Fatal -- should be PyMem_Del() */ In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are allocated and released with :c:macro:`PyObject_New`, :c:macro:`PyObject_NewVar` and :c:func:`PyObject_Del`. These will be explained in the next chapter on defining and implementing new object types in C. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/memory.rst#codepoints:30000:31848"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-c-api-memory.rst-2,dp-Python-c-api-memory.rst,"Allocator Domains ================= .. _allocator-domains: All allocating functions belong to one of three different ""domains"" (see also :c:type:`PyMemAllocatorDomain`). These domains represent different allocation strategies and are optimized for different purposes. The specific details on how every domain allocates memory or what internal functions each domain calls is considered an implementation detail, but for debugging purposes a simplified table can be found at :ref:`here `. There is no hard requirement to use the memory returned by the allocation functions belonging to a given domain for only the purposes hinted by that domain (although this is the recommended practice). For example, one could use the memory returned by :c:func:`PyMem_RawMalloc` for allocating Python objects or the memory returned by :c:func:`PyObject_Malloc` for allocating memory for buffers. The three allocation domains are: * Raw domain: intended for allocating memory for general-purpose memory buffers where the allocation *must* go to the system allocator or where the allocator can operate without the :term:`GIL`. The memory is requested directly to the system. * ""Mem"" domain: intended for allocating memory for Python buffers and general-purpose memory buffers where the allocation must be performed with the :term:`GIL` held. The memory is taken from the Python private heap. * Object domain: intended for allocating memory belonging to Python objects. The memory is taken from the Python private heap. When freeing memory previously allocated by the allocating functions belonging to a given domain,the matching specific deallocating functions must be used. For example, :c:func:`PyMem_Free` must be used to free memory allocated using :c:func:`PyMem_Malloc`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/memory.rst#codepoints:4218:6025"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-c-api-memory.rst-4,dp-Python-c-api-memory.rst,"Memory Interface ================ The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap. The :ref:`default memory allocator ` uses the :ref:`pymalloc memory allocator `. .. warning:: The :term:`GIL ` must be held when using these functions. .. versionchanged:: 3.6 The default allocator is now pymalloc instead of system :c:func:`malloc`. .. c:function:: void* PyMem_Malloc(size_t n) Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_Malloc(1)`` had been called instead. The memory will not have been initialized in any way. .. c:function:: void* PyMem_Calloc(size_t nelem, size_t elsize) Allocates *nelem* elements each whose size in bytes is *elsize* and returns a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the request fails. The memory is initialized to zeros. Requesting zero elements or elements of size zero bytes returns a distinct non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been called instead. .. versionadded:: 3.5 .. c:function:: void* PyMem_Realloc(void *p, size_t n) Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-``NULL``. Unless *p* is ``NULL``, it must have been returned by a previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`. If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* remains a valid pointer to the previous memory area. .. c:function:: void PyMem_Free(void *p) Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`. Otherwise, or if ``PyMem_Free(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. The following type-oriented macros are provided for convenience. Note that *TYPE* refers to any C type. .. c:macro:: PyMem_New(TYPE, n) Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of memory. Returns a pointer cast to ``TYPE*``. The memory will not have been initialized in any way. .. c:macro:: PyMem_Resize(p, TYPE, n) Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * sizeof(TYPE))`` bytes. Returns a pointer cast to ``TYPE*``. On return, *p* will be a pointer to the new memory area, or ``NULL`` in the event of failure. This is a C preprocessor macro; *p* is always reassigned. Save the original value of *p* to avoid losing memory when handling errors. .. c:function:: void PyMem_Del(void *p) Same as :c:func:`PyMem_Free`. In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving the C API functions listed above. However, note that their use does not preserve binary compatibility across Python versions and is therefore deprecated in extension modules. * ``PyMem_MALLOC(size)`` * ``PyMem_NEW(type, size)`` * ``PyMem_REALLOC(ptr, size)`` * ``PyMem_RESIZE(ptr, type, size)`` * ``PyMem_FREE(ptr)`` * ``PyMem_DEL(ptr)`` ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/memory.rst#codepoints:8462:12192"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-c-api-memory.rst-6,dp-Python-c-api-memory.rst,"Default Memory Allocators ========================= Default memory allocators: =============================== ==================== ================== ===================== ==================== Configuration Name PyMem_RawMalloc PyMem_Malloc PyObject_Malloc =============================== ==================== ================== ===================== ==================== Release build ``""pymalloc""`` ``malloc`` ``pymalloc`` ``pymalloc`` Debug build ``""pymalloc_debug""`` ``malloc`` + debug ``pymalloc`` + debug ``pymalloc`` + debug Release build, without pymalloc ``""malloc""`` ``malloc`` ``malloc`` ``malloc`` Debug build, without pymalloc ``""malloc_debug""`` ``malloc`` + debug ``malloc`` + debug ``malloc`` + debug =============================== ==================== ================== ===================== ==================== Legend: * Name: value for :envvar:`PYTHONMALLOC` environment variable. * ``malloc``: system allocators from the standard C library, C functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. * ``pymalloc``: :ref:`pymalloc memory allocator `. * ""+ debug"": with :ref:`debug hooks on the Python memory allocators `. * ""Debug build"": :ref:`Python build in debug mode `. .. _customize-memory-allocators: ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/memory.rst#codepoints:14910:16395"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-c-api-memory.rst-9,dp-Python-c-api-memory.rst,"The pymalloc allocator ====================== Python has a *pymalloc* allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses memory mappings called ""arenas"" with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms. It falls back to :c:func:`PyMem_RawMalloc` and :c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes. *pymalloc* is the :ref:`default allocator ` of the :c:macro:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and :c:macro:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains. The arena allocator uses the following functions: * :c:func:`!VirtualAlloc` and :c:func:`!VirtualFree` on Windows, * :c:func:`!mmap` and :c:func:`!munmap` if available, * :c:func:`malloc` and :c:func:`free` otherwise. This allocator is disabled if Python is configured with the :option:`--without-pymalloc` option. It can also be disabled at runtime using the :envvar:`PYTHONMALLOC` environment variable (ex: ``PYTHONMALLOC=malloc``). Customize pymalloc Arena Allocator ---------------------------------- .. versionadded:: 3.4 .. c:type:: PyObjectArenaAllocator Structure used to describe an arena allocator. The structure has three fields: +--------------------------------------------------+---------------------------------------+ | Field | Meaning | +==================================================+=======================================+ | ``void *ctx`` | user context passed as first argument | +--------------------------------------------------+---------------------------------------+ | ``void* alloc(void *ctx, size_t size)`` | allocate an arena of size bytes | +--------------------------------------------------+---------------------------------------+ | ``void free(void *ctx, void *ptr, size_t size)`` | free an arena | +--------------------------------------------------+---------------------------------------+ .. c:function:: void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator) Get the arena allocator. .. c:function:: void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator) Set the arena allocator. tracemalloc C API ================= .. versionadded:: 3.7 .. c:function:: int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size) Track an allocated memory block in the :mod:`tracemalloc` module. Return ``0`` on success, return ``-1`` on error (failed to allocate memory to store the trace). Return ``-2`` if tracemalloc is disabled. If memory block is already tracked, update the existing trace. .. c:function:: int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr) Untrack an allocated memory block in the :mod:`tracemalloc` module. Do nothing if the block was not tracked. Return ``-2`` if tracemalloc is disabled, otherwise return ``0``. .. _memoryexamples: ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/memory.rst#codepoints:26143:29221"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/memory.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-c-api-none.rst-0,dp-Python-c-api-none.rst,".. highlight:: c .. _noneobject: The ``None`` Object ------------------- .. index:: pair: object; None Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the Python/C API. Since ``None`` is a singleton, testing for object identity (using ``==`` in C) is sufficient. There is no :c:func:`!PyNone_Check` function for the same reason. .. c:var:: PyObject* Py_None The Python ``None`` object, denoting lack of value. This object has no methods and is :term:`immortal`. .. versionchanged:: 3.12 :c:data:`Py_None` is :term:`immortal`. .. c:macro:: Py_RETURN_NONE Return :c:data:`Py_None` from a function. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/c-api/none.rst#codepoints:0:655"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:c-api/none.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-c-api-none.rst-0,dp-Python-c-api-none.rst,".. highlight:: c .. _noneobject: The ``None`` Object ------------------- .. index:: pair: object; None Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the Python/C API. Since ``None`` is a singleton, testing for object identity (using ``==`` in C) is sufficient. There is no :c:func:`!PyNone_Check` function for the same reason. .. c:var:: PyObject* Py_None The Python ``None`` object, denoting lack of value. This object has no methods and is `immortal `_. .. versionchanged:: 3.12 :c:data:`Py_None` is immortal. .. c:macro:: Py_RETURN_NONE Return :c:data:`Py_None` from a function. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/c-api/none.rst#codepoints:0:672"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:c-api/none.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-copyright.rst-0,dp-Python-copyright.rst,"********* Copyright ********* Python and this documentation is: Copyright © 2001-2024 Python Software Foundation. All rights reserved. Copyright © 2000 BeOpen.com. All rights reserved. Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved. Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. ------- See :ref:`history-and-license` for complete license and permissions information. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/copyright.rst#codepoints:0:447"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:copyright.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-copyright.rst-0,dp-Python-copyright.rst,"********* Copyright ********* Python and this documentation is: Copyright © 2001-2023 Python Software Foundation. All rights reserved. Copyright © 2000 BeOpen.com. All rights reserved. Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved. Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. ------- See :ref:`history-and-license` for complete license and permissions information. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/copyright.rst#codepoints:0:447"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:copyright.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-extending-index.rst-0,dp-Python-extending-index.rst,".. _extending-index: ################################################## Extending and Embedding the Python Interpreter ################################################## This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can not only define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature. This document assumes basic knowledge about Python. For an informal introduction to the language, see :ref:`tutorial-index`. :ref:`reference-index` gives a more formal definition of the language. :ref:`library-index` documents the existing object types, functions and modules (both built-in and written in Python) that give the language its wide application range. For a detailed description of the whole Python/C API, see the separate :ref:`c-api-index`. Recommended third party tools ============================= This guide only covers the basic tools for creating extensions provided as part of this version of CPython. Third party tools like `Cython `_, `cffi `_, `SWIG `_ and `Numba `_ offer both simpler and more sophisticated approaches to creating C and C++ extensions for Python. .. seealso:: `Python Packaging User Guide: Binary Extensions `_ The Python Packaging User Guide not only covers several available tools that simplify the creation of binary extensions, but also discusses the various reasons why creating an extension module may be desirable in the first place. Creating extensions without third party tools ============================================= This section of the guide covers creating C and C++ extensions without assistance from third party tools. It is intended primarily for creators of those tools, rather than being a recommended way to create your own C extensions. .. toctree:: :maxdepth: 2 :numbered: extending.rst newtypes_tutorial.rst newtypes.rst building.rst windows.rst Embedding the CPython runtime in a larger application ===================================================== Sometimes, rather than creating an extension that runs inside the Python interpreter as the main application, it is desirable to instead embed the CPython runtime inside a larger application. This section covers some of the details involved in doing that successfully. .. toctree:: :maxdepth: 2 :numbered: embedding.rst ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/extending/index.rst#codepoints:0:2878"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:extending/index.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-1,dp-Python-glossary.rst,"******** Glossary ******** .. if you add new entries, keep the alphabetical sorting! .. glossary:: ``>>>`` The default Python prompt of the :term:`interactive` shell. Often seen for code examples which can be executed interactively in the interpreter. ``...`` Can refer to: * The default Python prompt of the :term:`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 :const:`Ellipsis` built-in constant. abstract base class Abstract base classes complement :term:`duck-typing` by providing a way to define interfaces when other techniques like :func:`hasattr` would be clumsy or subtly wrong (for example with :ref:`magic methods `). ABCs introduce virtual subclasses, which are classes that don't inherit from a class but are still recognized by :func:`isinstance` and :func:`issubclass`; see the :mod:`abc` module documentation. Python comes with many built-in ABCs for data structures (in the :mod:`collections.abc` module), numbers (in the :mod:`numbers` module), streams (in the :mod:`io` module), import finders and loaders (in the :mod:`importlib.abc` module). You can create your own ABCs with the :mod:`abc` module. annotation A label associated with a variable, a class attribute or a function parameter or return value, used by convention as a :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 :attr:`__annotations__` special attribute of modules, classes, and functions, respectively. See :term:`variable annotation`, :term:`function annotation`, :pep:`484` and :pep:`526`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. argument A value passed to a :term:`function` (or :term:`method`) when calling the function. There are two kinds of argument: * :dfn:`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 :func:`complex`:: complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5}) * :dfn:`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 :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 :ref:`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 :term:`parameter` glossary entry, the FAQ question on :ref:`the difference between arguments and parameters `, and :pep:`362`. asynchronous context manager An object which controls the environment seen in an :keyword:`async with` statement by defining :meth:`~object.__aenter__` and :meth:`~object.__aexit__` methods. Introduced by :pep:`492`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:15:3776"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-2,dp-Python-glossary.rst," `, and :pep:`362`. asynchronous context manager An object which controls the environment seen in an :keyword:`async with` statement by defining :meth:`~object.__aenter__` and :meth:`~object.__aexit__` methods. Introduced by :pep:`492`. asynchronous generator A function which returns an :term:`asynchronous generator iterator`. It looks like a coroutine function defined with :keyword:`async def` except that it contains :keyword:`yield` expressions for producing a series of values usable in an :keyword:`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 :keyword:`await` expressions as well as :keyword:`async for`, and :keyword:`async with` statements. asynchronous generator iterator An object created by a :term:`asynchronous generator` function. This is an :term:`asynchronous iterator` which when called using the :meth:`~object.__anext__` method returns an awaitable object which will execute the body of the asynchronous generator function until the next :keyword:`yield` expression. Each :keyword:`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 :meth:`~object.__anext__`, it picks up where it left off. See :pep:`492` and :pep:`525`. asynchronous iterable An object, that can be used in an :keyword:`async for` statement. Must return an :term:`asynchronous iterator` from its :meth:`~object.__aiter__` method. Introduced by :pep:`492`. asynchronous iterator An object that implements the :meth:`~object.__aiter__` and :meth:`~object.__anext__` methods. :meth:`~object.__anext__` must return an :term:`awaitable` object. :keyword:`async for` resolves the awaitables returned by an asynchronous iterator's :meth:`~object.__anext__` method until it raises a :exc:`StopAsyncIteration` exception. Introduced by :pep:`492`. attribute A value associated with an object which is usually referenced by name using dotted expressions. For example, if an object *o* has an attribute *a* it would be referenced as *o.a*. It is possible to give an object an attribute whose name is not an identifier as defined by :ref:`identifiers`, for example using :func:`setattr`, if the object allows it. Such an attribute will not be accessible using a dotted expression, and would instead need to be retrieved with :func:`getattr`. awaitable An object that can be used in an :keyword:`await` expression. Can be a :term:`coroutine` or an object with an :meth:`~object.__await__` method. See also :pep:`492`. BDFL Benevolent Dictator For Life, a.k.a. `Guido van Rossum `_, Python's creator. binary file A :term:`file object` able to read and write :term:`bytes-like objects `. Examples of binary files are files opened in binary mode (``'rb'``, ``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer `, :data:`sys.stdout.buffer `, and instances of :class:`io.BytesIO` and :class:`gzip.GzipFile`. See also :term:`text file` for a file object able to read and write :class:`str` objects. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:3483:7239"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-3,dp-Python-glossary.rst," ``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer `, :data:`sys.stdout.buffer `, and instances of :class:`io.BytesIO` and :class:`gzip.GzipFile`. See also :term:`text file` for a file object able to read and write :class:`str` objects. borrowed reference In Python's C API, a borrowed reference is a reference to an object, where the code using the object does not own the reference. It becomes a dangling pointer if the object is destroyed. For example, a garbage collection can remove the last :term:`strong reference` to the object and so destroy it. Calling :c:func:`Py_INCREF` on the :term:`borrowed reference` is recommended to convert it to a :term:`strong reference` in-place, except when the object cannot be destroyed before the last usage of the borrowed reference. The :c:func:`Py_NewRef` function can be used to create a new :term:`strong reference`. bytes-like object An object that supports the :ref:`bufferobjects` and can export a C-:term:`contiguous` buffer. This includes all :class:`bytes`, :class:`bytearray`, and :class:`array.array` objects, as well as many common :class:`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 :class:`bytearray` and a :class:`memoryview` of a :class:`bytearray`. Other operations require the binary data to be stored in immutable objects (""read-only bytes-like objects""); examples of these include :class:`bytes` and a :class:`memoryview` of a :class:`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 :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 :ref:`the dis module `. callable A callable is an object that can be called, possibly with a set of arguments (see :term:`argument`), with the following syntax:: callable(argument1, argument2, argumentN) A :term:`function`, and by extension a :term:`method`, is a callable. An instance of a class that implements the :meth:`~object.__call__` method is also a callable. 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). ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:6950:10448"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-4,dp-Python-glossary.rst," 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). 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 :mod:`math` module, use :mod:`cmath`. 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 :keyword:`with` statement by defining :meth:`~object.__enter__` and :meth:`~object.__exit__` methods. See :pep:`343`. 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 :mod:`contextvars`. contiguous .. index:: C-contiguous, Fortran 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 :keyword:`async def` statement. See also :pep:`492`. coroutine function A function which returns a :term:`coroutine` object. A coroutine function may be defined with the :keyword:`async def` statement, and may contain :keyword:`await`, :keyword:`async for`, and :keyword:`async with` keywords. These were introduced by :pep:`492`. CPython The canonical implementation of the Python programming language, as distributed on `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 :func:`classmethod` and :func:`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 :ref:`function definitions ` and :ref:`class definitions ` for more about decorators. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:10208:14108"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-5,dp-Python-glossary.rst," @staticmethod def f(arg): ... The same concept exists for classes, but is less commonly used there. See the documentation for :ref:`function definitions ` and :ref:`class definitions ` for more about decorators. descriptor Any object which defines the methods :meth:`~object.__get__`, :meth:`~object.__set__`, or :meth:`~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 :ref:`descriptors` or the :ref:`Descriptor How To Guide `. dictionary An associative array, where arbitrary keys are mapped to values. The keys can be any object with :meth:`~object.__hash__` and :meth:`~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 :ref:`comprehensions`. dictionary view The objects returned from :meth:`dict.keys`, :meth:`dict.values`, and :meth:`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 :ref:`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 :attr:`~definition.__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 :func:`type` or :func:`isinstance`. (Note, however, that duck-typing can be complemented with :term:`abstract base classes `.) Instead, it typically employs :func:`hasattr` tests or :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 :keyword:`try` and :keyword:`except` statements. The technique contrasts with the :term:`LBYL` style common to many other languages such as C. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:13826:17458"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-6,dp-Python-glossary.rst," exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many :keyword:`try` and :keyword:`except` statements. The technique contrasts with the :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 :term:`statement`\s which cannot be used as expressions, such as :keyword:`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 :ref:`formatted string literals `. See also :pep:`498`. file object An object exposing a file-oriented API (with methods such as :meth:`!read` or :meth:`!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 :dfn:`file-like objects` or :dfn:`streams`. There are actually three categories of file objects: raw :term:`binary files `, buffered :term:`binary files ` and :term:`text files `. Their interfaces are defined in the :mod:`io` module. The canonical way to create a file object is by using the :func:`open` function. file-like object A synonym for :term:`file object`. filesystem encoding and error handler Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to the operating system. The filesystem encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise :exc:`UnicodeError`. The :func:`sys.getfilesystemencoding` and :func:`sys.getfilesystemencodeerrors` functions can be used to get the filesystem encoding and error handler. The :term:`filesystem encoding and error handler` are configured at Python startup by the :c:func:`PyConfig_Read` function: see :c:member:`~PyConfig.filesystem_encoding` and :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`. See also the :term:`locale encoding`. finder An object that tries to find the :term:`loader` for a module that is being imported. There are two types of finder: :term:`meta path finders ` for use with :data:`sys.meta_path`, and :term:`path entry finders ` for use with :data:`sys.path_hooks`. See :ref:`importsystem` and :mod:`importlib` 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`. free threading A threading model where multiple threads can run Python bytecode simultaneously within the same interpreter. This is in contrast to the :term:`global interpreter lock` which allows only one thread to execute Python bytecode at a time. See :pep:`703`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:17178:21121"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-7,dp-Python-glossary.rst," free threading A threading model where multiple threads can run Python bytecode simultaneously within the same interpreter. This is in contrast to the :term:`global interpreter lock` which allows only one thread to execute Python bytecode at a time. See :pep:`703`. function A series of statements which returns some value to a caller. It can also be passed zero or more :term:`arguments ` which may be used in the execution of the body. See also :term:`parameter`, :term:`method`, and the :ref:`function` section. function annotation An :term:`annotation` of a function parameter or return value. Function annotations are usually used for :term:`type hints `: for example, this function is expected to take two :class:`int` arguments and is also expected to have an :class:`int` return value:: def sum_two_numbers(a: int, b: int) -> int: return a + b Function annotation syntax is explained in section :ref:`function`. See :term:`variable annotation` and :pep:`484`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. __future__ A :ref:`future statement `, ``from __future__ import ``, directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python. The :mod:`__future__` 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 :mod:`gc` module. .. index:: single: generator generator A function which returns a :term:`generator iterator`. It looks like a normal function except that it contains :keyword:`yield` expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the :func:`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 :term:`generator` function. Each :keyword:`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). .. index:: single: generator expression generator expression An :term:`expression` that returns an :term:`iterator`. It looks like a normal expression followed by a :keyword:`!for` clause defining a loop variable, range, and an optional :keyword:`!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 :term:`single dispatch` glossary entry, the :func:`functools.singledispatch` decorator, and :pep:`443`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:20824:24795"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-8,dp-Python-glossary.rst," for different types. Which implementation should be used during a call is determined by the dispatch algorithm. See also the :term:`single dispatch` glossary entry, the :func:`functools.singledispatch` decorator, and :pep:`443`. generic type A :term:`type` that can be parameterized; typically a :ref:`container class` such as :class:`list` or :class:`dict`. Used for :term:`type hints ` and :term:`annotations `. For more details, see :ref:`generic alias types`, :pep:`483`, :pep:`484`, :pep:`585`, and the :mod:`typing` module. GIL See :term:`global interpreter lock`. global interpreter lock The mechanism used by the :term:`CPython` interpreter to assure that only one thread executes Python :term:`bytecode` at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as :class:`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. As of Python 3.13, the GIL can be disabled using the :option:`--disable-gil` build configuration. After building Python with this option, code must be run with :option:`-X gil 0 <-X>` or after setting the :envvar:`PYTHON_GIL=0 ` environment variable. This feature enables improved performance for multi-threaded applications and makes it easier to use multi-core CPUs efficiently. For more details, see :pep:`703`. 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 :ref:`pyc-invalidation`. hashable An object is *hashable* if it has a hash value which never changes during its lifetime (it needs a :meth:`~object.__hash__` method), and can be compared to other objects (it needs an :meth:`~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 :func:`id`. IDLE An Integrated Development and Learning Environment for Python. :ref:`idle` is a basic editor and interpreter environment which ships with the standard distribution of Python. immortal *Immortal objects* are a CPython implementation detail introduced in :pep:`683`. If an object is immortal, its :term:`reference count` is never modified, and therefore it is never deallocated while the interpreter is running. For example, :const:`True` and :const:`None` are immortal in CPython. 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. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:24540:28528"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-9,dp-Python-glossary.rst," 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 :term:`path entries `) that are searched by the :term:`path based finder` for modules to import. During import, this list of locations usually comes from :data:`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 :term:`finder` and :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)``). For more on interactive mode, see :ref:`tut-interac`. 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 :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 :term:`garbage collector `. 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 :class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence types like :class:`dict`, :term:`file objects `, and objects of any classes you define with an :meth:`~iterator.__iter__` method or with a :meth:`~object.__getitem__` method that implements :term:`sequence` semantics. Iterables can be used in a :keyword:`for` loop and in many other places where a sequence is needed (:func:`zip`, :func:`map`, ...). When an iterable object is passed as an argument to the built-in function :func:`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 :func:`iter` or deal with iterator objects yourself. The :keyword:`for` statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also :term:`iterator`, :term:`sequence`, and :term:`generator`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:28273:32036"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-10,dp-Python-glossary.rst," :func:`iter` or deal with iterator objects yourself. The :keyword:`for` statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also :term:`iterator`, :term:`sequence`, and :term:`generator`. iterator An object representing a stream of data. Repeated calls to the iterator's :meth:`~iterator.__next__` method (or passing it to the built-in function :func:`next`) return successive items in the stream. When no more data are available a :exc:`StopIteration` exception is raised instead. At this point, the iterator object is exhausted and any further calls to its :meth:`!__next__` method just raise :exc:`StopIteration` again. Iterators are required to have an :meth:`~iterator.__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 :class:`list`) produces a fresh new iterator each time you pass it to the :func:`iter` function or use it in a :keyword:`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 :ref:`typeiter`. .. impl-detail:: CPython does not consistently apply the requirement that an iterator define :meth:`~iterator.__iter__`. And also please note that the free-threading CPython does not guarantee the thread-safety of iterator operations. key function A key function or collation function is a callable that returns a value used for sorting or ordering. For example, :func:`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 :func:`min`, :func:`max`, :func:`sorted`, :meth:`list.sort`, :func:`heapq.merge`, :func:`heapq.nsmallest`, :func:`heapq.nlargest`, and :func:`itertools.groupby`. There are several ways to create a key function. For example. the :meth:`str.lower` method can serve as a key function for case insensitive sorts. Alternatively, a key function can be built from a :keyword:`lambda` expression such as ``lambda r: (r[0], r[2])``. Also, :func:`operator.attrgetter`, :func:`operator.itemgetter`, and :func:`operator.methodcaller` are three key function constructors. See the :ref:`Sorting HOW TO ` for examples of how to create and use key functions. keyword argument See :term:`argument`. lambda An anonymous inline function consisting of a single :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 :term:`EAFP` approach and is characterized by the presence of many :keyword:`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. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:31737:35550"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-11,dp-Python-glossary.rst," 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 :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 :keyword:`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 :meth:`load_module`. A loader is typically returned by a :term:`finder`. See :pep:`302` for details and :class:`importlib.abc.Loader` for an :term:`abstract base class`. locale encoding On Unix, it is the encoding of the LC_CTYPE locale. It can be set with :func:`locale.setlocale(locale.LC_CTYPE, new_locale) `. On Windows, it is the ANSI code page (ex: ``""cp1252""``). On Android and VxWorks, Python uses ``""utf-8""`` as the locale encoding. :func:`locale.getencoding` can be used to get the locale encoding. See also the :term:`filesystem encoding and error handler`. magic method .. index:: pair: magic; method An informal synonym for :term:`special method`. mapping A container object that supports arbitrary key lookups and implements the methods specified in the :class:`collections.abc.Mapping` or :class:`collections.abc.MutableMapping` :ref:`abstract base classes `. Examples include :class:`dict`, :class:`collections.defaultdict`, :class:`collections.OrderedDict` and :class:`collections.Counter`. meta path finder A :term:`finder` returned by a search of :data:`sys.meta_path`. Meta path finders are related to, but different from :term:`path entry finders `. See :class:`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 :ref:`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 :term:`argument` (which is usually called ``self``). See :term:`function` and :term:`nested scope`. method resolution order Method Resolution Order is the order in which base classes are searched for a member during lookup. See :ref:`python_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 :term:`importing`. See also :term:`package`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:35320:39276"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-12,dp-Python-glossary.rst," 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 :term:`importing`. See also :term:`package`. module spec A namespace containing the import-related information used to load a module. An instance of :class:`importlib.machinery.ModuleSpec`. MRO See :term:`method resolution order`. mutable Mutable objects can change their value but keep their :func:`id`. See also :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 :func:`time.localtime` and :func:`os.stat`. Another example is :data:`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 :class:`tuple` and that defines named fields. Such a class can be written by hand, or it can be created by inheriting :class:`typing.NamedTuple`, or with the factory function :func:`collections.namedtuple`. The latter techniques also add 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 :func:`builtins.open <.open>` and :func:`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 :func:`random.seed` or :func:`itertools.islice` makes it clear that those functions are implemented by the :mod:`random` and :mod:`itertools` modules, respectively. namespace package A :pep:`420` :term:`package` which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a :term:`regular package` because they have no ``__init__.py`` file. See also :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 :keyword:`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 :attr:`~object.__slots__`, descriptors, properties, :meth:`~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 :term:`new-style class`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:39017:42870"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-13,dp-Python-glossary.rst," properties, :meth:`~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 :term:`new-style class`. optimized scope A scope where target local variable names are reliably known to the compiler when the code is compiled, allowing optimization of read and write access to these names. The local namespaces for functions, generators, coroutines, comprehensions, and generator expressions are optimized in this fashion. Note: most interpreter optimizations are applied to all scopes, only those relying on a known set of local and nonlocal variable names are restricted to optimized scopes. package A Python :term:`module` which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a ``__path__`` attribute. See also :term:`regular package` and :term:`namespace package`. parameter A named entity in a :term:`function` (or method) definition that specifies an :term:`argument` (or in some cases, arguments) that the function can accept. There are five kinds of parameter: * :dfn:`positional-or-keyword`: specifies an argument that can be passed either :term:`positionally ` or as a :term:`keyword argument `. This is the default kind of parameter, for example *foo* and *bar* in the following:: def func(foo, bar=None): ... .. _positional-only_parameter: * :dfn:`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_parameter: * :dfn:`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): ... * :dfn:`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): ... * :dfn:`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 :term:`argument` glossary entry, the FAQ question on :ref:`the difference between arguments and parameters `, the :class:`inspect.Parameter` class, the :ref:`function` section, and :pep:`362`. path entry A single location on the :term:`import path` which the :term:`path based finder` consults to find modules for importing. path entry finder A :term:`finder` returned by a callable on :data:`sys.path_hooks` (i.e. a :term:`path entry hook`) which knows how to locate modules given a :term:`path entry`. See :class:`importlib.abc.PathEntryFinder` for the methods that path entry finders implement. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:42611:46598"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-14,dp-Python-glossary.rst," A :term:`finder` returned by a callable on :data:`sys.path_hooks` (i.e. a :term:`path entry hook`) which knows how to locate modules given a :term:`path entry`. See :class:`importlib.abc.PathEntryFinder` for the methods that path entry finders implement. path entry hook A callable on the :data:`sys.path_hooks` list which returns a :term:`path entry finder` if it knows how to find modules on a specific :term:`path entry`. path based finder One of the default :term:`meta path finders ` which searches an :term:`import path` for modules. path-like object An object representing a file system path. A path-like object is either a :class:`str` or :class:`bytes` object representing a path, or an object implementing the :class:`os.PathLike` protocol. An object that supports the :class:`os.PathLike` protocol can be converted to a :class:`str` or :class:`bytes` file system path by calling the :func:`os.fspath` function; :func:`os.fsdecode` and :func:`os.fsencode` can be used to guarantee a :class:`str` or :class:`bytes` result instead, respectively. Introduced by :pep:`519`. 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`. 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`. positional argument See :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` for more details. provisional package See :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 :keyword:`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) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:46311:50305"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-15,dp-Python-glossary.rst," 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`. 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. Some objects are :term:`immortal` and have reference counts that are never modified, and therefore the objects are never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the :term:`CPython` implementation. Programmers can call the :func:`sys.getrefcount` function to return the reference count for a particular object. regular package A traditional :term:`package`, such as a directory containing an ``__init__.py`` file. See also :term:`namespace package`. REPL An acronym for the ""read–eval–print loop"", another name for the :term:`interactive` interpreter shell. __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 :term:`iterable` which supports efficient element access using integer indices via the :meth:`~object.__getitem__` special method and defines a :meth:`~object.__len__` method that returns the length of the sequence. Some built-in sequence types are :class:`list`, :class:`str`, :class:`tuple`, and :class:`bytes`. Note that :class:`dict` also supports :meth:`~object.__getitem__` and :meth:`!__len__`, but is considered a mapping rather than a sequence because the lookups use arbitrary :term:`hashable` keys rather than integers. The :class:`collections.abc.Sequence` abstract base class defines a much richer interface that goes beyond just :meth:`~object.__getitem__` and :meth:`~object.__len__`, adding :meth:`!count`, :meth:`!index`, :meth:`~object.__contains__`, and :meth:`~object.__reversed__`. Types that implement this expanded interface can be registered explicitly using :func:`~abc.ABCMeta.register`. For more documentation on sequence methods generally, see :ref:`Common Sequence Operations `. 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 :ref:`comprehensions`. single dispatch A form of :term:`generic function` dispatch where the implementation is chosen based on the type of a single argument. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:50050:53903"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-glossary.rst-16,dp-Python-glossary.rst," c not in 'abc'}`` generates the set of strings ``{'r', 'd'}``. See :ref:`comprehensions`. single dispatch A form of :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 :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 :class:`slice` objects internally. soft deprecated A soft deprecated API should not be used in new code, but it is safe for already existing code to use it. The API remains documented and tested, but will not be enhanced further. Soft deprecation, unlike normal deprecation, does not plan on removing the API and will not emit warnings. See `PEP 387: Soft Deprecation `_. special method .. index:: pair: 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 :ref:`specialnames`. statement A statement is part of a suite (a ""block"" of code). A statement is either an :term:`expression` or one of several constructs with a keyword, such as :keyword:`if`, :keyword:`while` or :keyword:`for`. static type checker An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also :term:`type hints ` and the :mod:`typing` module. strong reference In Python's C API, a strong reference is a reference to an object which is owned by the code holding the reference. The strong reference is taken by calling :c:func:`Py_INCREF` when the reference is created and released with :c:func:`Py_DECREF` when the reference is deleted. The :c:func:`Py_NewRef` function can be used to create a strong reference to an object. Usually, the :c:func:`Py_DECREF` function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking one reference. See also :term:`borrowed reference`. 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 :ref:`codecs `, which are collectively referred to as ""text encodings"". text file A :term:`file object` able to read and write :class:`str` objects. Often, a text file actually accesses a byte-oriented datastream and handles the :term:`text encoding` automatically. Examples of text files are files opened in text mode (``'r'`` or ``'w'``), :data:`sys.stdin`, :data:`sys.stdout`, and instances of :class:`io.StringIO`. See also :term:`binary file` for a file object able to read and write :term:`bytes-like objects `. 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 :attr:`~object.__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 :term:`type hints `. 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 :mod:`typing` and :pep:`484`, which describe this functionality. type hint An :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 :term:`static type checkers `. They can also aid IDEs with code completion and refactoring. Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using :func:`typing.get_type_hints`. See :mod:`typing` and :pep:`484`, 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` and :pep:`3116`, as well as :func:`bytes.splitlines` for an additional use. variable annotation An :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 :term:`type hints `: for example this variable is expected to take :class:`int` values:: count: int = 0 Variable annotation syntax is explained in section :ref:`annassign`. See :term:`function annotation`, :pep:`484` and :pep:`526`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. 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 :mod:`venv`. virtual machine A computer defined entirely in software. Python's virtual machine executes the :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. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/glossary.rst#codepoints:53648:60791"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-glossary.rst-1,dp-Python-glossary.rst,"******** Glossary ******** .. if you add new entries, keep the alphabetical sorting! .. 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 :const:`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 :mod:`lib2to3`; a standalone entry point is provided as :file:`Tools/scripts/2to3`. See :ref:`2to3-reference`. abstract base class Abstract base classes complement :term:`duck-typing` by providing a way to define interfaces when other techniques like :func:`hasattr` would be clumsy or subtly wrong (for example with :ref:`magic methods `). ABCs introduce virtual subclasses, which are classes that don't inherit from a class but are still recognized by :func:`isinstance` and :func:`issubclass`; see the :mod:`abc` module documentation. Python comes with many built-in ABCs for data structures (in the :mod:`collections.abc` module), numbers (in the :mod:`numbers` module), streams (in the :mod:`io` module), import finders and loaders (in the :mod:`importlib.abc` module). You can create your own ABCs with the :mod:`abc` module. annotation A label associated with a variable, a class attribute or a function parameter or return value, used by convention as a :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 :attr:`__annotations__` special attribute of modules, classes, and functions, respectively. See :term:`variable annotation`, :term:`function annotation`, :pep:`484` and :pep:`526`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. argument A value passed to a :term:`function` (or :term:`method`) when calling the function. There are two kinds of argument: * :dfn:`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 :func:`complex`:: complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5}) * :dfn:`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 :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 :ref:`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 :term:`parameter` glossary entry, the FAQ question on :ref:`the difference between arguments and parameters `, and :pep:`362`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:15:3898"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-2,dp-Python-glossary.rst," evaluated value is assigned to the local variable. See also the :term:`parameter` glossary entry, the FAQ question on :ref:`the difference between arguments and parameters `, and :pep:`362`. asynchronous context manager An object which controls the environment seen in an :keyword:`async with` statement by defining :meth:`~object.__aenter__` and :meth:`~object.__aexit__` methods. Introduced by :pep:`492`. asynchronous generator A function which returns an :term:`asynchronous generator iterator`. It looks like a coroutine function defined with :keyword:`async def` except that it contains :keyword:`yield` expressions for producing a series of values usable in an :keyword:`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 :keyword:`await` expressions as well as :keyword:`async for`, and :keyword:`async with` statements. asynchronous generator iterator An object created by a :term:`asynchronous generator` function. This is an :term:`asynchronous iterator` which when called using the :meth:`~object.__anext__` method returns an awaitable object which will execute the body of the asynchronous generator function until the next :keyword:`yield` expression. Each :keyword:`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 :meth:`~object.__anext__`, it picks up where it left off. See :pep:`492` and :pep:`525`. asynchronous iterable An object, that can be used in an :keyword:`async for` statement. Must return an :term:`asynchronous iterator` from its :meth:`~object.__aiter__` method. Introduced by :pep:`492`. asynchronous iterator An object that implements the :meth:`~object.__aiter__` and :meth:`~object.__anext__` methods. :meth:`~object.__anext__` must return an :term:`awaitable` object. :keyword:`async for` resolves the awaitables returned by an asynchronous iterator's :meth:`~object.__anext__` method until it raises a :exc:`StopAsyncIteration` exception. Introduced by :pep:`492`. attribute A value associated with an object which is usually referenced by name using dotted expressions. For example, if an object *o* has an attribute *a* it would be referenced as *o.a*. It is possible to give an object an attribute whose name is not an identifier as defined by :ref:`identifiers`, for example using :func:`setattr`, if the object allows it. Such an attribute will not be accessible using a dotted expression, and would instead need to be retrieved with :func:`getattr`. awaitable An object that can be used in an :keyword:`await` expression. Can be a :term:`coroutine` or an object with an :meth:`~object.__await__` method. See also :pep:`492`. BDFL Benevolent Dictator For Life, a.k.a. `Guido van Rossum `_, Python's creator. binary file A :term:`file object` able to read and write :term:`bytes-like objects `. Examples of binary files are files opened in binary mode (``'rb'``, ``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer `, :data:`sys.stdout.buffer `, and instances of :class:`io.BytesIO` and :class:`gzip.GzipFile`. See also :term:`text file` for a file object able to read and write :class:`str` objects. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:3654:7601"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-6,dp-Python-glossary.rst," exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many :keyword:`try` and :keyword:`except` statements. The technique contrasts with the :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 :term:`statement`\s which cannot be used as expressions, such as :keyword:`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 :ref:`formatted string literals `. See also :pep:`498`. file object An object exposing a file-oriented API (with methods such as :meth:`!read` or :meth:`!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 :dfn:`file-like objects` or :dfn:`streams`. There are actually three categories of file objects: raw :term:`binary files `, buffered :term:`binary files ` and :term:`text files `. Their interfaces are defined in the :mod:`io` module. The canonical way to create a file object is by using the :func:`open` function. file-like object A synonym for :term:`file object`. filesystem encoding and error handler Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to the operating system. The filesystem encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise :exc:`UnicodeError`. The :func:`sys.getfilesystemencoding` and :func:`sys.getfilesystemencodeerrors` functions can be used to get the filesystem encoding and error handler. The :term:`filesystem encoding and error handler` are configured at Python startup by the :c:func:`PyConfig_Read` function: see :c:member:`~PyConfig.filesystem_encoding` and :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`. See also the :term:`locale encoding`. finder An object that tries to find the :term:`loader` for a module that is being imported. There are two types of finder: :term:`meta path finders ` for use with :data:`sys.meta_path`, and :term:`path entry finders ` for use with :data:`sys.path_hooks`. See :ref:`importsystem` and :mod:`importlib` 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`. function A series of statements which returns some value to a caller. It can also be passed zero or more :term:`arguments ` which may be used in the execution of the body. See also :term:`parameter`, :term:`method`, and the :ref:`function` section. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:17540:21474"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-7,dp-Python-glossary.rst," function A series of statements which returns some value to a caller. It can also be passed zero or more :term:`arguments ` which may be used in the execution of the body. See also :term:`parameter`, :term:`method`, and the :ref:`function` section. function annotation An :term:`annotation` of a function parameter or return value. Function annotations are usually used for :term:`type hints `: for example, this function is expected to take two :class:`int` arguments and is also expected to have an :class:`int` return value:: def sum_two_numbers(a: int, b: int) -> int: return a + b Function annotation syntax is explained in section :ref:`function`. See :term:`variable annotation` and :pep:`484`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. __future__ A :ref:`future statement `, ``from __future__ import ``, directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python. The :mod:`__future__` 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 :mod:`gc` module. .. index:: single: generator generator A function which returns a :term:`generator iterator`. It looks like a normal function except that it contains :keyword:`yield` expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the :func:`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 :term:`generator` function. Each :keyword:`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). .. index:: single: generator expression generator expression An expression that returns an iterator. It looks like a normal expression followed by a :keyword:`!for` clause defining a loop variable, range, and an optional :keyword:`!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 :term:`single dispatch` glossary entry, the :func:`functools.singledispatch` decorator, and :pep:`443`. generic type A :term:`type` that can be parameterized; typically a :ref:`container class` such as :class:`list` or :class:`dict`. Used for :term:`type hints ` and :term:`annotations `. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:21186:25097"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-8,dp-Python-glossary.rst," generic type A :term:`type` that can be parameterized; typically a :ref:`container class` such as :class:`list` or :class:`dict`. Used for :term:`type hints ` and :term:`annotations `. For more details, see :ref:`generic alias types`, :pep:`483`, :pep:`484`, :pep:`585`, and the :mod:`typing` module. GIL See :term:`global interpreter lock`. global interpreter lock The mechanism used by the :term:`CPython` interpreter to assure that only one thread executes Python :term:`bytecode` at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as :class:`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 :ref:`pyc-invalidation`. hashable An object is *hashable* if it has a hash value which never changes during its lifetime (it needs a :meth:`~object.__hash__` method), and can be compared to other objects (it needs an :meth:`~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 :func:`id`. IDLE An Integrated Development and Learning Environment for Python. :ref:`idle` is a basic editor and interpreter environment which ships with the standard distribution of Python. immortal *Immortal objects* are a CPython implementation detail introduced in :pep:`683`. If an object is immortal, its :term:`reference count` is never modified, and therefore it is never deallocated while the interpreter is running. For example, :const:`True` and :const:`None` are immortal in CPython. 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 :term:`path entries `) that are searched by the :term:`path based finder` for modules to import. During import, this list of locations usually comes from :data:`sys.path`, but for subpackages it may also come from the parent package's ``__path__`` attribute. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:24844:28831"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-9,dp-Python-glossary.rst," searched by the :term:`path based finder` for modules to import. During import, this list of locations usually comes from :data:`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 :term:`finder` and :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 :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 :term:`garbage collector `. 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 :class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence types like :class:`dict`, :term:`file objects `, and objects of any classes you define with an :meth:`~iterator.__iter__` method or with a :meth:`~object.__getitem__` method that implements :term:`sequence` semantics. Iterables can be used in a :keyword:`for` loop and in many other places where a sequence is needed (:func:`zip`, :func:`map`, ...). When an iterable object is passed as an argument to the built-in function :func:`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 :func:`iter` or deal with iterator objects yourself. The :keyword:`for` statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also :term:`iterator`, :term:`sequence`, and :term:`generator`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:28579:31938"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-10,dp-Python-glossary.rst," :func:`iter` or deal with iterator objects yourself. The :keyword:`for` statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also :term:`iterator`, :term:`sequence`, and :term:`generator`. iterator An object representing a stream of data. Repeated calls to the iterator's :meth:`~iterator.__next__` method (or passing it to the built-in function :func:`next`) return successive items in the stream. When no more data are available a :exc:`StopIteration` exception is raised instead. At this point, the iterator object is exhausted and any further calls to its :meth:`!__next__` method just raise :exc:`StopIteration` again. Iterators are required to have an :meth:`~iterator.__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 :class:`list`) produces a fresh new iterator each time you pass it to the :func:`iter` function or use it in a :keyword:`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 :ref:`typeiter`. .. impl-detail:: CPython does not consistently apply the requirement that an iterator define :meth:`~iterator.__iter__`. key function A key function or collation function is a callable that returns a value used for sorting or ordering. For example, :func:`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 :func:`min`, :func:`max`, :func:`sorted`, :meth:`list.sort`, :func:`heapq.merge`, :func:`heapq.nsmallest`, :func:`heapq.nlargest`, and :func:`itertools.groupby`. There are several ways to create a key function. For example. the :meth:`str.lower` method can serve as a key function for case insensitive sorts. Alternatively, a key function can be built from a :keyword:`lambda` expression such as ``lambda r: (r[0], r[2])``. Also, :func:`operator.attrgetter`, :func:`operator.itemgetter`, and :func:`operator.methodcaller` are three key function constructors. See the :ref:`Sorting HOW TO ` for examples of how to create and use key functions. keyword argument See :term:`argument`. lambda An anonymous inline function consisting of a single :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 :term:`EAFP` approach and is characterized by the presence of many :keyword:`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 :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). ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:31639:35507"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-11,dp-Python-glossary.rst," This issue can be solved with locks or by using the EAFP approach. list A built-in Python :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 :keyword:`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 :meth:`load_module`. A loader is typically returned by a :term:`finder`. See :pep:`302` for details and :class:`importlib.abc.Loader` for an :term:`abstract base class`. locale encoding On Unix, it is the encoding of the LC_CTYPE locale. It can be set with :func:`locale.setlocale(locale.LC_CTYPE, new_locale) `. On Windows, it is the ANSI code page (ex: ``""cp1252""``). On Android and VxWorks, Python uses ``""utf-8""`` as the locale encoding. :func:`locale.getencoding` can be used to get the locale encoding. See also the :term:`filesystem encoding and error handler`. magic method .. index:: pair: magic; method An informal synonym for :term:`special method`. mapping A container object that supports arbitrary key lookups and implements the methods specified in the :class:`collections.abc.Mapping` or :class:`collections.abc.MutableMapping` :ref:`abstract base classes `. Examples include :class:`dict`, :class:`collections.defaultdict`, :class:`collections.OrderedDict` and :class:`collections.Counter`. meta path finder A :term:`finder` returned by a search of :data:`sys.meta_path`. Meta path finders are related to, but different from :term:`path entry finders `. See :class:`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 :ref:`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 :term:`argument` (which is usually called ``self``). See :term:`function` and :term:`nested scope`. method resolution order Method Resolution Order is the order in which base classes are searched for a member during lookup. See :ref:`python_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 :term:`importing`. See also :term:`package`. module spec A namespace containing the import-related information used to load a module. An instance of :class:`importlib.machinery.ModuleSpec`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:35245:39206"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-12,dp-Python-glossary.rst," into Python by the process of :term:`importing`. See also :term:`package`. module spec A namespace containing the import-related information used to load a module. An instance of :class:`importlib.machinery.ModuleSpec`. MRO See :term:`method resolution order`. mutable Mutable objects can change their value but keep their :func:`id`. See also :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 :func:`time.localtime` and :func:`os.stat`. Another example is :data:`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 :class:`tuple` and that defines named fields. Such a class can be written by hand, or it can be created by inheriting :class:`typing.NamedTuple`, or with the factory function :func:`collections.namedtuple`. The latter techniques also add 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 :func:`builtins.open <.open>` and :func:`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 :func:`random.seed` or :func:`itertools.islice` makes it clear that those functions are implemented by the :mod:`random` and :mod:`itertools` modules, respectively. namespace package A :pep:`420` :term:`package` which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a :term:`regular package` because they have no ``__init__.py`` file. See also :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 :keyword:`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 :attr:`~object.__slots__`, descriptors, properties, :meth:`~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 :term:`new-style class`. package A Python :term:`module` which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a ``__path__`` attribute. See also :term:`regular package` and :term:`namespace package`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:38956:42896"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-13,dp-Python-glossary.rst," class`. package A Python :term:`module` which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a ``__path__`` attribute. See also :term:`regular package` and :term:`namespace package`. parameter A named entity in a :term:`function` (or method) definition that specifies an :term:`argument` (or in some cases, arguments) that the function can accept. There are five kinds of parameter: * :dfn:`positional-or-keyword`: specifies an argument that can be passed either :term:`positionally ` or as a :term:`keyword argument `. This is the default kind of parameter, for example *foo* and *bar* in the following:: def func(foo, bar=None): ... .. _positional-only_parameter: * :dfn:`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_parameter: * :dfn:`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): ... * :dfn:`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): ... * :dfn:`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 :term:`argument` glossary entry, the FAQ question on :ref:`the difference between arguments and parameters `, the :class:`inspect.Parameter` class, the :ref:`function` section, and :pep:`362`. path entry A single location on the :term:`import path` which the :term:`path based finder` consults to find modules for importing. path entry finder A :term:`finder` returned by a callable on :data:`sys.path_hooks` (i.e. a :term:`path entry hook`) which knows how to locate modules given a :term:`path entry`. See :class:`importlib.abc.PathEntryFinder` for the methods that path entry finders implement. path entry hook A callable on the :data:`sys.path_hooks` list which returns a :term:`path entry finder` if it knows how to find modules on a specific :term:`path entry`. path based finder One of the default :term:`meta path finders ` which searches an :term:`import path` for modules. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:42624:46175"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-14,dp-Python-glossary.rst," entry finder` if it knows how to find modules on a specific :term:`path entry`. path based finder One of the default :term:`meta path finders ` which searches an :term:`import path` for modules. path-like object An object representing a file system path. A path-like object is either a :class:`str` or :class:`bytes` object representing a path, or an object implementing the :class:`os.PathLike` protocol. An object that supports the :class:`os.PathLike` protocol can be converted to a :class:`str` or :class:`bytes` file system path by calling the :func:`os.fspath` function; :func:`os.fsdecode` and :func:`os.fsencode` can be used to guarantee a :class:`str` or :class:`bytes` result instead, respectively. Introduced by :pep:`519`. 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`. 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`. positional argument See :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` for more details. provisional package See :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 :keyword:`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) ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:45933:49541"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-15,dp-Python-glossary.rst," 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`. 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. Some objects are ""immortal"" and have reference counts that are never modified, and therefore the objects are never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the :term:`CPython` implementation. Programmers can call the :func:`sys.getrefcount` function to return the reference count for a particular object. regular package A traditional :term:`package`, such as a directory containing an ``__init__.py`` file. See also :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 :term:`iterable` which supports efficient element access using integer indices via the :meth:`~object.__getitem__` special method and defines a :meth:`~object.__len__` method that returns the length of the sequence. Some built-in sequence types are :class:`list`, :class:`str`, :class:`tuple`, and :class:`bytes`. Note that :class:`dict` also supports :meth:`~object.__getitem__` and :meth:`!__len__`, but is considered a mapping rather than a sequence because the lookups use arbitrary :term:`hashable` keys rather than integers. The :class:`collections.abc.Sequence` abstract base class defines a much richer interface that goes beyond just :meth:`~object.__getitem__` and :meth:`~object.__len__`, adding :meth:`!count`, :meth:`!index`, :meth:`~object.__contains__`, and :meth:`~object.__reversed__`. Types that implement this expanded interface can be registered explicitly using :func:`~abc.ABCMeta.register`. For more documentation on sequence methods generally, see :ref:`Common Sequence Operations `. 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 :ref:`comprehensions`. single dispatch A form of :term:`generic function` dispatch where the implementation is chosen based on the type of a single argument. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:49286:53009"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-glossary.rst-16,dp-Python-glossary.rst," c not in 'abc'}`` generates the set of strings ``{'r', 'd'}``. See :ref:`comprehensions`. single dispatch A form of :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 :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 :class:`slice` objects internally. special method .. index:: pair: 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 :ref:`specialnames`. statement A statement is part of a suite (a ""block"" of code). A statement is either an :term:`expression` or one of several constructs with a keyword, such as :keyword:`if`, :keyword:`while` or :keyword:`for`. static type checker An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also :term:`type hints ` and the :mod:`typing` module. strong reference In Python's C API, a strong reference is a reference to an object which is owned by the code holding the reference. The strong reference is taken by calling :c:func:`Py_INCREF` when the reference is created and released with :c:func:`Py_DECREF` when the reference is deleted. The :c:func:`Py_NewRef` function can be used to create a strong reference to an object. Usually, the :c:func:`Py_DECREF` function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking one reference. See also :term:`borrowed reference`. 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 :ref:`codecs `, which are collectively referred to as ""text encodings"". text file A :term:`file object` able to read and write :class:`str` objects. Often, a text file actually accesses a byte-oriented datastream and handles the :term:`text encoding` automatically. Examples of text files are files opened in text mode (``'r'`` or ``'w'``), :data:`sys.stdin`, :data:`sys.stdout`, and instances of :class:`io.StringIO`. See also :term:`binary file` for a file object able to read and write :term:`bytes-like objects `. 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 :attr:`~object.__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 :term:`type hints `. 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 :mod:`typing` and :pep:`484`, which describe this functionality. type hint An :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 :term:`static type checkers `. They can also aid IDEs with code completion and refactoring. Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using :func:`typing.get_type_hints`. See :mod:`typing` and :pep:`484`, 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` and :pep:`3116`, as well as :func:`bytes.splitlines` for an additional use. variable annotation An :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 :term:`type hints `: for example this variable is expected to take :class:`int` values:: count: int = 0 Variable annotation syntax is explained in section :ref:`annassign`. See :term:`function annotation`, :pep:`484` and :pep:`526`, which describe this functionality. Also see :ref:`annotations-howto` for best practices on working with annotations. 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 :mod:`venv`. virtual machine A computer defined entirely in software. Python's virtual machine executes the :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. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/glossary.rst#codepoints:52754:59460"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:glossary.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-howto-clinic.rst-0,dp-Python-howto-clinic.rst,":orphan: .. This page is retained solely for existing links to /howto/clinic.html. Direct readers to the devguide. ********************** Argument Clinic How-To ********************** .. note:: The Argument Clinic How-TO has been moved to the `Python Developer's Guide `__. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/clinic.rst#codepoints:0:343"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/clinic.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-cporting.rst-0,dp-Python-howto-cporting.rst,".. highlight:: c .. _cporting-howto: ************************************* Porting Extension Modules to Python 3 ************************************* We recommend the following resources for porting extension modules to Python 3: * The `Migrating C extensions`_ chapter from *Supporting Python 3: An in-depth guide*, a book on moving from Python 2 to Python 3 in general, guides the reader through porting an extension module. * The `Porting guide`_ from the *py3c* project provides opinionated suggestions with supporting code. * The `Cython`_ and `CFFI`_ libraries offer abstractions over Python's C API. Extensions generally need to be re-written to use one of them, but the library then handles differences between various Python versions and implementations. .. _Migrating C extensions: http://python3porting.com/cextensions.html .. _Porting guide: https://py3c.readthedocs.io/en/latest/guide.html .. _Cython: https://cython.org/ .. _CFFI: https://cffi.readthedocs.io/en/latest/ ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/cporting.rst#codepoints:0:1006"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/cporting.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-perf_profiling.rst-1,dp-Python-howto-perf_profiling.rst,"============================================== Python support for the Linux ``perf`` profiler ============================================== :author: Pablo Galindo `The Linux perf profiler `_ is a very powerful tool that allows you to profile and obtain information about the performance of your application. ``perf`` also has a very vibrant ecosystem of tools that aid with the analysis of the data that it produces. The main problem with using the ``perf`` profiler with Python applications is that ``perf`` only gets information about native symbols, that is, the names of functions and procedures written in C. This means that the names and file names of Python functions in your code will not appear in the output of ``perf``. Since Python 3.12, the interpreter can run in a special mode that allows Python functions to appear in the output of the ``perf`` profiler. When this mode is enabled, the interpreter will interpose a small piece of code compiled on the fly before the execution of every Python function and it will teach ``perf`` the relationship between this piece of code and the associated Python function using :doc:`perf map files <../c-api/perfmaps>`. .. note:: Support for the ``perf`` profiler is currently only available for Linux on select architectures. Check the output of the ``configure`` build step or check the output of ``python -m sysconfig | grep HAVE_PERF_TRAMPOLINE`` to see if your system is supported. For example, consider the following script: .. code-block:: python def foo(n): result = 0 for _ in range(n): result += 1 return result def bar(n): foo(n) def baz(n): bar(n) if __name__ == ""__main__"": baz(1000000) We can run ``perf`` to sample CPU stack traces at 9999 hertz:: $ perf record -F 9999 -g -o perf.data python my_script.py Then we can use ``perf report`` to analyze the data: .. code-block:: shell-session $ perf report --stdio -n -g # Children Self Samples Command Shared Object Symbol # ........ ........ ............ .......... .................. .......................................... # 91.08% 0.00% 0 python.exe python.exe [.] _start | ---_start | --90.71%--__libc_start_main Py_BytesMain | |--56.88%--pymain_run_python.constprop.0 | | | |--56.13%--_PyRun_AnyFileObject | | _PyRun_SimpleFileObject | | | | | |--55.02%--run_mod | | | | | | | --54.65%--PyEval_EvalCode | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | | | | | |--51.67%--_PyEval_EvalFrameDefault | | | | | | | | | |--11.52%--_PyLong_Add | | | | | | | | | | | |--2.97%--_PyObject_Malloc ... As you can see, the Python functions are not shown in the output, only ``_PyEval_EvalFrameDefault`` (the function that evaluates the Python bytecode) shows up. Unfortunately that's not very useful because all Python functions use the same C function to evaluate bytecode so we cannot know which Python function corresponds to which bytecode-evaluating function. Instead, if we run the same experiment with ``perf`` support enabled we get: .. code-block:: shell-session $ perf report --stdio -n -g # Children Self Samples Command Shared Object Symbol # ........ ........ ............ .......... .................. ..................................................................... # 90.58% 0.36% 1 python.exe python.exe [.] _start | ---_start | --89.86%--__libc_start_main Py_BytesMain | |--55.43%--pymain_run_python.constprop.0 | | | |--54.71%--_PyRun_AnyFileObject | | _PyRun_SimpleFileObject | | | | | |--53.62%--run_mod | | | | | | | --53.26%--PyEval_EvalCode | | | py:::/src/script.py | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | py::baz:/src/script.py | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | py::bar:/src/script.py | | | _PyEval_EvalFrameDefault | | | PyObject_Vectorcall | | | _PyEval_Vector | | | py::foo:/src/script.py | | | | | | | |--51.81%--_PyEval_EvalFrameDefault | | | | | | | | | |--13.77%--_PyLong_Add | | | | | | | | | | | |--3.26%--_PyObject_Malloc ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/perf_profiling.rst#codepoints:51:7831"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/perf_profiling.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-perf_profiling.rst-2,dp-Python-howto-perf_profiling.rst,"How to enable ``perf`` profiling support ---------------------------------------- ``perf`` profiling support can be enabled either from the start using the environment variable :envvar:`PYTHONPERFSUPPORT` or the :option:`-X perf <-X>` option, or dynamically using :func:`sys.activate_stack_trampoline` and :func:`sys.deactivate_stack_trampoline`. The :mod:`!sys` functions take precedence over the :option:`!-X` option, the :option:`!-X` option takes precedence over the environment variable. Example, using the environment variable:: $ PYTHONPERFSUPPORT=1 perf record -F 9999 -g -o perf.data python script.py $ perf report -g -i perf.data Example, using the :option:`!-X` option:: $ perf record -F 9999 -g -o perf.data python -X perf script.py $ perf report -g -i perf.data Example, using the :mod:`sys` APIs in file :file:`example.py`: .. code-block:: python import sys sys.activate_stack_trampoline(""perf"") do_profiled_stuff() sys.deactivate_stack_trampoline() non_profiled_stuff() ...then:: $ perf record -F 9999 -g -o perf.data python ./example.py $ perf report -g -i perf.data How to obtain the best results ------------------------------ For best results, Python should be compiled with ``CFLAGS=""-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer""`` as this allows profilers to unwind using only the frame pointer and not on DWARF debug information. This is because as the code that is interposed to allow ``perf`` support is dynamically generated it doesn't have any DWARF debugging information available. You can check if your system has been compiled with this flag by running:: $ python -m sysconfig | grep 'no-omit-frame-pointer' If you don't see any output it means that your interpreter has not been compiled with frame pointers and therefore it may not be able to show Python functions in the output of ``perf``. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/perf_profiling.rst#codepoints:7831:9720"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/perf_profiling.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-perf_profiling.rst-3,dp-Python-howto-perf_profiling.rst,"How to work without frame pointers ---------------------------------- If you are working with a Python interpreter that has been compiled without frame pointers, you can still use the ``perf`` profiler, but the overhead will be a bit higher because Python needs to generate unwinding information for every Python function call on the fly. Additionally, ``perf`` will take more time to process the data because it will need to use the DWARF debugging information to unwind the stack and this is a slow process. To enable this mode, you can use the environment variable :envvar:`PYTHON_PERF_JIT_SUPPORT` or the :option:`-X perf_jit <-X>` option, which will enable the JIT mode for the ``perf`` profiler. .. note:: Due to a bug in the ``perf`` tool, only ``perf`` versions higher than v6.8 will work with the JIT mode. The fix was also backported to the v6.7.2 version of the tool. Note that when checking the version of the ``perf`` tool (which can be done by running ``perf version``) you must take into account that some distros add some custom version numbers including a ``-`` character. This means that ``perf 6.7-3`` is not necessarily ``perf 6.7.3``. When using the perf JIT mode, you need an extra step before you can run ``perf report``. You need to call the ``perf inject`` command to inject the JIT information into the ``perf.data`` file.:: $ perf record -F 9999 -g --call-graph dwarf -o perf.data python -Xperf_jit my_script.py $ perf inject -i perf.data --jit --output perf.jit.data $ perf report -g -i perf.jit.data or using the environment variable:: $ PYTHON_PERF_JIT_SUPPORT=1 perf record -F 9999 -g --call-graph dwarf -o perf.data python my_script.py $ perf inject -i perf.data --jit --output perf.jit.data $ perf report -g -i perf.jit.data ``perf inject --jit`` command will read ``perf.data``, automatically pick up the perf dump file that Python creates (in ``/tmp/perf-$PID.dump``), and then create ``perf.jit.data`` which merges all the JIT information together. It should also create a lot of ``jitted-XXXX-N.so`` files in the current directory which are ELF images for all the JIT trampolines that were created by Python. .. warning:: Notice that when using ``--call-graph dwarf`` the ``perf`` tool will take snapshots of the stack of the process being profiled and save the information in the ``perf.data`` file. By default the size of the stack dump is 8192 bytes but the user can change the size by passing the size after comma like ``--call-graph dwarf,4096``. The size of the stack dump is important because if the size is too small ``perf`` will not be able to unwind the stack and the output will be incomplete. On the other hand, if the size is too big, then ``perf`` won't be able to sample the process as frequently as it would like as the overhead will be higher. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/perf_profiling.rst#codepoints:9720:12621"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/perf_profiling.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-howto-perf_profiling.rst-2,dp-Python-howto-perf_profiling.rst,"How to enable ``perf`` profiling support ---------------------------------------- ``perf`` profiling support can be enabled either from the start using the environment variable :envvar:`PYTHONPERFSUPPORT` or the :option:`-X perf <-X>` option, or dynamically using :func:`sys.activate_stack_trampoline` and :func:`sys.deactivate_stack_trampoline`. The :mod:`!sys` functions take precedence over the :option:`!-X` option, the :option:`!-X` option takes precedence over the environment variable. Example, using the environment variable:: $ PYTHONPERFSUPPORT=1 python script.py $ perf report -g -i perf.data Example, using the :option:`!-X` option:: $ python -X perf script.py $ perf report -g -i perf.data Example, using the :mod:`sys` APIs in file :file:`example.py`: .. code-block:: python import sys sys.activate_stack_trampoline(""perf"") do_profiled_stuff() sys.deactivate_stack_trampoline() non_profiled_stuff() ...then:: $ python ./example.py $ perf report -g -i perf.data How to obtain the best results ------------------------------ For best results, Python should be compiled with ``CFLAGS=""-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer""`` as this allows profilers to unwind using only the frame pointer and not on DWARF debug information. This is because as the code that is interposed to allow ``perf`` support is dynamically generated it doesn't have any DWARF debugging information available. You can check if your system has been compiled with this flag by running:: $ python -m sysconfig | grep 'no-omit-frame-pointer' If you don't see any output it means that your interpreter has not been compiled with frame pointers and therefore it may not be able to show Python functions in the output of ``perf``. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/howto/perf_profiling.rst#codepoints:7831:9610"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:howto/perf_profiling.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-howto-sockets.rst-0,dp-Python-howto-sockets.rst,".. _socket-howto: **************************** Socket Programming HOWTO **************************** :Author: Gordon McMillan .. topic:: Abstract Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It's not really a tutorial - you'll still have work to do in getting things operational. It doesn't cover the fine points (and there are a lot of them), but I hope it will give you enough background to begin using them decently. Sockets ======= I'm only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of the sockets in use. And I'll only talk about STREAM (i.e. TCP) sockets - unless you really know what you're doing (in which case this HOWTO isn't for you!), you'll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I'll start by talking about blocking sockets. You'll need to know how they work before dealing with non-blocking sockets. Part of the trouble with understanding these things is that ""socket"" can mean a number of subtly different things, depending on context. So first, let's make a distinction between a ""client"" socket - an endpoint of a conversation, and a ""server"" socket, which is more like a switchboard operator. The client application (your browser, for example) uses ""client"" sockets exclusively; the web server it's talking to uses both ""server"" sockets and ""client"" sockets. History ------- Of the various forms of :abbr:`IPC (Inter Process Communication)`, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town. They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the internet. With good reason --- the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy (at least compared to other schemes). ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/sockets.rst#codepoints:0:2185"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/sockets.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-sockets.rst-1,dp-Python-howto-sockets.rst,"Creating a Socket ================= Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following:: # create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # now connect to the web server on port 80 - the normal http port s.connect((""www.python.org"", 80)) When the ``connect`` completes, the socket ``s`` can be used to send in a request for the text of the page. The same socket will read the reply, and then be destroyed. That's right, destroyed. Client sockets are normally only used for one exchange (or a small set of sequential exchanges). What happens in the web server is a bit more complex. First, the web server creates a ""server socket"":: # create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host, and a well-known port serversocket.bind((socket.gethostname(), 80)) # become a server socket serversocket.listen(5) A couple things to notice: we used ``socket.gethostname()`` so that the socket would be visible to the outside world. If we had used ``s.bind(('localhost', 80))`` or ``s.bind(('127.0.0.1', 80))`` we would still have a ""server"" socket, but one that was only visible within the same machine. ``s.bind(('', 80))`` specifies that the socket is reachable by any address the machine happens to have. A second thing to note: low number ports are usually reserved for ""well known"" services (HTTP, SNMP etc). If you're playing around, use a nice high number (4 digits). Finally, the argument to ``listen`` tells the socket library that we want it to queue up as many as 5 connect requests (the normal max) before refusing outside connections. If the rest of the code is written properly, that should be plenty. Now that we have a ""server"" socket, listening on port 80, we can enter the mainloop of the web server:: while True: # accept connections from outside (clientsocket, address) = serversocket.accept() # now do something with the clientsocket # in this case, we'll pretend this is a threaded server ct = client_thread(clientsocket) ct.run() There's actually 3 general ways in which this loop could work - dispatching a thread to handle ``clientsocket``, create a new process to handle ``clientsocket``, or restructure this app to use non-blocking sockets, and multiplex between our ""server"" socket and any active ``clientsocket``\ s using ``select``. More about that later. The important thing to understand now is this: this is *all* a ""server"" socket does. It doesn't send any data. It doesn't receive any data. It just produces ""client"" sockets. Each ``clientsocket`` is created in response to some *other* ""client"" socket doing a ``connect()`` to the host and port we're bound to. As soon as we've created that ``clientsocket``, we go back to listening for more connections. The two ""clients"" are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends. IPC --- If you need fast IPC between two processes on one machine, you should look into pipes or shared memory. If you do decide to use AF_INET sockets, bind the ""server"" socket to ``'localhost'``. On most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster. .. seealso:: The :mod:`multiprocessing` integrates cross-platform IPC into a higher-level API. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/sockets.rst#codepoints:2185:5708"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/sockets.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-sockets.rst-2,dp-Python-howto-sockets.rst,"Using a Socket ============== The first thing to note, is that the web browser's ""client"" socket and the web server's ""client"" socket are identical beasts. That is, this is a ""peer to peer"" conversation. Or to put it another way, *as the designer, you will have to decide what the rules of etiquette are for a conversation*. Normally, the ``connect``\ ing socket starts the conversation, by sending in a request, or perhaps a signon. But that's a design decision - it's not a rule of sockets. Now there are two sets of verbs to use for communication. You can use ``send`` and ``recv``, or you can transform your client socket into a file-like beast and use ``read`` and ``write``. The latter is the way Java presents its sockets. I'm not going to talk about it here, except to warn you that you need to use ``flush`` on sockets. These are buffered ""files"", and a common mistake is to ``write`` something, and then ``read`` for a reply. Without a ``flush`` in there, you may wait forever for the reply, because the request may still be in your output buffer. Now we come to the major stumbling block of sockets - ``send`` and ``recv`` operate on the network buffers. They do not necessarily handle all the bytes you hand them (or expect from them), because their major focus is handling the network buffers. In general, they return when the associated network buffers have been filled (``send``) or emptied (``recv``). They then tell you how many bytes they handled. It is *your* responsibility to call them again until your message has been completely dealt with. When a ``recv`` returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I'll talk more about this later. A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That's it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes. But if you plan to reuse your socket for further transfers, you need to realize that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket ``send`` or ``recv`` returns after handling 0 bytes, the connection has been broken. If the connection has *not* been broken, you may wait on a ``recv`` forever, because the socket will *not* tell you that there's nothing more to read (for now). Now if you think about that a bit, you'll come to realize a fundamental truth of sockets: *messages must either be fixed length* (yuck), *or be delimited* (shrug), *or indicate how long they are* (much better), *or end by shutting down the connection*. The choice is entirely yours, (but some ways are righter than others). Assuming you don't want to end the connection, the simplest solution is a fixed length message:: class MySocket: """"""demonstration class only - coded for clarity, not efficiency """""" def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError(""socket connection broken"") totalsent = totalsent + sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN: chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError(""socket connection broken"") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return b''.join(chunks) The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use ``len()`` to determine its length (even if it has embedded ``\0`` characters). It's mostly the receiving code that gets more complex. (And in C, it's not much worse, except you can't use ``strlen`` if the message has embedded ``\0``\ s.) The easiest enhancement is to make the first character of the message an indicator of message type, and have the type determine the length. Now you have two ``recv``\ s - the first to get (at least) that first character so you can look up the length, and the second in a loop to get the rest. If you decide to go the delimited route, you'll be receiving in some arbitrary chunk size, (4096 or 8192 is frequently a good match for network buffer sizes), and scanning what you've received for a delimiter. One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass ``recv`` an arbitrary chunk size, you may end up reading the start of a following message. You'll need to put that aside and hold onto it, until it's needed. Prefixing the message with its length (say, as 5 numeric characters) gets more complex, because (believe it or not), you may not get all 5 characters in one ``recv``. In playing around, you'll get away with it; but in high network loads, your code will very quickly break unless you use two ``recv`` loops - the first to determine the length, the second to get the data part of the message. Nasty. This is also when you'll discover that ``send`` does not always manage to get rid of everything in one pass. And despite having read this, you will eventually get bit by it! In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/sockets.rst#codepoints:5708:11631"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/sockets.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-sockets.rst-3,dp-Python-howto-sockets.rst,"Binary Data ----------- It is perfectly possible to send binary data over a socket. The major problem is that not all machines use the same formats for binary data. For example, `network byte order `_ is big-endian, with the most significant byte first, so a 16 bit integer with the value ``1`` would be the two hex bytes ``00 01``. However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian, with the least significant byte first - that same ``1`` would be ``01 00``. Socket libraries have calls for converting 16 and 32 bit integers - ``ntohl, htonl, ntohs, htons`` where ""n"" means *network* and ""h"" means *host*, ""s"" means *short* and ""l"" means *long*. Where network order is host order, these do nothing, but where the machine is byte-reversed, these swap the bytes around appropriately. In these days of 64-bit machines, the ASCII representation of binary data is frequently smaller than the binary representation. That's because a surprising amount of the time, most integers have the value 0, or maybe 1. The string ``""0""`` would be two bytes, while a full 64-bit integer would be 8. Of course, this doesn't fit well with fixed-length messages. Decisions, decisions. Disconnecting ============= Strictly speaking, you're supposed to use ``shutdown`` on a socket before you ``close`` it. The ``shutdown`` is an advisory to the socket at the other end. Depending on the argument you pass it, it can mean ""I'm not going to send anymore, but I'll still listen"", or ""I'm not listening, good riddance!"". Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a ``close`` is the same as ``shutdown(); close()``. So in most situations, an explicit ``shutdown`` is not needed. One way to use ``shutdown`` effectively is in an HTTP-like exchange. The client sends a request and then does a ``shutdown(1)``. This tells the server ""This client is done sending, but can still receive."" The server can detect ""EOF"" by a receive of 0 bytes. It can assume it has the complete request. The server sends a reply. If the ``send`` completes successfully then, indeed, the client was still receiving. Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a ``close`` if it's needed. But relying on this is a very bad habit. If your socket just disappears without doing a ``close``, the socket at the other end may hang indefinitely, thinking you're just being slow. *Please* ``close`` your sockets when you're done. When Sockets Die ---------------- Probably the worst thing about using blocking sockets is what happens when the other side comes down hard (without doing a ``close``). Your socket is likely to hang. TCP is a reliable protocol, and it will wait a long, long time before giving up on a connection. If you're using threads, the entire thread is essentially dead. There's not much you can do about it. As long as you aren't doing something dumb, like holding a lock while doing a blocking read, the thread isn't really consuming much in the way of resources. Do *not* try to kill the thread - part of the reason that threads are more efficient than processes is that they avoid the overhead associated with the automatic recycling of resources. In other words, if you do manage to kill the thread, your whole process is likely to be screwed up. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/sockets.rst#codepoints:11631:15096"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/sockets.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-howto-sockets.rst-4,dp-Python-howto-sockets.rst,"Non-blocking Sockets ==================== If you've understood the preceding, you already know most of what you need to know about the mechanics of using sockets. You'll still use the same calls, in much the same ways. It's just that, if you do it right, your app will be almost inside-out. In Python, you use ``socket.setblocking(False)`` to make it non-blocking. In C, it's more complex, (for one thing, you'll need to choose between the BSD flavor ``O_NONBLOCK`` and the almost indistinguishable POSIX flavor ``O_NDELAY``, which is completely different from ``TCP_NODELAY``), but it's the exact same idea. You do this after creating the socket, but before using it. (Actually, if you're nuts, you can switch back and forth.) The major mechanical difference is that ``send``, ``recv``, ``connect`` and ``accept`` can return without having done anything. You have (of course) a number of choices. You can check return code and error codes and generally drive yourself crazy. If you don't believe me, try it sometime. Your app will grow large, buggy and suck CPU. So let's skip the brain-dead solutions and do it right. Use ``select``. In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but it's close enough to the C version that if you understand ``select`` in Python, you'll have little trouble with it in C:: ready_to_read, ready_to_write, in_error = \ select.select( potential_readers, potential_writers, potential_errs, timeout) You pass ``select`` three lists: the first contains all sockets that you might want to try reading; the second all the sockets you might want to try writing to, and the last (normally left empty) those that you want to check for errors. You should note that a socket can go into more than one list. The ``select`` call is blocking, but you can give it a timeout. This is generally a sensible thing to do - give it a nice long timeout (say a minute) unless you have good reason to do otherwise. In return, you will get three lists. They contain the sockets that are actually readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in. If a socket is in the output readable list, you can be as-close-to-certain-as-we-ever-get-in-this-business that a ``recv`` on that socket will return *something*. Same idea for the writable list. You'll be able to send *something*. Maybe not all you want to, but *something* is better than nothing. (Actually, any reasonably healthy socket will return as writable - it just means outbound network buffer space is available.) If you have a ""server"" socket, put it in the potential_readers list. If it comes out in the readable list, your ``accept`` will (almost certainly) work. If you have created a new socket to ``connect`` to someone else, put it in the potential_writers list. If it shows up in the writable list, you have a decent chance that it has connected. Actually, ``select`` can be handy even with blocking sockets. It's one way of determining whether you will block - the socket returns as readable when there's something in the buffers. However, this still doesn't help with the problem of determining whether the other end is done, or just busy with something else. **Portability alert**: On Unix, ``select`` works both with the sockets and files. Don't try this on Windows. On Windows, ``select`` works with sockets only. Also note that in C, many of the more advanced socket options are done differently on Windows. In fact, on Windows I usually use threads (which work very, very well) with my sockets. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/howto/sockets.rst#codepoints:15096:18795"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:howto/sockets.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-library-aifc.rst-0,dp-Python-library-aifc.rst,":mod:`aifc` --- Read and write AIFF and AIFC files ================================================== .. module:: aifc :synopsis: Read and write audio files in AIFF or AIFC format. :deprecated: **Source code:** :source:`Lib/aifc.py` .. index:: single: Audio Interchange File Format single: AIFF single: AIFF-C .. deprecated-removed:: 3.11 3.13 The :mod:`aifc` module is deprecated (see :pep:`PEP 594 <594#aifc>` for details). -------------- This module provides support for reading and writing AIFF and AIFF-C files. AIFF is Audio Interchange File Format, a format for storing digital audio samples in a file. AIFF-C is a newer version of the format that includes the ability to compress the audio data. Audio files have a number of parameters that describe the audio data. The sampling rate or frame rate is the number of times per second the sound is sampled. The number of channels indicate if the audio is mono, stereo, or quadro. Each frame consists of one sample per channel. The sample size is the size in bytes of each sample. Thus a frame consists of ``nchannels * samplesize`` bytes, and a second's worth of audio consists of ``nchannels * samplesize * framerate`` bytes. For example, CD quality audio has a sample size of two bytes (16 bits), uses two channels (stereo) and has a frame rate of 44,100 frames/second. This gives a frame size of 4 bytes (2\*2), and a second's worth occupies 2\*2\*44100 bytes (176,400 bytes). Module :mod:`aifc` defines the following function: .. function:: open(file, mode=None) Open an AIFF or AIFF-C file and return an object instance with methods that are described below. The argument *file* is either a string naming a file or a :term:`file object`. *mode* must be ``'r'`` or ``'rb'`` when the file must be opened for reading, or ``'w'`` or ``'wb'`` when the file must be opened for writing. If omitted, ``file.mode`` is used if it exists, otherwise ``'rb'`` is used. When used for writing, the file object should be seekable, unless you know ahead of time how many samples you are going to write in total and use :meth:`writeframesraw` and :meth:`setnframes`. The :func:`.open` function may be used in a :keyword:`with` statement. When the :keyword:`!with` block completes, the :meth:`~aifc.close` method is called. .. versionchanged:: 3.4 Support for the :keyword:`with` statement was added. Objects returned by :func:`.open` when a file is opened for reading have the following methods: .. method:: aifc.getnchannels() Return the number of audio channels (1 for mono, 2 for stereo). .. method:: aifc.getsampwidth() Return the size in bytes of individual samples. .. method:: aifc.getframerate() Return the sampling rate (number of audio frames per second). .. method:: aifc.getnframes() Return the number of audio frames in the file. .. method:: aifc.getcomptype() Return a bytes array of length 4 describing the type of compression used in the audio file. For AIFF files, the returned value is ``b'NONE'``. .. method:: aifc.getcompname() Return a bytes array convertible to a human-readable description of the type of compression used in the audio file. For AIFF files, the returned value is ``b'not compressed'``. .. method:: aifc.getparams() Returns a :func:`~collections.namedtuple` ``(nchannels, sampwidth, framerate, nframes, comptype, compname)``, equivalent to output of the :meth:`get\*` methods. .. method:: aifc.getmarkers() Return a list of markers in the audio file. A marker consists of a tuple of three elements. The first is the mark ID (an integer), the second is the mark position in frames from the beginning of the data (an integer), the third is the name of the mark (a string). .. method:: aifc.getmark(id) Return the tuple as described in :meth:`getmarkers` for the mark with the given *id*. .. method:: aifc.readframes(nframes) Read and return the next *nframes* frames from the audio file. The returned data is a string containing for each frame the uncompressed samples of all channels. .. method:: aifc.rewind() Rewind the read pointer. The next :meth:`readframes` will start from the beginning. .. method:: aifc.setpos(pos) Seek to the specified frame number. .. method:: aifc.tell() Return the current frame number. .. method:: aifc.close() Close the AIFF file. After calling this method, the object can no longer be used. Objects returned by :func:`.open` when a file is opened for writing have all the above methods, except for :meth:`readframes` and :meth:`setpos`. In addition the following methods exist. The :meth:`get\*` methods can only be called after the corresponding :meth:`set\*` methods have been called. Before the first :meth:`writeframes` or :meth:`writeframesraw`, all parameters except for the number of frames must be filled in. .. method:: aifc.aiff() Create an AIFF file. The default is that an AIFF-C file is created, unless the name of the file ends in ``'.aiff'`` in which case the default is an AIFF file. .. method:: aifc.aifc() Create an AIFF-C file. The default is that an AIFF-C file is created, unless the name of the file ends in ``'.aiff'`` in which case the default is an AIFF file. .. method:: aifc.setnchannels(nchannels) Specify the number of channels in the audio file. .. method:: aifc.setsampwidth(width) Specify the size in bytes of audio samples. .. method:: aifc.setframerate(rate) Specify the sampling frequency in frames per second. .. method:: aifc.setnframes(nframes) Specify the number of frames that are to be written to the audio file. If this parameter is not set, or not set correctly, the file needs to support seeking. .. method:: aifc.setcomptype(type, name) .. index:: single: u-LAW single: A-LAW single: G.722 Specify the compression type. If not specified, the audio data will not be compressed. In AIFF files, compression is not possible. The name parameter should be a human-readable description of the compression type as a bytes array, the type parameter should be a bytes array of length 4. Currently the following compression types are supported: ``b'NONE'``, ``b'ULAW'``, ``b'ALAW'``, ``b'G722'``. .. method:: aifc.setparams(nchannels, sampwidth, framerate, comptype, compname) Set all the above parameters at once. The argument is a tuple consisting of the various parameters. This means that it is possible to use the result of a :meth:`getparams` call as argument to :meth:`setparams`. .. method:: aifc.setmark(id, pos, name) Add a mark with the given id (larger than 0), and the given name at the given position. This method can be called at any time before :meth:`close`. .. method:: aifc.tell() :noindex: Return the current write position in the output file. Useful in combination with :meth:`setmark`. .. method:: aifc.writeframes(data) Write data to the output file. This method can only be called after the audio file parameters have been set. .. versionchanged:: 3.4 Any :term:`bytes-like object` is now accepted. .. method:: aifc.writeframesraw(data) Like :meth:`writeframes`, except that the header of the audio file is not updated. .. versionchanged:: 3.4 Any :term:`bytes-like object` is now accepted. .. method:: aifc.close() :noindex: Close the AIFF file. The header of the file is updated to reflect the actual size of the audio data. After calling this method, the object can no longer be used. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/aifc.rst#codepoints:0:7670"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/aifc.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-0,dp-Python-library-email.policy.rst,":mod:`!email.policy`: Policy Objects ------------------------------------ .. module:: email.policy :synopsis: Controlling the parsing and generating of messages .. moduleauthor:: R. David Murray .. sectionauthor:: R. David Murray .. versionadded:: 3.3 **Source code:** :source:`Lib/email/policy.py` -------------- The :mod:`email` package's prime focus is the handling of email messages as described by the various email and MIME RFCs. However, the general format of email messages (a block of header fields each consisting of a name followed by a colon followed by a value, the whole block followed by a blank line and an arbitrary 'body'), is a format that has found utility outside of the realm of email. Some of these uses conform fairly closely to the main email RFCs, some do not. Even when working with email, there are times when it is desirable to break strict compliance with the RFCs, such as generating emails that interoperate with email servers that do not themselves follow the standards, or that implement extensions you want to use in ways that violate the standards. Policy objects give the email package the flexibility to handle all these disparate use cases. A :class:`Policy` object encapsulates a set of attributes and methods that control the behavior of various components of the email package during use. :class:`Policy` instances can be passed to various classes and methods in the email package to alter the default behavior. The settable values and their defaults are described below. There is a default policy used by all classes in the email package. For all of the :mod:`~email.parser` classes and the related convenience functions, and for the :class:`~email.message.Message` class, this is the :class:`Compat32` policy, via its corresponding pre-defined instance :const:`compat32`. This policy provides for complete backward compatibility (in some cases, including bug compatibility) with the pre-Python3.3 version of the email package. This default value for the *policy* keyword to :class:`~email.message.EmailMessage` is the :class:`EmailPolicy` policy, via its pre-defined instance :data:`~default`. When a :class:`~email.message.Message` or :class:`~email.message.EmailMessage` object is created, it acquires a policy. If the message is created by a :mod:`~email.parser`, a policy passed to the parser will be the policy used by the message it creates. If the message is created by the program, then the policy can be specified when it is created. When a message is passed to a :mod:`~email.generator`, the generator uses the policy from the message by default, but you can also pass a specific policy to the generator that will override the one stored on the message object. The default value for the *policy* keyword for the :mod:`email.parser` classes and the parser convenience functions **will be changing** in a future version of Python. Therefore you should **always specify explicitly which policy you want to use** when calling any of the classes and functions described in the :mod:`~email.parser` module. The first part of this documentation covers the features of :class:`Policy`, an :term:`abstract base class` that defines the features that are common to all policy objects, including :const:`compat32`. This includes certain hook methods that are called internally by the email package, which a custom policy could override to obtain different behavior. The second part describes the concrete classes :class:`EmailPolicy` and :class:`Compat32`, which implement the hooks that provide the standard behavior and the backward compatible behavior and features, respectively. :class:`Policy` instances are immutable, but they can be cloned, accepting the same keyword arguments as the class constructor and returning a new :class:`Policy` instance that is a copy of the original but with the specified attributes values changed. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:0:3956"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-1,dp-Python-library-email.policy.rst,"behavior and features, respectively. :class:`Policy` instances are immutable, but they can be cloned, accepting the same keyword arguments as the class constructor and returning a new :class:`Policy` instance that is a copy of the original but with the specified attributes values changed. As an example, the following code could be used to read an email message from a file on disk and pass it to the system ``sendmail`` program on a Unix system: .. testsetup:: from unittest import mock mocker = mock.patch('subprocess.Popen') m = mocker.start() proc = mock.MagicMock() m.return_value = proc proc.stdin.close.return_value = None mymsg = open('mymsg.txt', 'w') mymsg.write('To: abc@xyz.com\n\n') mymsg.flush() .. doctest:: >>> from email import message_from_binary_file >>> from email.generator import BytesGenerator >>> from email import policy >>> from subprocess import Popen, PIPE >>> with open('mymsg.txt', 'rb') as f: ... msg = message_from_binary_file(f, policy=policy.default) ... >>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE) >>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n')) >>> g.flatten(msg) >>> p.stdin.close() >>> rc = p.wait() .. testcleanup:: mymsg.close() mocker.stop() import os os.remove('mymsg.txt') Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC correct line separator characters when creating the binary string to feed into ``sendmail's`` ``stdin``, where the default policy would use ``\n`` line separators. Some email package methods accept a *policy* keyword argument, allowing the policy to be overridden for that method. For example, the following code uses the :meth:`~email.message.Message.as_bytes` method of the *msg* object from the previous example and writes the message to a file using the native line separators for the platform on which it is running:: >>> import os >>> with open('converted.txt', 'wb') as f: ... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep))) 17 Policy objects can also be combined using the addition operator, producing a policy object whose settings are a combination of the non-default values of the summed objects:: >>> compat_SMTP = policy.compat32.clone(linesep='\r\n') >>> compat_strict = policy.compat32.clone(raise_on_defect=True) >>> compat_strict_SMTP = compat_SMTP + compat_strict This operation is not commutative; that is, the order in which the objects are added matters. To illustrate:: >>> policy100 = policy.compat32.clone(max_line_length=100) >>> policy80 = policy.compat32.clone(max_line_length=80) >>> apolicy = policy100 + policy80 >>> apolicy.max_line_length 80 >>> apolicy = policy80 + policy100 >>> apolicy.max_line_length 100 .. class:: Policy(**kw) This is the :term:`abstract base class` for all policy classes. It provides default implementations for a couple of trivial methods, as well as the implementation of the immutability property, the :meth:`clone` method, and the constructor semantics. The constructor of a policy class can be passed various keyword arguments. The arguments that may be specified are any non-method properties on this class, plus any additional non-method properties on the concrete class. A value specified in the constructor will override the default value for the corresponding attribute. This class defines the following properties, and thus values for the following may be passed in the constructor of any policy class: .. attribute:: max_line_length The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per :rfc:`5322`. A value of ``0`` or :const:`None` indicates that no line wrapping should be done at all. .. attribute:: linesep ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:3664:7590"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-2,dp-Python-library-email.policy.rst," The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per :rfc:`5322`. A value of ``0`` or :const:`None` indicates that no line wrapping should be done at all. .. attribute:: linesep The string to be used to terminate lines in serialized output. The default is ``\n`` because that's the internal end-of-line discipline used by Python, though ``\r\n`` is required by the RFCs. .. attribute:: cte_type Controls the type of Content Transfer Encodings that may be or are required to be used. The possible values are: .. tabularcolumns:: |l|L| ======== =============================================================== ``7bit`` all data must be ""7 bit clean"" (ASCII-only). This means that where necessary data will be encoded using either quoted-printable or base64 encoding. ``8bit`` data is not constrained to be 7 bit clean. Data in headers is still required to be ASCII-only and so will be encoded (see :meth:`fold_binary` and :attr:`~EmailPolicy.utf8` below for exceptions), but body parts may use the ``8bit`` CTE. ======== =============================================================== A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not ``Generator``, because strings cannot contain binary data. If a ``Generator`` is operating under a policy that specifies ``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``. .. attribute:: raise_on_defect If :const:`True`, any defects encountered will be raised as errors. If :const:`False` (the default), defects will be passed to the :meth:`register_defect` method. .. attribute:: mangle_from_ If :const:`True`, lines starting with *""From ""* in the body are escaped by putting a ``>`` in front of them. This parameter is used when the message is being serialized by a generator. Default: :const:`False`. .. versionadded:: 3.5 .. attribute:: message_factory A factory function for constructing a new empty message object. Used by the parser when building messages. Defaults to ``None``, in which case :class:`~email.message.Message` is used. .. versionadded:: 3.6 .. attribute:: verify_generated_headers If ``True`` (the default), the generator will raise :exc:`~email.errors.HeaderWriteError` instead of writing a header that is improperly folded or delimited, such that it would be parsed as multiple headers or joined with adjacent data. Such headers can be generated by custom header classes or bugs in the ``email`` module. As it's a security feature, this defaults to ``True`` even in the :class:`~email.policy.Compat32` policy. For backwards compatible, but unsafe, behavior, it must be set to ``False`` explicitly. .. versionadded:: 3.13 The following :class:`Policy` method is intended to be called by code using the email library to create policy instances with custom settings: .. method:: clone(**kw) Return a new :class:`Policy` instance whose attributes have the same values as the current instance, except where those attributes are given new values by the keyword arguments. The remaining :class:`Policy` methods are called by the email package code, and are not intended to be called by an application using the email package. A custom policy must implement all of these methods. .. method:: handle_defect(obj, defect) Handle a *defect* found on *obj*. When the email package calls this method, *defect* will always be a subclass of :class:`~email.errors.Defect`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:7313:11180"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-3,dp-Python-library-email.policy.rst," A custom policy must implement all of these methods. .. method:: handle_defect(obj, defect) Handle a *defect* found on *obj*. When the email package calls this method, *defect* will always be a subclass of :class:`~email.errors.Defect`. The default implementation checks the :attr:`raise_on_defect` flag. If it is ``True``, *defect* is raised as an exception. If it is ``False`` (the default), *obj* and *defect* are passed to :meth:`register_defect`. .. method:: register_defect(obj, defect) Register a *defect* on *obj*. In the email package, *defect* will always be a subclass of :class:`~email.errors.Defect`. The default implementation calls the ``append`` method of the ``defects`` attribute of *obj*. When the email package calls :attr:`handle_defect`, *obj* will normally have a ``defects`` attribute that has an ``append`` method. Custom object types used with the email package (for example, custom ``Message`` objects) should also provide such an attribute, otherwise defects in parsed messages will raise unexpected errors. .. method:: header_max_count(name) Return the maximum allowed number of headers named *name*. Called when a header is added to an :class:`~email.message.EmailMessage` or :class:`~email.message.Message` object. If the returned value is not ``0`` or ``None``, and there are already a number of headers with the name *name* greater than or equal to the value returned, a :exc:`ValueError` is raised. Because the default behavior of ``Message.__setitem__`` is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a ``Message`` programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns ``None`` for all header names. .. method:: header_source_parse(sourcelines) The email package calls this method with a list of strings, each string ending with the line separation characters found in the source being parsed. The first line includes the field header name and separator. All whitespace in the source is preserved. The method should return the ``(name, value)`` tuple that is to be stored in the ``Message`` to represent the parsed header. If an implementation wishes to retain compatibility with the existing email package policies, *name* should be the case preserved name (all characters up to the '``:``' separator), while *value* should be the unfolded value (all line separator characters removed, but whitespace kept intact), stripped of leading whitespace. *sourcelines* may contain surrogateescaped binary data. There is no default implementation .. method:: header_store_parse(name, value) The email package calls this method with the name and value provided by the application program when the application program is modifying a ``Message`` programmatically (as opposed to a ``Message`` created by a parser). The method should return the ``(name, value)`` tuple that is to be stored in the ``Message`` to represent the header. If an implementation wishes to retain compatibility with the existing email package policies, the *name* and *value* should be strings or string subclasses that do not change the content of the passed in arguments. There is no default implementation .. method:: header_fetch_parse(name, value) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:10914:14730"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-4,dp-Python-library-email.policy.rst," email package policies, the *name* and *value* should be strings or string subclasses that do not change the content of the passed in arguments. There is no default implementation .. method:: header_fetch_parse(name, value) The email package calls this method with the *name* and *value* currently stored in the ``Message`` when that header is requested by the application program, and whatever the method returns is what is passed back to the application as the value of the header being retrieved. Note that there may be more than one header with the same name stored in the ``Message``; the method is passed the specific name and value of the header destined to be returned to the application. *value* may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the value returned by the method. There is no default implementation .. method:: fold(name, value) The email package calls this method with the *name* and *value* currently stored in the ``Message`` for a given header. The method should return a string that represents that header ""folded"" correctly (according to the policy settings) by composing the *name* with the *value* and inserting :attr:`linesep` characters at the appropriate places. See :rfc:`5322` for a discussion of the rules for folding email headers. *value* may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the string returned by the method. .. method:: fold_binary(name, value) The same as :meth:`fold`, except that the returned value should be a bytes object rather than a string. *value* may contain surrogateescaped binary data. These could be converted back into binary data in the returned bytes object. .. class:: EmailPolicy(**kw) This concrete :class:`Policy` provides behavior that is intended to be fully compliant with the current email RFCs. These include (but are not limited to) :rfc:`5322`, :rfc:`2047`, and the current MIME RFCs. This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are ``str`` subclasses with attributes that depend on the type of the field. The parsing and folding algorithm fully implement :rfc:`2047` and :rfc:`5322`. The default value for the :attr:`~email.policy.Policy.message_factory` attribute is :class:`~email.message.EmailMessage`. In addition to the settable attributes listed above that apply to all policies, this policy adds the following additional attributes: .. versionadded:: 3.6 [1]_ .. attribute:: utf8 If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in headers by encoding them as ""encoded words"". If ``True``, follow :rfc:`6532` and use ``utf-8`` encoding for headers. Messages formatted in this way may be passed to SMTP servers that support the ``SMTPUTF8`` extension (:rfc:`6531`). .. attribute:: refold_source If the value for a header in the ``Message`` object originated from a :mod:`~email.parser` (as opposed to being set by a program), this attribute indicates whether or not a generator should refold that value when transforming the message back into serialized form. The possible values are: ======== =============================================================== ``none`` all source values use original folding ``long`` source values that have any line that is longer than ``max_line_length`` will be refolded ``all`` all values are refolded. ======== =============================================================== The default is ``long``. .. attribute:: header_factory ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:14475:18361"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-5,dp-Python-library-email.policy.rst," ``max_line_length`` will be refolded ``all`` all values are refolded. ======== =============================================================== The default is ``long``. .. attribute:: header_factory A callable that takes two arguments, ``name`` and ``value``, where ``name`` is a header field name and ``value`` is an unfolded header field value, and returns a string subclass that represents that header. A default ``header_factory`` (see :mod:`~email.headerregistry`) is provided that supports custom parsing for the various address and date :RFC:`5322` header field types, and the major MIME header field stypes. Support for additional custom parsing will be added in the future. .. attribute:: content_manager An object with at least two methods: get_content and set_content. When the :meth:`~email.message.EmailMessage.get_content` or :meth:`~email.message.EmailMessage.set_content` method of an :class:`~email.message.EmailMessage` object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. By default ``content_manager`` is set to :data:`~email.contentmanager.raw_data_manager`. .. versionadded:: 3.4 The class provides the following concrete implementations of the abstract methods of :class:`Policy`: .. method:: header_max_count(name) Returns the value of the :attr:`~email.headerregistry.BaseHeader.max_count` attribute of the specialized class used to represent the header with the given name. .. method:: header_source_parse(sourcelines) The name is parsed as everything up to the '``:``' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. .. method:: header_store_parse(name, value) The name is returned unchanged. If the input value has a ``name`` attribute and it matches *name* ignoring case, the value is returned unchanged. Otherwise the *name* and *value* are passed to ``header_factory``, and the resulting header object is returned as the value. In this case a ``ValueError`` is raised if the input value contains CR or LF characters. .. method:: header_fetch_parse(name, value) If the value has a ``name`` attribute, it is returned to unmodified. Otherwise the *name*, and the *value* with any CR or LF characters removed, are passed to the ``header_factory``, and the resulting header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph. .. method:: fold(name, value) Header folding is controlled by the :attr:`refold_source` policy setting. A value is considered to be a 'source value' if and only if it does not have a ``name`` attribute (having a ``name`` attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a header object by passing the *name* and the *value* with any CR and LF characters removed to the ``header_factory``. Folding of a header object is done by calling its ``fold`` method with the current policy. Source values are split into lines using :meth:`~str.splitlines`. If the value is not to be refolded, the lines are rejoined using the ``linesep`` from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the ``refold_source`` setting, which causes the binary data to be CTE encoded using the ``unknown-8bit`` charset. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:18118:22101"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-email.policy.rst-6,dp-Python-library-email.policy.rst," ``linesep`` from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the ``refold_source`` setting, which causes the binary data to be CTE encoded using the ``unknown-8bit`` charset. .. method:: fold_binary(name, value) The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except that the returned value is bytes. If :attr:`~Policy.cte_type` is ``8bit``, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the ``refold_header`` setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters. The following instances of :class:`EmailPolicy` provide defaults suitable for specific application domains. Note that in the future the behavior of these instances (in particular the ``HTTP`` instance) may be adjusted to conform even more closely to the RFCs relevant to their domains. .. data:: default An instance of ``EmailPolicy`` with all defaults unchanged. This policy uses the standard Python ``\n`` line endings rather than the RFC-correct ``\r\n``. .. data:: SMTP Suitable for serializing messages in conformance with the email RFCs. Like ``default``, but with ``linesep`` set to ``\r\n``, which is RFC compliant. .. data:: SMTPUTF8 The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``. Useful for serializing messages to a message store without using encoded words in the headers. Should only be used for SMTP transmission if the sender or recipient addresses have non-ASCII characters (the :meth:`smtplib.SMTP.send_message` method handles this automatically). .. data:: HTTP Suitable for serializing headers with for use in HTTP traffic. Like ``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited). .. data:: strict Convenience instance. The same as ``default`` except that ``raise_on_defect`` is set to ``True``. This allows any policy to be made strict by writing:: somepolicy + policy.strict With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API of the email package is changed from the Python 3.2 API in the following ways: * Setting a header on a :class:`~email.message.Message` results in that header being parsed and a header object created. * Fetching a header value from a :class:`~email.message.Message` results in that header being parsed and a header object created and returned. * Any header object, or any header that is refolded due to the policy settings, is folded using an algorithm that fully implements the RFC folding algorithms, including knowing where encoded words are required and allowed. From the application view, this means that any header obtained through the :class:`~email.message.EmailMessage` is a header object with extra attributes, whose string value is the fully decoded unicode value of the header. Likewise, a header may be assigned a new value, or a new header created, using a unicode string, and the policy will take care of converting the unicode string into the correct RFC encoded form. The header objects and their attributes are described in :mod:`~email.headerregistry`. .. class:: Compat32(**kw) This concrete :class:`Policy` is the backward compatibility policy. It replicates the behavior of the email package in Python 3.2. The :mod:`~email.policy` module also defines an instance of this class, :const:`compat32`, that is used as the default policy. Thus the default behavior of the email package is to maintain compatibility with Python 3.2. The following attributes have values that are different from the :class:`Policy` default: .. attribute:: mangle_from_ The default is ``True``. The class provides the following concrete implementations of the abstract methods of :class:`Policy`: .. method:: header_source_parse(sourcelines) The name is parsed as everything up to the '``:``' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. .. method:: header_store_parse(name, value) The name and value are returned unmodified. .. method:: header_fetch_parse(name, value) If the value contains binary data, it is converted into a :class:`~email.header.Header` object using the ``unknown-8bit`` charset. Otherwise it is returned unmodified. .. method:: fold(name, value) Headers are folded using the :class:`~email.header.Header` folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the ``max_line_length``. Non-ASCII binary data are CTE encoded using the ``unknown-8bit`` charset. .. method:: fold_binary(name, value) Headers are folded using the :class:`~email.header.Header` folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the ``max_line_length``. If ``cte_type`` is ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit`` charset. Otherwise the original source header is used, with its existing line breaks and any (RFC invalid) binary data it may contain. .. data:: compat32 An instance of :class:`Compat32`, providing backward compatibility with the behavior of the email package in Python 3.2. .. rubric:: Footnotes .. [1] Originally added in 3.3 as a :term:`provisional feature `. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/email.policy.rst#codepoints:21811:27621"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-library-email.policy.rst-2,dp-Python-library-email.policy.rst," The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per :rfc:`5322`. A value of ``0`` or :const:`None` indicates that no line wrapping should be done at all. .. attribute:: linesep The string to be used to terminate lines in serialized output. The default is ``\n`` because that's the internal end-of-line discipline used by Python, though ``\r\n`` is required by the RFCs. .. attribute:: cte_type Controls the type of Content Transfer Encodings that may be or are required to be used. The possible values are: .. tabularcolumns:: |l|L| ======== =============================================================== ``7bit`` all data must be ""7 bit clean"" (ASCII-only). This means that where necessary data will be encoded using either quoted-printable or base64 encoding. ``8bit`` data is not constrained to be 7 bit clean. Data in headers is still required to be ASCII-only and so will be encoded (see :meth:`fold_binary` and :attr:`~EmailPolicy.utf8` below for exceptions), but body parts may use the ``8bit`` CTE. ======== =============================================================== A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not ``Generator``, because strings cannot contain binary data. If a ``Generator`` is operating under a policy that specifies ``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``. .. attribute:: raise_on_defect If :const:`True`, any defects encountered will be raised as errors. If :const:`False` (the default), defects will be passed to the :meth:`register_defect` method. .. attribute:: mangle_from_ If :const:`True`, lines starting with *""From ""* in the body are escaped by putting a ``>`` in front of them. This parameter is used when the message is being serialized by a generator. Default: :const:`False`. .. versionadded:: 3.5 .. attribute:: message_factory A factory function for constructing a new empty message object. Used by the parser when building messages. Defaults to ``None``, in which case :class:`~email.message.Message` is used. .. versionadded:: 3.6 .. attribute:: verify_generated_headers If ``True`` (the default), the generator will raise :exc:`~email.errors.HeaderWriteError` instead of writing a header that is improperly folded or delimited, such that it would be parsed as multiple headers or joined with adjacent data. Such headers can be generated by custom header classes or bugs in the ``email`` module. As it's a security feature, this defaults to ``True`` even in the :class:`~email.policy.Compat32` policy. For backwards compatible, but unsafe, behavior, it must be set to ``False`` explicitly. .. versionadded:: 3.12.5 The following :class:`Policy` method is intended to be called by code using the email library to create policy instances with custom settings: .. method:: clone(**kw) Return a new :class:`Policy` instance whose attributes have the same values as the current instance, except where those attributes are given new values by the keyword arguments. The remaining :class:`Policy` methods are called by the email package code, and are not intended to be called by an application using the email package. A custom policy must implement all of these methods. .. method:: handle_defect(obj, defect) Handle a *defect* found on *obj*. When the email package calls this method, *defect* will always be a subclass of :class:`~email.errors.Defect`. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/email.policy.rst#codepoints:7313:11182"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/email.policy.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-library-errno.rst-0,dp-Python-library-errno.rst,":mod:`!errno` --- Standard errno system symbols =============================================== .. module:: errno :synopsis: Standard errno system symbols. ---------------- This module makes available standard ``errno`` system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from :file:`linux/include/errno.h`, which should be all-inclusive. .. data:: errorcode Dictionary providing a mapping from the errno value to the string name in the underlying system. For instance, ``errno.errorcode[errno.EPERM]`` maps to ``'EPERM'``. To translate a numeric error code to an error message, use :func:`os.strerror`. Of the following list, symbols that are not used on the current platform are not defined by the module. The specific list of defined symbols is available as ``errno.errorcode.keys()``. Symbols available can include: .. data:: EPERM Operation not permitted. This error is mapped to the exception :exc:`PermissionError`. .. data:: ENOENT No such file or directory. This error is mapped to the exception :exc:`FileNotFoundError`. .. data:: ESRCH No such process. This error is mapped to the exception :exc:`ProcessLookupError`. .. data:: EINTR Interrupted system call. This error is mapped to the exception :exc:`InterruptedError`. .. data:: EIO I/O error .. data:: ENXIO No such device or address .. data:: E2BIG Arg list too long .. data:: ENOEXEC Exec format error .. data:: EBADF Bad file number .. data:: ECHILD No child processes. This error is mapped to the exception :exc:`ChildProcessError`. .. data:: EAGAIN Try again. This error is mapped to the exception :exc:`BlockingIOError`. .. data:: ENOMEM Out of memory .. data:: EACCES Permission denied. This error is mapped to the exception :exc:`PermissionError`. .. data:: EFAULT Bad address .. data:: ENOTBLK Block device required .. data:: EBUSY Device or resource busy .. data:: EEXIST File exists. This error is mapped to the exception :exc:`FileExistsError`. .. data:: EXDEV Cross-device link .. data:: ENODEV No such device .. data:: ENOTDIR Not a directory. This error is mapped to the exception :exc:`NotADirectoryError`. .. data:: EISDIR Is a directory. This error is mapped to the exception :exc:`IsADirectoryError`. .. data:: EINVAL Invalid argument .. data:: ENFILE File table overflow .. data:: EMFILE Too many open files .. data:: ENOTTY Not a typewriter .. data:: ETXTBSY Text file busy .. data:: EFBIG File too large .. data:: ENOSPC No space left on device .. data:: ESPIPE Illegal seek .. data:: EROFS Read-only file system .. data:: EMLINK Too many links .. data:: EPIPE Broken pipe. This error is mapped to the exception :exc:`BrokenPipeError`. .. data:: EDOM Math argument out of domain of func .. data:: ERANGE Math result not representable .. data:: EDEADLK Resource deadlock would occur .. data:: ENAMETOOLONG File name too long .. data:: ENOLCK No record locks available .. data:: ENOSYS Function not implemented .. data:: ENOTEMPTY Directory not empty .. data:: ELOOP Too many symbolic links encountered .. data:: EWOULDBLOCK Operation would block. This error is mapped to the exception :exc:`BlockingIOError`. .. data:: ENOMSG No message of desired type .. data:: EIDRM Identifier removed .. data:: ECHRNG Channel number out of range .. data:: EL2NSYNC Level 2 not synchronized .. data:: EL3HLT Level 3 halted .. data:: EL3RST Level 3 reset .. data:: ELNRNG Link number out of range .. data:: EUNATCH Protocol driver not attached .. data:: ENOCSI No CSI structure available .. data:: EL2HLT Level 2 halted .. data:: EBADE Invalid exchange .. data:: EBADR ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/errno.rst#codepoints:0:3977"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/errno.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-errno.rst-1,dp-Python-library-errno.rst," .. data:: EL3RST Level 3 reset .. data:: ELNRNG Link number out of range .. data:: EUNATCH Protocol driver not attached .. data:: ENOCSI No CSI structure available .. data:: EL2HLT Level 2 halted .. data:: EBADE Invalid exchange .. data:: EBADR Invalid request descriptor .. data:: EXFULL Exchange full .. data:: ENOANO No anode .. data:: EBADRQC Invalid request code .. data:: EBADSLT Invalid slot .. data:: EDEADLOCK File locking deadlock error .. data:: EBFONT Bad font file format .. data:: ENOSTR Device not a stream .. data:: ENODATA No data available .. data:: ETIME Timer expired .. data:: ENOSR Out of streams resources .. data:: ENONET Machine is not on the network .. data:: ENOPKG Package not installed .. data:: EREMOTE Object is remote .. data:: ENOLINK Link has been severed .. data:: EADV Advertise error .. data:: ESRMNT Srmount error .. data:: ECOMM Communication error on send .. data:: EPROTO Protocol error .. data:: EMULTIHOP Multihop attempted .. data:: EDOTDOT RFS specific error .. data:: EBADMSG Not a data message .. data:: EOVERFLOW Value too large for defined data type .. data:: ENOTUNIQ Name not unique on network .. data:: EBADFD File descriptor in bad state .. data:: EREMCHG Remote address changed .. data:: ELIBACC Can not access a needed shared library .. data:: ELIBBAD Accessing a corrupted shared library .. data:: ELIBSCN .lib section in a.out corrupted .. data:: ELIBMAX Attempting to link in too many shared libraries .. data:: ELIBEXEC Cannot exec a shared library directly .. data:: EILSEQ Illegal byte sequence .. data:: ERESTART Interrupted system call should be restarted .. data:: ESTRPIPE Streams pipe error .. data:: EUSERS Too many users .. data:: ENOTSOCK Socket operation on non-socket .. data:: EDESTADDRREQ Destination address required .. data:: EMSGSIZE Message too long .. data:: EPROTOTYPE Protocol wrong type for socket .. data:: ENOPROTOOPT Protocol not available .. data:: EPROTONOSUPPORT Protocol not supported .. data:: ESOCKTNOSUPPORT Socket type not supported .. data:: EOPNOTSUPP Operation not supported on transport endpoint .. data:: ENOTSUP Operation not supported .. versionadded:: 3.2 .. data:: EPFNOSUPPORT Protocol family not supported .. data:: EAFNOSUPPORT Address family not supported by protocol .. data:: EADDRINUSE Address already in use .. data:: EADDRNOTAVAIL Cannot assign requested address .. data:: ENETDOWN Network is down .. data:: ENETUNREACH Network is unreachable .. data:: ENETRESET Network dropped connection because of reset .. data:: ECONNABORTED Software caused connection abort. This error is mapped to the exception :exc:`ConnectionAbortedError`. .. data:: ECONNRESET Connection reset by peer. This error is mapped to the exception :exc:`ConnectionResetError`. .. data:: ENOBUFS No buffer space available .. data:: EISCONN Transport endpoint is already connected .. data:: ENOTCONN Transport endpoint is not connected .. data:: ESHUTDOWN Cannot send after transport endpoint shutdown. This error is mapped to the exception :exc:`BrokenPipeError`. .. data:: ETOOMANYREFS Too many references: cannot splice .. data:: ETIMEDOUT Connection timed out. This error is mapped to the exception :exc:`TimeoutError`. .. data:: ECONNREFUSED Connection refused. This error is mapped to the exception :exc:`ConnectionRefusedError`. .. data:: EHOSTDOWN Host is down .. data:: EHOSTUNREACH No route to host .. data:: EALREADY Operation already in progress. This error is mapped to the exception :exc:`BlockingIOError`. .. data:: EINPROGRESS Operation now in progress. This error is mapped to the exception :exc:`BlockingIOError`. .. data:: ESTALE Stale NFS file handle .. data:: EUCLEAN Structure needs cleaning .. data:: ENOTNAM Not a XENIX named type file .. data:: ENAVAIL No XENIX semaphores available .. data:: EISNAM Is a named type file .. data:: EREMOTEIO Remote I/O error .. data:: EDQUOT Quota exceeded .. data:: EQFULL Interface output queue is full .. versionadded:: 3.11 .. data:: ENOTCAPABLE Capabilities insufficient. This error is mapped to the exception :exc:`PermissionError`. .. availability:: WASI, FreeBSD .. versionadded:: 3.11.1 .. data:: ECANCELED Operation canceled .. versionadded:: 3.2 .. data:: EOWNERDEAD Owner died .. versionadded:: 3.2 .. data:: ENOTRECOVERABLE State not recoverable .. versionadded:: 3.2 ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/errno.rst#codepoints:3693:8552"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/errno.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-msvcrt.rst-0,dp-Python-library-msvcrt.rst,":mod:`!msvcrt` --- Useful routines from the MS VC++ runtime =========================================================== .. module:: msvcrt :platform: Windows :synopsis: Miscellaneous useful routines from the MS VC++ runtime. .. sectionauthor:: Fred L. Drake, Jr. -------------- These functions provide access to some useful capabilities on Windows platforms. Some higher-level modules use these functions to build the Windows implementations of their services. For example, the :mod:`getpass` module uses this in the implementation of the :func:`getpass` function. Further documentation on these functions can be found in the Platform API documentation. The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible. .. versionchanged:: 3.3 Operations in this module now raise :exc:`OSError` where :exc:`IOError` was raised. .. _msvcrt-files: File Operations --------------- .. function:: locking(fd, mode, nbytes) Lock part of a file based on file descriptor *fd* from the C runtime. Raises :exc:`OSError` on failure. The locked region of the file extends from the current file position for *nbytes* bytes, and may continue beyond the end of the file. *mode* must be one of the :const:`!LK_\*` constants listed below. Multiple regions in a file may be locked at the same time, but may not overlap. Adjacent regions are not merged; they must be unlocked individually. .. audit-event:: msvcrt.locking fd,mode,nbytes msvcrt.locking .. data:: LK_LOCK LK_RLCK Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, :exc:`OSError` is raised. .. data:: LK_NBLCK LK_NBRLCK Locks the specified bytes. If the bytes cannot be locked, :exc:`OSError` is raised. .. data:: LK_UNLCK Unlocks the specified bytes, which must have been previously locked. .. function:: setmode(fd, flags) Set the line-end translation mode for the file descriptor *fd*. To set it to text mode, *flags* should be :const:`os.O_TEXT`; for binary, it should be :const:`os.O_BINARY`. .. function:: open_osfhandle(handle, flags) Create a C runtime file descriptor from the file handle *handle*. The *flags* parameter should be a bitwise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`, :const:`os.O_TEXT` and :const:`os.O_NOINHERIT`. The returned file descriptor may be used as a parameter to :func:`os.fdopen` to create a file object. The file descriptor is inheritable by default. Pass :const:`os.O_NOINHERIT` flag to make it non inheritable. .. audit-event:: msvcrt.open_osfhandle handle,flags msvcrt.open_osfhandle .. function:: get_osfhandle(fd) Return the file handle for the file descriptor *fd*. Raises :exc:`OSError` if *fd* is not recognized. .. audit-event:: msvcrt.get_osfhandle fd msvcrt.get_osfhandle .. _msvcrt-console: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/msvcrt.rst#codepoints:0:3151"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/msvcrt.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-msvcrt.rst-1,dp-Python-library-msvcrt.rst,"Console I/O ----------- .. function:: kbhit() Returns a nonzero value if a keypress is waiting to be read. Otherwise, return 0. .. function:: getch() Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for :kbd:`Enter` to be pressed. If the pressed key was a special function key, this will return ``'\000'`` or ``'\xe0'``; the next call will return the keycode. The :kbd:`Control-C` keypress cannot be read with this function. .. function:: getwch() Wide char variant of :func:`getch`, returning a Unicode value. .. function:: getche() Similar to :func:`getch`, but the keypress will be echoed if it represents a printable character. .. function:: getwche() Wide char variant of :func:`getche`, returning a Unicode value. .. function:: putch(char) Print the byte string *char* to the console without buffering. .. function:: putwch(unicode_char) Wide char variant of :func:`putch`, accepting a Unicode value. .. function:: ungetch(char) Cause the byte string *char* to be ""pushed back"" into the console buffer; it will be the next character read by :func:`getch` or :func:`getche`. .. function:: ungetwch(unicode_char) Wide char variant of :func:`ungetch`, accepting a Unicode value. .. _msvcrt-other: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/msvcrt.rst#codepoints:3151:4565"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/msvcrt.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-msvcrt.rst-2,dp-Python-library-msvcrt.rst,"Other Functions --------------- .. function:: heapmin() Force the :c:func:`malloc` heap to clean itself up and return unused blocks to the operating system. On failure, this raises :exc:`OSError`. .. function:: set_error_mode(mode) Changes the location where the C runtime writes an error message for an error that might end the program. *mode* must be one of the :const:`!OUT_\*` constants listed below or :const:`REPORT_ERRMODE`. Returns the old setting or -1 if an error occurs. Only available in :ref:`debug build of Python `. .. data:: OUT_TO_DEFAULT Error sink is determined by the app's type. Only available in :ref:`debug build of Python `. .. data:: OUT_TO_STDERR Error sink is a standard error. Only available in :ref:`debug build of Python `. .. data:: OUT_TO_MSGBOX Error sink is a message box. Only available in :ref:`debug build of Python `. .. data:: REPORT_ERRMODE Report the current error mode value. Only available in :ref:`debug build of Python `. .. function:: CrtSetReportMode(type, mode) Specifies the destination or destinations for a specific report type generated by :c:func:`!_CrtDbgReport` in the MS VC++ runtime. *type* must be one of the :const:`!CRT_\*` constants listed below. *mode* must be one of the :const:`!CRTDBG_\*` constants listed below. Only available in :ref:`debug build of Python `. .. function:: CrtSetReportFile(type, file) After you use :func:`CrtSetReportMode` to specify :const:`CRTDBG_MODE_FILE`, you can specify the file handle to receive the message text. *type* must be one of the :const:`!CRT_\*` constants listed below. *file* should be the file handle your want specified. Only available in :ref:`debug build of Python `. .. data:: CRT_WARN Warnings, messages, and information that doesn't need immediate attention. .. data:: CRT_ERROR Errors, unrecoverable problems, and issues that require immediate attention. .. data:: CRT_ASSERT Assertion failures. .. data:: CRTDBG_MODE_DEBUG Writes the message to the debugger's output window. .. data:: CRTDBG_MODE_FILE Writes the message to a user-supplied file handle. :func:`CrtSetReportFile` should be called to define the specific file or stream to use as the destination. .. data:: CRTDBG_MODE_WNDW Creates a message box to display the message along with the ``Abort``, ``Retry``, and ``Ignore`` buttons. .. data:: CRTDBG_REPORT_MODE Returns current *mode* for the specified *type*. .. data:: CRT_ASSEMBLY_VERSION The CRT Assembly version, from the :file:`crtassem.h` header file. .. data:: VC_ASSEMBLY_PUBLICKEYTOKEN The VC Assembly public key token, from the :file:`crtassem.h` header file. .. data:: LIBRARIES_ASSEMBLY_NAME_PREFIX The Libraries Assembly name prefix, from the :file:`crtassem.h` header file. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/msvcrt.rst#codepoints:4565:7539"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/msvcrt.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-library-msvcrt.rst-0,dp-Python-library-msvcrt.rst,":mod:`!msvcrt` --- Useful routines from the MS VC++ runtime =========================================================== .. module:: msvcrt :platform: Windows :synopsis: Miscellaneous useful routines from the MS VC++ runtime. .. sectionauthor:: Fred L. Drake, Jr. -------------- These functions provide access to some useful capabilities on Windows platforms. Some higher-level modules use these functions to build the Windows implementations of their services. For example, the :mod:`getpass` module uses this in the implementation of the :func:`getpass` function. Further documentation on these functions can be found in the Platform API documentation. The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible. .. versionchanged:: 3.3 Operations in this module now raise :exc:`OSError` where :exc:`IOError` was raised. .. _msvcrt-files: File Operations --------------- .. function:: locking(fd, mode, nbytes) Lock part of a file based on file descriptor *fd* from the C runtime. Raises :exc:`OSError` on failure. The locked region of the file extends from the current file position for *nbytes* bytes, and may continue beyond the end of the file. *mode* must be one of the :const:`!LK_\*` constants listed below. Multiple regions in a file may be locked at the same time, but may not overlap. Adjacent regions are not merged; they must be unlocked individually. .. audit-event:: msvcrt.locking fd,mode,nbytes msvcrt.locking .. data:: LK_LOCK LK_RLCK Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, :exc:`OSError` is raised. .. data:: LK_NBLCK LK_NBRLCK Locks the specified bytes. If the bytes cannot be locked, :exc:`OSError` is raised. .. data:: LK_UNLCK Unlocks the specified bytes, which must have been previously locked. .. function:: setmode(fd, flags) Set the line-end translation mode for the file descriptor *fd*. To set it to text mode, *flags* should be :const:`os.O_TEXT`; for binary, it should be :const:`os.O_BINARY`. .. function:: open_osfhandle(handle, flags) Create a C runtime file descriptor from the file handle *handle*. The *flags* parameter should be a bitwise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`, and :const:`os.O_TEXT`. The returned file descriptor may be used as a parameter to :func:`os.fdopen` to create a file object. .. audit-event:: msvcrt.open_osfhandle handle,flags msvcrt.open_osfhandle .. function:: get_osfhandle(fd) Return the file handle for the file descriptor *fd*. Raises :exc:`OSError` if *fd* is not recognized. .. audit-event:: msvcrt.get_osfhandle fd msvcrt.get_osfhandle .. _msvcrt-console: ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/msvcrt.rst#codepoints:0:3018"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/msvcrt.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-library-msvcrt.rst-1,dp-Python-library-msvcrt.rst,"Console I/O ----------- .. function:: kbhit() Return ``True`` if a keypress is waiting to be read. .. function:: getch() Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for :kbd:`Enter` to be pressed. If the pressed key was a special function key, this will return ``'\000'`` or ``'\xe0'``; the next call will return the keycode. The :kbd:`Control-C` keypress cannot be read with this function. .. function:: getwch() Wide char variant of :func:`getch`, returning a Unicode value. .. function:: getche() Similar to :func:`getch`, but the keypress will be echoed if it represents a printable character. .. function:: getwche() Wide char variant of :func:`getche`, returning a Unicode value. .. function:: putch(char) Print the byte string *char* to the console without buffering. .. function:: putwch(unicode_char) Wide char variant of :func:`putch`, accepting a Unicode value. .. function:: ungetch(char) Cause the byte string *char* to be ""pushed back"" into the console buffer; it will be the next character read by :func:`getch` or :func:`getche`. .. function:: ungetwch(unicode_char) Wide char variant of :func:`ungetch`, accepting a Unicode value. .. _msvcrt-other: Other Functions --------------- .. function:: heapmin() Force the :c:func:`malloc` heap to clean itself up and return unused blocks to the operating system. On failure, this raises :exc:`OSError`. .. data:: CRT_ASSEMBLY_VERSION The CRT Assembly version, from the :file:`crtassem.h` header file. .. data:: VC_ASSEMBLY_PUBLICKEYTOKEN The VC Assembly public key token, from the :file:`crtassem.h` header file. .. data:: LIBRARIES_ASSEMBLY_NAME_PREFIX The Libraries Assembly name prefix, from the :file:`crtassem.h` header file. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/msvcrt.rst#codepoints:3018:4953"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/msvcrt.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-library-numbers.rst-0,dp-Python-library-numbers.rst,":mod:`!numbers` --- Numeric abstract base classes ================================================= .. module:: numbers :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.). **Source code:** :source:`Lib/numbers.py` -------------- The :mod:`!numbers` module (:pep:`3141`) defines a hierarchy of numeric :term:`abstract base classes ` which progressively define more operations. None of the types defined in this module are intended to be instantiated. .. class:: Number The root of the numeric hierarchy. If you just want to check if an argument *x* is a number, without caring what kind, use ``isinstance(x, Number)``. The numeric tower ----------------- .. class:: Complex Subclasses of this type describe complex numbers and include the operations that work on the built-in :class:`complex` type. These are: conversions to :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``, ``-``, ``*``, ``/``, ``**``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All except ``-`` and ``!=`` are abstract. .. attribute:: real Abstract. Retrieves the real component of this number. .. attribute:: imag Abstract. Retrieves the imaginary component of this number. .. abstractmethod:: conjugate() Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() == (1-3j)``. .. class:: Real To :class:`Complex`, :class:`!Real` adds the operations that work on real numbers. In short, those are: a conversion to :class:`float`, :func:`math.trunc`, :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``, ``%``, ``<``, ``<=``, ``>``, and ``>=``. Real also provides defaults for :func:`complex`, :attr:`~Complex.real`, :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`. .. class:: Rational Subtypes :class:`Real` and adds :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties. It also provides a default for :func:`float`. The :attr:`~Rational.numerator` and :attr:`~Rational.denominator` values should be instances of :class:`Integral` and should be in lowest terms with :attr:`~Rational.denominator` positive. .. attribute:: numerator Abstract. .. attribute:: denominator Abstract. .. class:: Integral Subtypes :class:`Rational` and adds a conversion to :class:`int`. Provides defaults for :func:`float`, :attr:`~Rational.numerator`, and :attr:`~Rational.denominator`. Adds abstract methods for :func:`pow` with modulus and bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``. Notes for type implementers --------------------------- Implementers should be careful to make equal numbers equal and hash them to the same values. This may be subtle if there are two different extensions of the real numbers. For example, :class:`fractions.Fraction` implements :func:`hash` as follows:: def __hash__(self): if self.denominator == 1: # Get integers right. return hash(self.numerator) # Expensive check, but definitely correct. if self == float(self): return hash(float(self)) else: # Use tuple's hash to avoid a high collision rate on # simple fractions. return hash((self.numerator, self.denominator)) Adding More Numeric ABCs ~~~~~~~~~~~~~~~~~~~~~~~~ There are, of course, more possible ABCs for numbers, and this would be a poor hierarchy if it precluded the possibility of adding those. You can add ``MyFoo`` between :class:`Complex` and :class:`Real` with:: class MyFoo(Complex): ... MyFoo.register(Real) .. _implementing-the-arithmetic-operations: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/numbers.rst#codepoints:0:3760"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/numbers.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-numbers.rst-1,dp-Python-library-numbers.rst,"Implementing the arithmetic operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. For subtypes of :class:`Integral`, this means that :meth:`~object.__add__` and :meth:`~object.__radd__` should be defined as:: class MyIntegral(Integral): def __add__(self, other): if isinstance(other, MyIntegral): return do_my_adding_stuff(self, other) elif isinstance(other, OtherTypeIKnowAbout): return do_my_other_adding_stuff(self, other) else: return NotImplemented def __radd__(self, other): if isinstance(other, MyIntegral): return do_my_adding_stuff(other, self) elif isinstance(other, OtherTypeIKnowAbout): return do_my_other_adding_stuff(other, self) elif isinstance(other, Integral): return int(other) + int(self) elif isinstance(other, Real): return float(other) + float(self) elif isinstance(other, Complex): return complex(other) + complex(self) else: return NotImplemented There are 5 different cases for a mixed-type operation on subclasses of :class:`Complex`. I'll refer to all of the above code that doesn't refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as ""boilerplate"". ``a`` will be an instance of ``A``, which is a subtype of :class:`Complex` (``a : A <: Complex``), and ``b : B <: Complex``. I'll consider ``a + b``: 1. If ``A`` defines an :meth:`~object.__add__` which accepts ``b``, all is well. 2. If ``A`` falls back to the boilerplate code, and it were to return a value from :meth:`~object.__add__`, we'd miss the possibility that ``B`` defines a more intelligent :meth:`~object.__radd__`, so the boilerplate should return :data:`NotImplemented` from :meth:`!__add__`. (Or ``A`` may not implement :meth:`!__add__` at all.) 3. Then ``B``'s :meth:`~object.__radd__` gets a chance. If it accepts ``a``, all is well. 4. If it falls back to the boilerplate, there are no more possible methods to try, so this is where the default implementation should live. 5. If ``B <: A``, Python tries ``B.__radd__`` before ``A.__add__``. This is ok, because it was implemented with knowledge of ``A``, so it can handle those instances before delegating to :class:`Complex`. If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge, then the appropriate shared operation is the one involving the built in :class:`complex`, and both :meth:`~object.__radd__` s land there, so ``a+b == b+a``. Because most of the operations on any given type will be very similar, it can be useful to define a helper function which generates the forward and reverse instances of any given operator. For example, :class:`fractions.Fraction` uses:: def _operator_fallbacks(monomorphic_operator, fallback_operator): def forward(a, b): if isinstance(b, (int, Fraction)): return monomorphic_operator(a, b) elif isinstance(b, float): return fallback_operator(float(a), b) elif isinstance(b, complex): return fallback_operator(complex(a), b) else: return NotImplemented forward.__name__ = '__' + fallback_operator.__name__ + '__' forward.__doc__ = monomorphic_operator.__doc__ def reverse(b, a): if isinstance(a, Rational): # Includes ints. return monomorphic_operator(a, b) elif isinstance(a, Real): return fallback_operator(float(a), float(b)) elif isinstance(a, Complex): return fallback_operator(complex(a), complex(b)) else: return NotImplemented reverse.__name__ = '__r' + fallback_operator.__name__ + '__' reverse.__doc__ = monomorphic_operator.__doc__ return forward, reverse def _add(a, b): """"""a + b"""""" return Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator) __add__, __radd__ = _operator_fallbacks(_add, operator.add) # ... ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/numbers.rst#codepoints:3760:8263"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/numbers.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-readline.rst-0,dp-Python-library-readline.rst,":mod:`!readline` --- GNU readline interface =========================================== .. module:: readline :platform: Unix :synopsis: GNU readline support for Python. .. sectionauthor:: Skip Montanaro -------------- The :mod:`readline` module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly, or via the :mod:`rlcompleter` module, which supports completion of Python identifiers at the interactive prompt. Settings made using this module affect the behaviour of both the interpreter's interactive prompt and the prompts offered by the built-in :func:`input` function. Readline keybindings may be configured via an initialization file, typically ``.inputrc`` in your home directory. See `Readline Init File `_ in the GNU Readline manual for information about the format and allowable constructs of that file, and the capabilities of the Readline library in general. .. include:: ../includes/wasm-mobile-notavail.rst .. note:: The underlying Readline library API may be implemented by the ``editline`` (``libedit``) library instead of GNU readline. On macOS the :mod:`readline` module detects which library is being used at run time. The configuration file for ``editline`` is different from that of GNU readline. If you programmatically load configuration strings you can use :data:`backend` to determine which library is being used. If you use ``editline``/``libedit`` readline emulation on macOS, the initialization file located in your home directory is named ``.editrc``. For example, the following content in ``~/.editrc`` will turn ON *vi* keybindings and TAB completion:: python:bind -v python:bind ^I rl_complete Also note that different libraries may use different history file formats. When switching the underlying library, existing history files may become unusable. .. data:: backend The name of the underlying Readline library being used, either ``""readline""`` or ``""editline""``. .. versionadded:: 3.13 Init file --------- The following functions relate to the init file and user configuration: .. function:: parse_and_bind(string) Execute the init line provided in the *string* argument. This calls :c:func:`rl_parse_and_bind` in the underlying library. .. function:: read_init_file([filename]) Execute a readline initialization file. The default filename is the last filename used. This calls :c:func:`rl_read_init_file` in the underlying library. Line buffer ----------- The following functions operate on the line buffer: .. function:: get_line_buffer() Return the current contents of the line buffer (:c:data:`rl_line_buffer` in the underlying library). .. function:: insert_text(string) Insert text into the line buffer at the cursor position. This calls :c:func:`rl_insert_text` in the underlying library, but ignores the return value. .. function:: redisplay() Change what's displayed on the screen to reflect the current contents of the line buffer. This calls :c:func:`rl_redisplay` in the underlying library. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/readline.rst#codepoints:0:3271"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/readline.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-readline.rst-1,dp-Python-library-readline.rst,"History file ------------ The following functions operate on a history file: .. function:: read_history_file([filename]) Load a readline history file, and append it to the history list. The default filename is :file:`~/.history`. This calls :c:func:`read_history` in the underlying library. .. function:: write_history_file([filename]) Save the history list to a readline history file, overwriting any existing file. The default filename is :file:`~/.history`. This calls :c:func:`write_history` in the underlying library. .. function:: append_history_file(nelements[, filename]) Append the last *nelements* items of history to a file. The default filename is :file:`~/.history`. The file must already exist. This calls :c:func:`append_history` in the underlying library. This function only exists if Python was compiled for a version of the library that supports it. .. versionadded:: 3.5 .. function:: get_history_length() set_history_length(length) Set or return the desired number of lines to save in the history file. The :func:`write_history_file` function uses this value to truncate the history file, by calling :c:func:`history_truncate_file` in the underlying library. Negative values imply unlimited history file size. History list ------------ The following functions operate on a global history list: .. function:: clear_history() Clear the current history. This calls :c:func:`clear_history` in the underlying library. The Python function only exists if Python was compiled for a version of the library that supports it. .. function:: get_current_history_length() Return the number of items currently in the history. (This is different from :func:`get_history_length`, which returns the maximum number of lines that will be written to a history file.) .. function:: get_history_item(index) Return the current contents of history item at *index*. The item index is one-based. This calls :c:func:`history_get` in the underlying library. .. function:: remove_history_item(pos) Remove history item specified by its position from the history. The position is zero-based. This calls :c:func:`remove_history` in the underlying library. .. function:: replace_history_item(pos, line) Replace history item specified by its position with *line*. The position is zero-based. This calls :c:func:`replace_history_entry` in the underlying library. .. function:: add_history(line) Append *line* to the history buffer, as if it was the last line typed. This calls :c:func:`add_history` in the underlying library. .. function:: set_auto_history(enabled) Enable or disable automatic calls to :c:func:`add_history` when reading input via readline. The *enabled* argument should be a Boolean value that when true, enables auto history, and that when false, disables auto history. .. versionadded:: 3.6 .. impl-detail:: Auto history is enabled by default, and changes to this do not persist across multiple sessions. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/readline.rst#codepoints:3271:6381"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/readline.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-readline.rst-2,dp-Python-library-readline.rst,"Startup hooks ------------- .. function:: set_startup_hook([function]) Set or remove the function invoked by the :c:data:`rl_startup_hook` callback of the underlying library. If *function* is specified, it will be used as the new hook function; if omitted or ``None``, any function already installed is removed. The hook is called with no arguments just before readline prints the first prompt. .. function:: set_pre_input_hook([function]) Set or remove the function invoked by the :c:data:`rl_pre_input_hook` callback of the underlying library. If *function* is specified, it will be used as the new hook function; if omitted or ``None``, any function already installed is removed. The hook is called with no arguments after the first prompt has been printed and just before readline starts reading input characters. This function only exists if Python was compiled for a version of the library that supports it. .. _readline-completion: Completion ---------- The following functions relate to implementing a custom word completion function. This is typically operated by the Tab key, and can suggest and automatically complete a word being typed. By default, Readline is set up to be used by :mod:`rlcompleter` to complete Python identifiers for the interactive interpreter. If the :mod:`readline` module is to be used with a custom completer, a different set of word delimiters should be set. .. function:: set_completer([function]) Set or remove the completer function. If *function* is specified, it will be used as the new completer function; if omitted or ``None``, any completer function already installed is removed. The completer function is called as ``function(text, state)``, for *state* in ``0``, ``1``, ``2``, ..., until it returns a non-string value. It should return the next possible completion starting with *text*. The installed completer function is invoked by the *entry_func* callback passed to :c:func:`rl_completion_matches` in the underlying library. The *text* string comes from the first parameter to the :c:data:`rl_attempted_completion_function` callback of the underlying library. .. function:: get_completer() Get the completer function, or ``None`` if no completer function has been set. .. function:: get_completion_type() Get the type of completion being attempted. This returns the :c:data:`rl_completion_type` variable in the underlying library as an integer. .. function:: get_begidx() get_endidx() Get the beginning or ending index of the completion scope. These indexes are the *start* and *end* arguments passed to the :c:data:`rl_attempted_completion_function` callback of the underlying library. The values may be different in the same input editing scenario based on the underlying C readline implementation. Ex: libedit is known to behave differently than libreadline. .. function:: set_completer_delims(string) get_completer_delims() Set or get the word delimiters for completion. These determine the start of the word to be considered for completion (the completion scope). These functions access the :c:data:`rl_completer_word_break_characters` variable in the underlying library. .. function:: set_completion_display_matches_hook([function]) Set or remove the completion display function. If *function* is specified, it will be used as the new completion display function; if omitted or ``None``, any completion display function already installed is removed. This sets or clears the :c:data:`rl_completion_display_matches_hook` callback in the underlying library. The completion display function is called as ``function(substitution, [matches], longest_match_length)`` once each time matches need to be displayed. .. _readline-example: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/readline.rst#codepoints:6381:10278"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/readline.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-readline.rst-3,dp-Python-library-readline.rst,"Example ------- The following example demonstrates how to use the :mod:`readline` module's history reading and writing functions to automatically load and save a history file named :file:`.python_history` from the user's home directory. The code below would normally be executed automatically during interactive sessions from the user's :envvar:`PYTHONSTARTUP` file. :: import atexit import os import readline histfile = os.path.join(os.path.expanduser(""~""), "".python_history"") try: readline.read_history_file(histfile) # default history len is -1 (infinite), which may grow unruly readline.set_history_length(1000) except FileNotFoundError: pass atexit.register(readline.write_history_file, histfile) This code is actually automatically run when Python is run in :ref:`interactive mode ` (see :ref:`rlcompleter-config`). The following example achieves the same goal but supports concurrent interactive sessions, by only appending the new history. :: import atexit import os import readline histfile = os.path.join(os.path.expanduser(""~""), "".python_history"") try: readline.read_history_file(histfile) h_len = readline.get_current_history_length() except FileNotFoundError: open(histfile, 'wb').close() h_len = 0 def save(prev_h_len, histfile): new_h_len = readline.get_current_history_length() readline.set_history_length(1000) readline.append_history_file(new_h_len - prev_h_len, histfile) atexit.register(save, h_len, histfile) The following example extends the :class:`code.InteractiveConsole` class to support history save/restore. :: import atexit import code import os import readline class HistoryConsole(code.InteractiveConsole): def __init__(self, locals=None, filename="""", histfile=os.path.expanduser(""~/.console-history"")): code.InteractiveConsole.__init__(self, locals, filename) self.init_history(histfile) def init_history(self, histfile): readline.parse_and_bind(""tab: complete"") if hasattr(readline, ""read_history_file""): try: readline.read_history_file(histfile) except FileNotFoundError: pass atexit.register(self.save_history, histfile) def save_history(self, histfile): readline.set_history_length(1000) readline.write_history_file(histfile) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/readline.rst#codepoints:10278:12808"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/readline.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-library-readline.rst-0,dp-Python-library-readline.rst,":mod:`!readline` --- GNU readline interface =========================================== .. module:: readline :platform: Unix :synopsis: GNU readline support for Python. .. sectionauthor:: Skip Montanaro -------------- The :mod:`readline` module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly, or via the :mod:`rlcompleter` module, which supports completion of Python identifiers at the interactive prompt. Settings made using this module affect the behaviour of both the interpreter's interactive prompt and the prompts offered by the built-in :func:`input` function. Readline keybindings may be configured via an initialization file, typically ``.inputrc`` in your home directory. See `Readline Init File `_ in the GNU Readline manual for information about the format and allowable constructs of that file, and the capabilities of the Readline library in general. .. note:: The underlying Readline library API may be implemented by the ``libedit`` library instead of GNU readline. On macOS the :mod:`readline` module detects which library is being used at run time. The configuration file for ``libedit`` is different from that of GNU readline. If you programmatically load configuration strings you can check for the text ""libedit"" in :const:`readline.__doc__` to differentiate between GNU readline and libedit. If you use *editline*/``libedit`` readline emulation on macOS, the initialization file located in your home directory is named ``.editrc``. For example, the following content in ``~/.editrc`` will turn ON *vi* keybindings and TAB completion:: python:bind -v python:bind ^I rl_complete Also note that different libraries may use different history file formats. When switching the underlying library, existing history files may become unusable. Init file --------- The following functions relate to the init file and user configuration: .. function:: parse_and_bind(string) Execute the init line provided in the *string* argument. This calls :c:func:`rl_parse_and_bind` in the underlying library. .. function:: read_init_file([filename]) Execute a readline initialization file. The default filename is the last filename used. This calls :c:func:`rl_read_init_file` in the underlying library. Line buffer ----------- The following functions operate on the line buffer: .. function:: get_line_buffer() Return the current contents of the line buffer (:c:data:`rl_line_buffer` in the underlying library). .. function:: insert_text(string) Insert text into the line buffer at the cursor position. This calls :c:func:`rl_insert_text` in the underlying library, but ignores the return value. .. function:: redisplay() Change what's displayed on the screen to reflect the current contents of the line buffer. This calls :c:func:`rl_redisplay` in the underlying library. ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/readline.rst#codepoints:0:3102"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/readline.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-library-tkinter.colorchooser.rst-0,dp-Python-library-tkinter.colorchooser.rst,":mod:`!tkinter.colorchooser` --- Color choosing dialog ====================================================== .. module:: tkinter.colorchooser :platform: Tk :synopsis: Color choosing dialog **Source code:** :source:`Lib/tkinter/colorchooser.py` -------------- The :mod:`tkinter.colorchooser` module provides the :class:`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 :class:`~tkinter.commondialog.Dialog` class. .. class:: Chooser(master=None, **options) .. function:: 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. .. seealso:: Module :mod:`tkinter.commondialog` Tkinter standard dialog module ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/tkinter.colorchooser.rst#codepoints:0:908"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/tkinter.colorchooser.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-tokenize.rst-0,dp-Python-library-tokenize.rst,":mod:`!tokenize` --- Tokenizer for Python source ================================================ .. module:: tokenize :synopsis: Lexical scanner for Python source code. .. moduleauthor:: Ka Ping Yee .. sectionauthor:: Fred L. Drake, Jr. **Source code:** :source:`Lib/tokenize.py` -------------- The :mod:`tokenize` module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing ""pretty-printers"", including colorizers for on-screen displays. To simplify token stream handling, all :ref:`operator ` and :ref:`delimiter ` tokens and :data:`Ellipsis` are returned using the generic :data:`~token.OP` token type. The exact type can be determined by checking the ``exact_type`` property on the :term:`named tuple` returned from :func:`tokenize.tokenize`. .. warning:: Note that the functions in this module are only designed to parse syntactically valid Python code (code that does not raise when parsed using :func:`ast.parse`). The behavior of the functions in this module is **undefined** when providing invalid Python code and it can change at any point. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/tokenize.rst#codepoints:0:1241"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/tokenize.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-tokenize.rst-1,dp-Python-library-tokenize.rst,"Tokenizing Input ---------------- The primary entry point is a :term:`generator`: .. function:: tokenize(readline) The :func:`.tokenize` generator requires one argument, *readline*, which must be a callable object which provides the same interface as the :meth:`io.IOBase.readline` method of file objects. Each call to the function should return one line of input as bytes. The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the *physical* line. The 5 tuple is returned as a :term:`named tuple` with the field names: ``type string start end line``. The returned :term:`named tuple` has an additional property named ``exact_type`` that contains the exact operator type for :data:`~token.OP` tokens. For all other token types ``exact_type`` equals the named tuple ``type`` field. .. versionchanged:: 3.1 Added support for named tuples. .. versionchanged:: 3.3 Added support for ``exact_type``. :func:`.tokenize` determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to :pep:`263`. .. function:: generate_tokens(readline) Tokenize a source reading unicode strings instead of bytes. Like :func:`.tokenize`, the *readline* argument is a callable returning a single line of input. However, :func:`generate_tokens` expects *readline* to return a str object rather than bytes. The result is an iterator yielding named tuples, exactly like :func:`.tokenize`. It does not yield an :data:`~token.ENCODING` token. All constants from the :mod:`token` module are also exported from :mod:`tokenize`. Another function is provided to reverse the tokenization process. This is useful for creating tools that tokenize a script, modify the token stream, and write back the modified script. .. function:: untokenize(iterable) Converts tokens back into Python source code. The *iterable* must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored. The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change. It returns bytes, encoded using the :data:`~token.ENCODING` token, which is the first token sequence output by :func:`.tokenize`. If there is no encoding token in the input, it returns a str instead. :func:`.tokenize` needs to detect the encoding of source files it tokenizes. The function it uses to do this is available: .. function:: detect_encoding(readline) The :func:`detect_encoding` function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the :func:`.tokenize` generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in. It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in :pep:`263`. If both a BOM and a cookie are present, but disagree, a :exc:`SyntaxError` will be raised. Note that if the BOM is found, ``'utf-8-sig'`` will be returned as an encoding. If no encoding is specified, then the default of ``'utf-8'`` will be returned. Use :func:`.open` to open Python source files: it uses :func:`detect_encoding` to detect the file encoding. .. function:: open(filename) Open a file in read only mode using the encoding detected by :func:`detect_encoding`. .. versionadded:: 3.2 .. exception:: TokenError Raised when either a docstring or expression that may be split over several lines is not completed anywhere in the file, for example:: """"""Beginning of docstring or:: [1, 2, 3 .. _tokenize-cli: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/tokenize.rst#codepoints:1241:5640"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/tokenize.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-tokenize.rst-2,dp-Python-library-tokenize.rst,"Command-Line Usage ------------------ .. versionadded:: 3.3 The :mod:`tokenize` module can be executed as a script from the command line. It is as simple as: .. code-block:: sh python -m tokenize [-e] [filename.py] The following options are accepted: .. program:: tokenize .. option:: -h, --help show this help message and exit .. option:: -e, --exact display token names using the exact type If :file:`filename.py` is specified its contents are tokenized to stdout. Otherwise, tokenization is performed on stdin. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/tokenize.rst#codepoints:5640:6175"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/tokenize.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-tokenize.rst-3,dp-Python-library-tokenize.rst,"Examples ------------------ Example of a script rewriter that transforms float literals into Decimal objects:: from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP from io import BytesIO def decistmt(s): """"""Substitute Decimals for floats in a string of statements. >>> from decimal import Decimal >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) ""print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"" The format of the exponent is inherited from the platform C library. Known cases are ""e-007"" (Windows) and ""e-07"" (not Windows). Since we're only showing 12 digits, and the 13th isn't close to 5, the rest of the output should be platform-independent. >>> exec(s) #doctest: +ELLIPSIS -3.21716034272e-0...7 Output from calculations with Decimal should be identical across all platforms. >>> exec(decistmt(s)) -3.217160342717258261933904529E-7 """""" result = [] g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string for toknum, tokval, _, _, _ in g: if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens result.extend([ (NAME, 'Decimal'), (OP, '('), (STRING, repr(tokval)), (OP, ')') ]) else: result.append((toknum, tokval)) return untokenize(result).decode('utf-8') Example of tokenizing from the command line. The script:: def say_hello(): print(""Hello, World!"") say_hello() will be tokenized to the following output where the first column is the range of the line/column coordinates where the token is found, the second column is the name of the token, and the final column is the value of the token (if any) .. code-block:: shell-session $ python -m tokenize hello.py 0,0-0,0: ENCODING 'utf-8' 1,0-1,3: NAME 'def' 1,4-1,13: NAME 'say_hello' 1,13-1,14: OP '(' 1,14-1,15: OP ')' 1,15-1,16: OP ':' 1,16-1,17: NEWLINE '\n' 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' 2,9-2,10: OP '(' 2,10-2,25: STRING '""Hello, World!""' 2,25-2,26: OP ')' 2,26-2,27: NEWLINE '\n' 3,0-3,1: NL '\n' 4,0-4,0: DEDENT '' 4,0-4,9: NAME 'say_hello' 4,9-4,10: OP '(' 4,10-4,11: OP ')' 4,11-4,12: NEWLINE '\n' 5,0-5,0: ENDMARKER '' The exact token type names can be displayed using the :option:`-e` option: .. code-block:: shell-session $ python -m tokenize -e hello.py 0,0-0,0: ENCODING 'utf-8' 1,0-1,3: NAME 'def' 1,4-1,13: NAME 'say_hello' 1,13-1,14: LPAR '(' 1,14-1,15: RPAR ')' 1,15-1,16: COLON ':' 1,16-1,17: NEWLINE '\n' 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' 2,9-2,10: LPAR '(' 2,10-2,25: STRING '""Hello, World!""' 2,25-2,26: RPAR ')' 2,26-2,27: NEWLINE '\n' 3,0-3,1: NL '\n' 4,0-4,0: DEDENT '' 4,0-4,9: NAME 'say_hello' 4,9-4,10: LPAR '(' 4,10-4,11: RPAR ')' 4,11-4,12: NEWLINE '\n' 5,0-5,0: ENDMARKER '' Example of tokenizing a file programmatically, reading unicode strings instead of bytes with :func:`generate_tokens`:: import tokenize with tokenize.open('hello.py') as f: tokens = tokenize.generate_tokens(f.readline) for token in tokens: print(token) Or reading bytes directly with :func:`.tokenize`:: import tokenize with open('hello.py', 'rb') as f: tokens = tokenize.tokenize(f.readline) for token in tokens: print(token) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/tokenize.rst#codepoints:6175:10624"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/tokenize.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-types.rst-0,dp-Python-library-types.rst,":mod:`!types` --- Dynamic type creation and names for built-in types ==================================================================== .. module:: types :synopsis: Names for built-in types. **Source code:** :source:`Lib/types.py` -------------- This module defines utility functions to assist in dynamic creation of new types. It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like :class:`int` or :class:`str` are. Finally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/types.rst#codepoints:0:630"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-types.rst-1,dp-Python-library-types.rst,"Dynamic Type Creation --------------------- .. function:: new_class(name, bases=(), kwds=None, exec_body=None) Creates a class object dynamically using the appropriate metaclass. The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as ``metaclass``). The *exec_body* argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in ``lambda ns: None``. .. versionadded:: 3.3 .. function:: prepare_class(name, bases=(), kwds=None) Calculates the appropriate metaclass and creates the class namespace. The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as ``metaclass``). The return value is a 3-tuple: ``metaclass, namespace, kwds`` *metaclass* is the appropriate metaclass, *namespace* is the prepared class namespace and *kwds* is an updated copy of the passed in *kwds* argument with any ``'metaclass'`` entry removed. If no *kwds* argument is passed in, this will be an empty dict. .. versionadded:: 3.3 .. versionchanged:: 3.6 The default value for the ``namespace`` element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a ``__prepare__`` method. .. seealso:: :ref:`metaclasses` Full details of the class creation process supported by these functions :pep:`3115` - Metaclasses in Python 3000 Introduced the ``__prepare__`` namespace hook .. function:: resolve_bases(bases) Resolve MRO entries dynamically as specified by :pep:`560`. This function looks for items in *bases* that are not instances of :class:`type`, and returns a tuple where each such object that has an :meth:`~object.__mro_entries__` method is replaced with an unpacked result of calling this method. If a *bases* item is an instance of :class:`type`, or it doesn't have an :meth:`!__mro_entries__` method, then it is included in the return tuple unchanged. .. versionadded:: 3.7 .. function:: get_original_bases(cls, /) Return the tuple of objects originally given as the bases of *cls* before the :meth:`~object.__mro_entries__` method has been called on any bases (following the mechanisms laid out in :pep:`560`). This is useful for introspecting :ref:`Generics `. For classes that have an ``__orig_bases__`` attribute, this function returns the value of ``cls.__orig_bases__``. For classes without the ``__orig_bases__`` attribute, :attr:`cls.__bases__ ` is returned. Examples:: from typing import TypeVar, Generic, NamedTuple, TypedDict T = TypeVar(""T"") class Foo(Generic[T]): ... class Bar(Foo[int], float): ... class Baz(list[str]): ... Eggs = NamedTuple(""Eggs"", [(""a"", int), (""b"", str)]) Spam = TypedDict(""Spam"", {""a"": int, ""b"": str}) assert Bar.__bases__ == (Foo, float) assert get_original_bases(Bar) == (Foo[int], float) assert Baz.__bases__ == (list,) assert get_original_bases(Baz) == (list[str],) assert Eggs.__bases__ == (tuple,) assert get_original_bases(Eggs) == (NamedTuple,) assert Spam.__bases__ == (dict,) assert get_original_bases(Spam) == (TypedDict,) assert int.__bases__ == (object,) assert get_original_bases(int) == (object,) .. versionadded:: 3.12 .. seealso:: :pep:`560` - Core support for typing module and generic types ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/types.rst#codepoints:630:4510"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-types.rst-2,dp-Python-library-types.rst,"Standard Interpreter Types -------------------------- This module provides names for many of the types that are required to implement a Python interpreter. It deliberately avoids including some of the types that arise only incidentally during processing such as the ``listiterator`` type. Typical use of these names is for :func:`isinstance` or :func:`issubclass` checks. If you instantiate any of these types, note that signatures may vary between Python versions. Standard names are defined for the following types: .. data:: NoneType The type of :data:`None`. .. versionadded:: 3.10 .. data:: FunctionType LambdaType The type of user-defined functions and functions created by :keyword:`lambda` expressions. .. audit-event:: function.__new__ code types.FunctionType The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation. .. data:: GeneratorType The type of :term:`generator`-iterator objects, created by generator functions. .. data:: CoroutineType The type of :term:`coroutine` objects, created by :keyword:`async def` functions. .. versionadded:: 3.5 .. data:: AsyncGeneratorType The type of :term:`asynchronous generator`-iterator objects, created by asynchronous generator functions. .. versionadded:: 3.6 .. class:: CodeType(**kwargs) .. index:: pair: built-in function; compile The type of :ref:`code objects ` such as returned by :func:`compile`. .. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags types.CodeType Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation. .. data:: CellType The type for cell objects: such objects are used as containers for a function's free variables. .. versionadded:: 3.8 .. data:: MethodType The type of methods of user-defined class instances. .. data:: BuiltinFunctionType BuiltinMethodType The type of built-in functions like :func:`len` or :func:`sys.exit`, and methods of built-in classes. (Here, the term ""built-in"" means ""written in C"".) .. data:: WrapperDescriptorType The type of methods of some built-in data types and base classes such as :meth:`object.__init__` or :meth:`object.__lt__`. .. versionadded:: 3.7 .. data:: MethodWrapperType The type of *bound* methods of some built-in data types and base classes. For example it is the type of :code:`object().__str__`. .. versionadded:: 3.7 .. data:: NotImplementedType The type of :data:`NotImplemented`. .. versionadded:: 3.10 .. data:: MethodDescriptorType The type of methods of some built-in data types such as :meth:`str.join`. .. versionadded:: 3.7 .. data:: ClassMethodDescriptorType The type of *unbound* class methods of some built-in data types such as ``dict.__dict__['fromkeys']``. .. versionadded:: 3.7 .. class:: ModuleType(name, doc=None) The type of :term:`modules `. The constructor takes the name of the module to be created and optionally its :term:`docstring`. .. note:: Use :func:`importlib.util.module_from_spec` to create a new module if you wish to set the various import-controlled attributes. .. attribute:: __doc__ The :term:`docstring` of the module. Defaults to ``None``. .. attribute:: __loader__ The :term:`loader` which loaded the module. Defaults to ``None``. This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader` as stored in the :attr:`__spec__` object. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/types.rst#codepoints:4510:8290"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-types.rst-3,dp-Python-library-types.rst," The :term:`docstring` of the module. Defaults to ``None``. .. attribute:: __loader__ The :term:`loader` which loaded the module. Defaults to ``None``. This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader` as stored in the :attr:`__spec__` object. .. note:: A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the :attr:`__spec__` attribute instead or use ``getattr(module, ""__loader__"", None)`` if you explicitly need to use this attribute. .. versionchanged:: 3.4 Defaults to ``None``. Previously the attribute was optional. .. attribute:: __name__ The name of the module. Expected to match :attr:`importlib.machinery.ModuleSpec.name`. .. attribute:: __package__ Which :term:`package` a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to ``''``, else it should be set to the name of the package (which can be :attr:`__name__` if the module is a package itself). Defaults to ``None``. This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent` as stored in the :attr:`__spec__` object. .. note:: A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the :attr:`__spec__` attribute instead or use ``getattr(module, ""__package__"", None)`` if you explicitly need to use this attribute. .. versionchanged:: 3.4 Defaults to ``None``. Previously the attribute was optional. .. attribute:: __spec__ A record of the module's import-system-related state. Expected to be an instance of :class:`importlib.machinery.ModuleSpec`. .. versionadded:: 3.4 .. data:: EllipsisType The type of :data:`Ellipsis`. .. versionadded:: 3.10 .. class:: GenericAlias(t_origin, t_args) The type of :ref:`parameterized generics ` such as ``list[int]``. ``t_origin`` should be a non-parameterized generic class, such as ``list``, ``tuple`` or ``dict``. ``t_args`` should be a :class:`tuple` (possibly of length 1) of types which parameterize ``t_origin``:: >>> from types import GenericAlias >>> list[int] == GenericAlias(list, (int,)) True >>> dict[str, int] == GenericAlias(dict, (str, int)) True .. versionadded:: 3.9 .. versionchanged:: 3.9.2 This type can now be subclassed. .. seealso:: :ref:`Generic Alias Types` In-depth documentation on instances of :class:`!types.GenericAlias` :pep:`585` - Type Hinting Generics In Standard Collections Introducing the :class:`!types.GenericAlias` class .. class:: UnionType The type of :ref:`union type expressions`. .. versionadded:: 3.10 .. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno) The type of traceback objects such as found in ``sys.exception().__traceback__``. See :ref:`the language reference ` for details of the available attributes and operations, and guidance on creating tracebacks dynamically. .. data:: FrameType The type of :ref:`frame objects ` such as found in :attr:`tb.tb_frame ` if ``tb`` is a traceback object. .. data:: GetSetDescriptorType The type of objects defined in extension modules with ``PyGetSetDef``, such as :attr:`FrameType.f_locals ` or ``array.array.typecode``. This type is used as descriptor for object attributes; it has the same purpose as the :class:`property` type, but for classes defined in extension modules. .. data:: MemberDescriptorType The type of objects defined in extension modules with ``PyMemberDef``, such as ``datetime.timedelta.days``. This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the :class:`property` type, but for classes defined in extension modules. In addition, when a class is defined with a :attr:`~object.__slots__` attribute, then for each slot, an instance of :class:`!MemberDescriptorType` will be added as an attribute on the class. This allows the slot to appear in the class's :attr:`~type.__dict__`. .. impl-detail:: In other implementations of Python, this type may be identical to ``GetSetDescriptorType``. .. class:: MappingProxyType(mapping) Read-only proxy of a mapping. It provides a dynamic view on the mapping's entries, which means that when the mapping changes, the view reflects these changes. .. versionadded:: 3.3 .. versionchanged:: 3.9 Updated to support the new union (``|``) operator from :pep:`584`, which simply delegates to the underlying mapping. .. describe:: key in proxy Return ``True`` if the underlying mapping has a key *key*, else ``False``. .. describe:: proxy[key] Return the item of the underlying mapping with key *key*. Raises a :exc:`KeyError` if *key* is not in the underlying mapping. .. describe:: iter(proxy) Return an iterator over the keys of the underlying mapping. This is a shortcut for ``iter(proxy.keys())``. .. describe:: len(proxy) Return the number of items in the underlying mapping. .. method:: copy() Return a shallow copy of the underlying mapping. .. method:: get(key[, default]) Return the value for *key* if *key* is in the underlying mapping, else *default*. If *default* is not given, it defaults to ``None``, so that this method never raises a :exc:`KeyError`. .. method:: items() Return a new view of the underlying mapping's items (``(key, value)`` pairs). .. method:: keys() Return a new view of the underlying mapping's keys. .. method:: values() Return a new view of the underlying mapping's values. .. describe:: reversed(proxy) Return a reverse iterator over the keys of the underlying mapping. .. versionadded:: 3.9 .. describe:: hash(proxy) Return a hash of the underlying mapping. .. versionadded:: 3.12 .. class:: CapsuleType The type of :ref:`capsule objects `. .. versionadded:: 3.13 ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/types.rst#codepoints:7992:14505"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-library-types.rst-4,dp-Python-library-types.rst,"Additional Utility Classes and Functions ---------------------------------------- .. class:: SimpleNamespace A simple :class:`object` subclass that provides attribute access to its namespace, as well as a meaningful repr. Unlike :class:`object`, with :class:`!SimpleNamespace` you can add and remove attributes. :py:class:`SimpleNamespace` objects may be initialized in the same way as :class:`dict`: either with keyword arguments, with a single positional argument, or with both. When initialized with keyword arguments, those are directly added to the underlying namespace. Alternatively, when initialized with a positional argument, the underlying namespace will be updated with key-value pairs from that argument (either a mapping object or an :term:`iterable` object producing key-value pairs). All such keys must be strings. The type is roughly equivalent to the following code:: class SimpleNamespace: def __init__(self, mapping_or_iterable=(), /, **kwargs): self.__dict__.update(mapping_or_iterable) self.__dict__.update(kwargs) def __repr__(self): items = (f""{k}={v!r}"" for k, v in self.__dict__.items()) return ""{}({})"".format(type(self).__name__, "", "".join(items)) def __eq__(self, other): if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace): return self.__dict__ == other.__dict__ return NotImplemented ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``. However, for a structured record type use :func:`~collections.namedtuple` instead. :class:`!SimpleNamespace` objects are supported by :func:`copy.replace`. .. versionadded:: 3.3 .. versionchanged:: 3.9 Attribute order in the repr changed from alphabetical to insertion (like ``dict``). .. versionchanged:: 3.13 Added support for an optional positional argument. .. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None) Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class's __getattr__ method; this is done by raising AttributeError. This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see :class:`enum.Enum` for an example). .. versionadded:: 3.4 Coroutine Utility Functions --------------------------- .. function:: coroutine(gen_func) This function transforms a :term:`generator` function into a :term:`coroutine function` which returns a generator-based coroutine. The generator-based coroutine is still a :term:`generator iterator`, but is also considered to be a :term:`coroutine` object and is :term:`awaitable`. However, it may not necessarily implement the :meth:`~object.__await__` method. If *gen_func* is a generator function, it will be modified in-place. If *gen_func* is not a generator function, it will be wrapped. If it returns an instance of :class:`collections.abc.Generator`, the instance will be wrapped in an *awaitable* proxy object. All other types of objects will be returned as is. .. versionadded:: 3.5 ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/types.rst#codepoints:14505:17983"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-library-types.rst-3,dp-Python-library-types.rst," The :term:`docstring` of the module. Defaults to ``None``. .. attribute:: __loader__ The :term:`loader` which loaded the module. Defaults to ``None``. This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader` as stored in the :attr:`__spec__` object. .. note:: A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the :attr:`__spec__` attribute instead or use ``getattr(module, ""__loader__"", None)`` if you explicitly need to use this attribute. .. versionchanged:: 3.4 Defaults to ``None``. Previously the attribute was optional. .. attribute:: __name__ The name of the module. Expected to match :attr:`importlib.machinery.ModuleSpec.name`. .. attribute:: __package__ Which :term:`package` a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to ``''``, else it should be set to the name of the package (which can be :attr:`__name__` if the module is a package itself). Defaults to ``None``. This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent` as stored in the :attr:`__spec__` object. .. note:: A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the :attr:`__spec__` attribute instead or use ``getattr(module, ""__package__"", None)`` if you explicitly need to use this attribute. .. versionchanged:: 3.4 Defaults to ``None``. Previously the attribute was optional. .. attribute:: __spec__ A record of the module's import-system-related state. Expected to be an instance of :class:`importlib.machinery.ModuleSpec`. .. versionadded:: 3.4 .. data:: EllipsisType The type of :data:`Ellipsis`. .. versionadded:: 3.10 .. class:: GenericAlias(t_origin, t_args) The type of :ref:`parameterized generics ` such as ``list[int]``. ``t_origin`` should be a non-parameterized generic class, such as ``list``, ``tuple`` or ``dict``. ``t_args`` should be a :class:`tuple` (possibly of length 1) of types which parameterize ``t_origin``:: >>> from types import GenericAlias >>> list[int] == GenericAlias(list, (int,)) True >>> dict[str, int] == GenericAlias(dict, (str, int)) True .. versionadded:: 3.9 .. versionchanged:: 3.9.2 This type can now be subclassed. .. seealso:: :ref:`Generic Alias Types` In-depth documentation on instances of :class:`!types.GenericAlias` :pep:`585` - Type Hinting Generics In Standard Collections Introducing the :class:`!types.GenericAlias` class .. class:: UnionType The type of :ref:`union type expressions`. .. versionadded:: 3.10 .. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno) The type of traceback objects such as found in ``sys.exception().__traceback__``. See :ref:`the language reference ` for details of the available attributes and operations, and guidance on creating tracebacks dynamically. .. data:: FrameType The type of :ref:`frame objects ` such as found in :attr:`tb.tb_frame ` if ``tb`` is a traceback object. .. data:: GetSetDescriptorType The type of objects defined in extension modules with ``PyGetSetDef``, such as :attr:`FrameType.f_locals ` or ``array.array.typecode``. This type is used as descriptor for object attributes; it has the same purpose as the :class:`property` type, but for classes defined in extension modules. .. data:: MemberDescriptorType The type of objects defined in extension modules with ``PyMemberDef``, such as ``datetime.timedelta.days``. This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the :class:`property` type, but for classes defined in extension modules. In addition, when a class is defined with a :attr:`~object.__slots__` attribute, then for each slot, an instance of :class:`!MemberDescriptorType` will be added as an attribute on the class. This allows the slot to appear in the class's :attr:`~type.__dict__`. .. impl-detail:: In other implementations of Python, this type may be identical to ``GetSetDescriptorType``. .. class:: MappingProxyType(mapping) Read-only proxy of a mapping. It provides a dynamic view on the mapping's entries, which means that when the mapping changes, the view reflects these changes. .. versionadded:: 3.3 .. versionchanged:: 3.9 Updated to support the new union (``|``) operator from :pep:`584`, which simply delegates to the underlying mapping. .. describe:: key in proxy Return ``True`` if the underlying mapping has a key *key*, else ``False``. .. describe:: proxy[key] Return the item of the underlying mapping with key *key*. Raises a :exc:`KeyError` if *key* is not in the underlying mapping. .. describe:: iter(proxy) Return an iterator over the keys of the underlying mapping. This is a shortcut for ``iter(proxy.keys())``. .. describe:: len(proxy) Return the number of items in the underlying mapping. .. method:: copy() Return a shallow copy of the underlying mapping. .. method:: get(key[, default]) Return the value for *key* if *key* is in the underlying mapping, else *default*. If *default* is not given, it defaults to ``None``, so that this method never raises a :exc:`KeyError`. .. method:: items() Return a new view of the underlying mapping's items (``(key, value)`` pairs). .. method:: keys() Return a new view of the underlying mapping's keys. .. method:: values() Return a new view of the underlying mapping's values. .. describe:: reversed(proxy) Return a reverse iterator over the keys of the underlying mapping. .. versionadded:: 3.9 .. describe:: hash(proxy) Return a hash of the underlying mapping. .. versionadded:: 3.12 ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/types.rst#codepoints:7992:14403"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.12-library-types.rst-4,dp-Python-library-types.rst,"Additional Utility Classes and Functions ---------------------------------------- .. class:: SimpleNamespace A simple :class:`object` subclass that provides attribute access to its namespace, as well as a meaningful repr. Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove attributes. If a ``SimpleNamespace`` object is initialized with keyword arguments, those are directly added to the underlying namespace. The type is roughly equivalent to the following code:: class SimpleNamespace: def __init__(self, /, **kwargs): self.__dict__.update(kwargs) def __repr__(self): items = (f""{k}={v!r}"" for k, v in self.__dict__.items()) return ""{}({})"".format(type(self).__name__, "", "".join(items)) def __eq__(self, other): if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace): return self.__dict__ == other.__dict__ return NotImplemented ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``. However, for a structured record type use :func:`~collections.namedtuple` instead. .. versionadded:: 3.3 .. versionchanged:: 3.9 Attribute order in the repr changed from alphabetical to insertion (like ``dict``). .. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None) Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class's __getattr__ method; this is done by raising AttributeError. This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see :class:`enum.Enum` for an example). .. versionadded:: 3.4 Coroutine Utility Functions --------------------------- .. function:: coroutine(gen_func) This function transforms a :term:`generator` function into a :term:`coroutine function` which returns a generator-based coroutine. The generator-based coroutine is still a :term:`generator iterator`, but is also considered to be a :term:`coroutine` object and is :term:`awaitable`. However, it may not necessarily implement the :meth:`~object.__await__` method. If *gen_func* is a generator function, it will be modified in-place. If *gen_func* is not a generator function, it will be wrapped. If it returns an instance of :class:`collections.abc.Generator`, the instance will be wrapped in an *awaitable* proxy object. All other types of objects will be returned as is. .. versionadded:: 3.5 ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/library/types.rst#codepoints:14403:17210"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:library/types.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-library-urllib.rst-0,dp-Python-library-urllib.rst,":mod:`!urllib` --- URL handling modules ======================================= .. module:: urllib **Source code:** :source:`Lib/urllib/` -------------- ``urllib`` is a package that collects several modules for working with URLs: * :mod:`urllib.request` for opening and reading URLs * :mod:`urllib.error` containing the exceptions raised by :mod:`urllib.request` * :mod:`urllib.parse` for parsing URLs * :mod:`urllib.robotparser` for parsing ``robots.txt`` files ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/library/urllib.rst#codepoints:0:468"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:library/urllib.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-0,dp-Python-tutorial-inputoutput.rst,".. _tut-io: **************** 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. .. _tut-formatting: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:0:283"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-1,dp-Python-tutorial-inputoutput.rst,"Fancier Output Formatting ========================= So far we've encountered two ways of writing values: *expression statements* and the :func:`print` function. (A third way is using the :meth:`~io.TextIOBase.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 :ref:`formatted string literals `, 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 :meth:`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. In the following code block there are two examples of how to format variables: :: >>> yes_votes = 42_572_654 >>> total_votes = 85_705_149 >>> percentage = yes_votes / total_votes >>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) ' 42572654 YES votes 49.67%' Notice how the ``yes_votes`` are padded with spaces and a negative sign only for negative numbers. The example also prints ``percentage`` multiplied by 100, with 2 decimal places and followed by a percent sign (see :ref:`formatspec` for details). * 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 :func:`repr` or :func:`str` functions. The :func:`str` function is meant to return representations of values which are fairly human-readable, while :func:`repr` is meant to generate representations which can be read by the interpreter (or will force a :exc:`SyntaxError` if there is no equivalent syntax). For objects which don't have a particular representation for human consumption, :func:`str` will return the same value as :func:`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 :mod:`string` module contains a :class:`~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. .. _tut-f-strings: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:283:4024"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-2,dp-Python-tutorial-inputoutput.rst,"Formatted String Literals ------------------------- :ref:`Formatted string literals ` (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 :func:`ascii`, ``'!s'`` applies :func:`str`, and ``'!r'`` applies :func:`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'. The ``=`` specifier can be used to expand an expression to the text of the expression, an equal sign, then the representation of the evaluated expression: >>> bugs = 'roaches' >>> count = 13 >>> area = 'living room' >>> print(f'Debugging {bugs=} {count=} {area=}') Debugging bugs='roaches' count=13 area='living room' See :ref:`self-documenting expressions ` for more information on the ``=`` specifier. For a reference on these format specifications, see the reference guide for the :ref:`formatspec`. .. _tut-string-format: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:4024:5957"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-3,dp-Python-tutorial-inputoutput.rst,"The String format() Method -------------------------- Basic usage of the :meth:`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 :meth:`str.format` method. A number in the brackets can be used to refer to the position of the object passed into the :meth:`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 :meth:`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`` dictionary 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 :func:`vars`, which returns a dictionary containing all local variables:: >>> table = {k: str(v) for k, v in vars().items()} >>> message = "" "".join([f'{k}: ' + '{' + k +'};' for k in table.keys()]) >>> print(message.format(**table)) __name__: __main__; __doc__: None; __package__: None; __loader__: ... 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 :meth:`str.format`, see :ref:`formatstrings`. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:5957:8768"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-4,dp-Python-tutorial-inputoutput.rst,"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 :func:`print` works: it always adds spaces between its arguments.) The :meth:`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 :meth:`str.ljust` and :meth:`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, :meth:`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' Old string formatting --------------------- The % operator (modulo) can also be used for string formatting. Given ``format % values`` (where *format* is a string), ``%`` conversion specifications in *format* 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 :ref:`old-string-formatting` section. .. _tut-files: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:8768:10755"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-5,dp-Python-tutorial-inputoutput.rst,"Reading and Writing Files ========================= .. index:: pair: built-in function; open pair: object; file :func:`open` returns a :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"") .. XXX str(f) is >>> print(f) 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 :dfn:`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 :func:`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 :dfn:`binary mode`. Binary mode data is read and written as :class:`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 :file:`JPEG` or :file:`EXE` files. Be very careful to use binary mode when reading and writing such files. It is good practice to use the :keyword:`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 :keyword:`!with` is also much shorter than writing equivalent :keyword:`try`\ -\ :keyword:`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 :keyword:`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 :keyword:`!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. .. See also https://bugs.python.org/issue17852 After a file object is closed, either by a :keyword:`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 """", line 1, in ValueError: I/O operation on closed file. .. _tut-filemethods: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:10755:14134"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-6,dp-Python-tutorial-inputoutput.rst,"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 :meth:`~io.IOBase.isatty` and :meth:`~io.IOBase.truncate` which are less frequently used; consult the Library Reference for a complete guide to file objects. .. _tut-json: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:14134:17752"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-tutorial-inputoutput.rst-7,dp-Python-tutorial-inputoutput.rst,"Saving structured data with :mod:`json` --------------------------------------- .. index:: pair: module; json Strings can easily be written to and read from a file. Numbers take a bit more effort, since the :meth:`~io.TextIOBase.read` method only returns strings, which will have to be passed to a function like :func:`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) `_. The standard module called :mod:`json` can take Python data hierarchies, and convert them to string representations; this process is called :dfn:`serializing`. Reconstructing the data from the string representation is called :dfn:`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 :func:`~json.dumps` function, called :func:`~json.dump`, simply serializes the object to a :term:`text file`. So if ``f`` is a :term:`text file` object opened for writing, we can do this:: json.dump(x, f) To decode the object again, if ``f`` is a :term:`binary file` or :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 :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 :mod:`json` module contains an explanation of this. .. seealso:: :mod:`pickle` - the pickle module Contrary to :ref:`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. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/tutorial/inputoutput.rst#codepoints:17752:20596"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:tutorial/inputoutput.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-using-index.rst-0,dp-Python-using-index.rst,".. _using-index: ########################## 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. .. toctree:: :numbered: :maxdepth: 2 cmdline.rst unix.rst configure.rst windows.rst mac.rst android.rst ios.rst editors.rst ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/using/index.rst#codepoints:0:467"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:using/index.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-using-index.rst-0,dp-Python-using-index.rst,".. _using-index: ########################## 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. .. toctree:: :numbered: cmdline.rst unix.rst configure.rst windows.rst mac.rst editors.rst ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/using/index.rst#codepoints:0:425"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:using/index.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-0,dp-Python-whatsnew-3.10.rst,"**************************** What's New In Python 3.10 **************************** :Editor: Pablo Galindo Salgado .. Rules for maintenance: * Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree. * The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file. * This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.) * If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section. * It's OK to just add a fragmentary note about a change. For example: ""XXX Describe the transmogrify() function added to the socket module."" The maintainer will research the change and write the necessary text. * You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away). * Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary. * It's helpful to add the bug/patch number as a comment: XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in :issue:`12345`.) This saves the maintainer the effort of going through the git log when researching a change. This article explains the new features in Python 3.10, compared to 3.9. Python 3.10 was released on October 4, 2021. For full details, see the :ref:`changelog `. Summary -- Release highlights ============================= .. This section singles out the most important changes in Python 3.10. Brevity is key. .. PEP-sized items next. New syntax features: * :pep:`634`, Structural Pattern Matching: Specification * :pep:`635`, Structural Pattern Matching: Motivation and Rationale * :pep:`636`, Structural Pattern Matching: Tutorial * :issue:`12782`, Parenthesized context managers are now officially allowed. New features in the standard library: * :pep:`618`, Add Optional Length-Checking To zip. Interpreter improvements: * :pep:`626`, Precise line numbers for debugging and other tools. New typing features: * :pep:`604`, Allow writing union types as X | Y * :pep:`612`, Parameter Specification Variables * :pep:`613`, Explicit Type Aliases * :pep:`647`, User-Defined Type Guards Important deprecations, removals or restrictions: * :pep:`644`, Require OpenSSL 1.1.1 or newer * :pep:`632`, Deprecate distutils module. * :pep:`623`, Deprecate and prepare for the removal of the wstr member in PyUnicodeObject. * :pep:`624`, Remove Py_UNICODE encoder APIs * :pep:`597`, Add optional EncodingWarning New Features ============ .. _whatsnew310-pep563: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:0:3089"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-1,dp-Python-whatsnew-3.10.rst,"Parenthesized context managers ------------------------------ Using enclosing parentheses for continuation across multiple lines in context managers is now supported. This allows formatting a long collection of context managers in multiple lines in a similar way as it was previously possible with import statements. For instance, all these examples are now valid: .. code-block:: python with (CtxManager() as example): ... with ( CtxManager1(), CtxManager2() ): ... with (CtxManager1() as example, CtxManager2()): ... with (CtxManager1(), CtxManager2() as example): ... with ( CtxManager1() as example1, CtxManager2() as example2 ): ... it is also possible to use a trailing comma at the end of the enclosed group: .. code-block:: python with ( CtxManager1() as example1, CtxManager2() as example2, CtxManager3() as example3, ): ... This new syntax uses the non LL(1) capacities of the new parser. Check :pep:`617` for more details. (Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou in :issue:`12782` and :issue:`40334`.) Better error messages --------------------- ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:3089:4352"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-2,dp-Python-whatsnew-3.10.rst,"SyntaxErrors ~~~~~~~~~~~~ When parsing code that contains unclosed parentheses or brackets the interpreter now includes the location of the unclosed bracket of parentheses instead of displaying *SyntaxError: unexpected EOF while parsing* or pointing to some incorrect location. For instance, consider the following code (notice the unclosed '{'): .. code-block:: python expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6, some_other_code = foo() Previous versions of the interpreter reported confusing places as the location of the syntax error: .. code-block:: python File ""example.py"", line 3 some_other_code = foo() ^ SyntaxError: invalid syntax but in Python 3.10 a more informative error is emitted: .. code-block:: python File ""example.py"", line 1 expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, ^ SyntaxError: '{' was never closed In a similar way, errors involving unclosed string literals (single and triple quoted) now point to the start of the string instead of reporting EOF/EOL. These improvements are inspired by previous work in the PyPy interpreter. (Contributed by Pablo Galindo in :issue:`42864` and Batuhan Taskaya in :issue:`40176`.) :exc:`SyntaxError` exceptions raised by the interpreter will now highlight the full error range of the expression that constitutes the syntax error itself, instead of just where the problem is detected. In this way, instead of displaying (before Python 3.10): .. code-block:: python >>> foo(x, z for z in range(10), t, w) File """", line 1 foo(x, z for z in range(10), t, w) ^ SyntaxError: Generator expression must be parenthesized now Python 3.10 will display the exception as: .. code-block:: python >>> foo(x, z for z in range(10), t, w) File """", line 1 foo(x, z for z in range(10), t, w) ^^^^^^^^^^^^^^^^^^^^ SyntaxError: Generator expression must be parenthesized This improvement was contributed by Pablo Galindo in :issue:`43914`. A considerable amount of new specialized messages for :exc:`SyntaxError` exceptions have been incorporated. Some of the most notable ones are as follows: * Missing ``:`` before blocks: .. code-block:: python >>> if rocket.position > event_horizon File """", line 1 if rocket.position > event_horizon ^ SyntaxError: expected ':' (Contributed by Pablo Galindo in :issue:`42997`.) * Unparenthesised tuples in comprehensions targets: .. code-block:: python >>> {x,y for x,y in zip('abcd', '1234')} File """", line 1 {x,y for x,y in zip('abcd', '1234')} ^ SyntaxError: did you forget parentheses around the comprehension target? (Contributed by Pablo Galindo in :issue:`43017`.) * Missing commas in collection literals and between expressions: .. code-block:: python >>> items = { ... x: 1, ... y: 2 ... z: 3, File """", line 3 y: 2 ^ SyntaxError: invalid syntax. Perhaps you forgot a comma? (Contributed by Pablo Galindo in :issue:`43822`.) * Multiple Exception types without parentheses: .. code-block:: python >>> try: ... build_dyson_sphere() ... except NotEnoughScienceError, NotEnoughResourcesError: File """", line 3 except NotEnoughScienceError, NotEnoughResourcesError: ^ SyntaxError: multiple exception types must be parenthesized (Contributed by Pablo Galindo in :issue:`43149`.) * Missing ``:`` and values in dictionary literals: .. code-block:: python >>> values = { ... x: 1, ... y: 2, ... z: ... } File """", line 4 z: ^ SyntaxError: expression expected after dictionary key and ':' >>> values = {x:1, y:2, z w:3} File """", line 1 values = {x:1, y:2, z w:3} ^ SyntaxError: ':' expected after dictionary key (Contributed by Pablo Galindo in :issue:`43823`.) * ``try`` blocks without ``except`` or ``finally`` blocks: .. code-block:: python >>> try: ... x = 2 ... something = 3 File """", line 3 something = 3 ^^^^^^^^^ SyntaxError: expected 'except' or 'finally' block (Contributed by Pablo Galindo in :issue:`44305`.) * Usage of ``=`` instead of ``==`` in comparisons: .. code-block:: python >>> if rocket.position = event_horizon: File """", line 1 if rocket.position = event_horizon: ^ SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='? (Contributed by Pablo Galindo in :issue:`43797`.) * Usage of ``*`` in f-strings: .. code-block:: python >>> f""Black holes {*all_black_holes} and revelations"" File """", line 1 (*all_black_holes) ^ SyntaxError: f-string: cannot use starred expression here (Contributed by Pablo Galindo in :issue:`41064`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:4352:9656"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-3,dp-Python-whatsnew-3.10.rst,"IndentationErrors ~~~~~~~~~~~~~~~~~ Many :exc:`IndentationError` exceptions now have more context regarding what kind of block was expecting an indentation, including the location of the statement: .. code-block:: python >>> def foo(): ... if lel: ... x = 2 File """", line 3 x = 2 ^ IndentationError: expected an indented block after 'if' statement in line 2 AttributeErrors ~~~~~~~~~~~~~~~ When printing :exc:`AttributeError`, :c:func:`!PyErr_Display` will offer suggestions of similar attribute names in the object that the exception was raised from: .. code-block:: python >>> collections.namedtoplo Traceback (most recent call last): File """", line 1, in AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple? (Contributed by Pablo Galindo in :issue:`38530`.) .. warning:: Notice this won't work if :c:func:`!PyErr_Display` is not called to display the error which can happen if some other custom error display function is used. This is a common scenario in some REPLs like IPython. NameErrors ~~~~~~~~~~ When printing :exc:`NameError` raised by the interpreter, :c:func:`!PyErr_Display` will offer suggestions of similar variable names in the function that the exception was raised from: .. code-block:: python >>> schwarzschild_black_hole = None >>> schwarschild_black_hole Traceback (most recent call last): File """", line 1, in NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole? (Contributed by Pablo Galindo in :issue:`38530`.) .. warning:: Notice this won't work if :c:func:`!PyErr_Display` is not called to display the error, which can happen if some other custom error display function is used. This is a common scenario in some REPLs like IPython. PEP 626: Precise line numbers for debugging and other tools ----------------------------------------------------------- PEP 626 brings more precise and reliable line numbers for debugging, profiling and coverage tools. Tracing events, with the correct line number, are generated for all lines of code executed and only for lines of code that are executed. The :attr:`~frame.f_lineno` attribute of frame objects will always contain the expected line number. The :attr:`~codeobject.co_lnotab` attribute of :ref:`code objects ` is deprecated and will be removed in 3.12. Code that needs to convert from offset to line number should use the new :meth:`~codeobject.co_lines` method instead. PEP 634: Structural Pattern Matching ------------------------------------ Structural pattern matching has been added in the form of a *match statement* and *case statements* of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. Pattern matching enables programs to extract information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:9656:12742"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-4,dp-Python-whatsnew-3.10.rst,"Syntax and operations ~~~~~~~~~~~~~~~~~~~~~ The generic syntax of pattern matching is:: match subject: case : case : case : case _: A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. Specifically, pattern matching operates by: 1. using data with type and shape (the ``subject``) 2. evaluating the ``subject`` in the ``match`` statement 3. comparing the subject with each pattern in a ``case`` statement from top to bottom until a match is confirmed. 4. executing the action associated with the pattern of the confirmed match 5. If an exact match is not confirmed, the last case, a wildcard ``_``, if provided, will be used as the matching case. If an exact match is not confirmed and a wildcard case does not exist, the entire match block is a no-op. Declarative approach ~~~~~~~~~~~~~~~~~~~~ Readers may be aware of pattern matching through the simple example of matching a subject (data object) to a literal (pattern) with the switch statement found in C, Java or JavaScript (and many other languages). Often the switch statement is used for comparison of an object/expression with case statements containing literals. More powerful examples of pattern matching can be found in languages such as Scala and Elixir. With structural pattern matching, the approach is ""declarative"" and explicitly states the conditions (the patterns) for data to match. While an ""imperative"" series of instructions using nested ""if"" statements could be used to accomplish something similar to structural pattern matching, it is less clear than the ""declarative"" approach. Instead the ""declarative"" approach states the conditions to meet for a match and is more readable through its explicit patterns. While structural pattern matching can be used in its simplest form comparing a variable to a literal in a case statement, its true value for Python lies in its handling of the subject's type and shape. Simple pattern: match to a literal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Let's look at this example as pattern matching in its simplest form: a value, the subject, being matched to several literals, the patterns. In the example below, ``status`` is the subject of the match statement. The patterns are each of the case statements, where literals represent request status codes. The associated action to the case is executed after a match:: def http_error(status): match status: case 400: return ""Bad request"" case 404: return ""Not found"" case 418: return ""I'm a teapot"" case _: return ""Something's wrong with the internet"" If the above function is passed a ``status`` of 418, ""I'm a teapot"" is returned. If the above function is passed a ``status`` of 500, the case statement with ``_`` will match as a wildcard, and ""Something's wrong with the internet"" is returned. Note the last block: the variable name, ``_``, acts as a *wildcard* and insures the subject will always match. The use of ``_`` is optional. You can combine several literals in a single pattern using ``|`` (""or""):: case 401 | 403 | 404: return ""Not allowed"" Behavior without the wildcard ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If we modify the above example by removing the last case block, the example becomes:: def http_error(status): match status: case 400: return ""Bad request"" case 404: return ""Not found"" case 418: return ""I'm a teapot"" Without the use of ``_`` in a case statement, a match may not exist. If no match exists, the behavior is a no-op. For example, if ``status`` of 500 is passed, a no-op occurs. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:12742:16736"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-5,dp-Python-whatsnew-3.10.rst,"Patterns with a literal and variable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Patterns can look like unpacking assignments, and a pattern may be used to bind variables. In this example, a data point can be unpacked to its x-coordinate and y-coordinate:: # point is an (x, y) tuple match point: case (0, 0): print(""Origin"") case (0, y): print(f""Y={y}"") case (x, 0): print(f""X={x}"") case (x, y): print(f""X={x}, Y={y}"") case _: raise ValueError(""Not a point"") The first pattern has two literals, ``(0, 0)``, and may be thought of as an extension of the literal pattern shown above. The next two patterns combine a literal and a variable, and the variable *binds* a value from the subject (``point``). The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment ``(x, y) = point``. Patterns and classes ~~~~~~~~~~~~~~~~~~~~ If you are using classes to structure your data, you can use as a pattern the class name followed by an argument list resembling a constructor. This pattern has the ability to capture class attributes into variables:: class Point: x: int y: int def location(point): match point: case Point(x=0, y=0): print(""Origin is the point's location."") case Point(x=0, y=y): print(f""Y={y} and the point is on the y-axis."") case Point(x=x, y=0): print(f""X={x} and the point is on the x-axis."") case Point(): print(""The point is located somewhere else on the plane."") case _: print(""Not a point"") Patterns with positional parameters ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the ``__match_args__`` special attribute in your classes. If it's set to (""x"", ""y""), the following patterns are all equivalent (and all bind the ``y`` attribute to the ``var`` variable):: Point(1, var) Point(1, y=var) Point(x=1, y=var) Point(y=var, x=1) Nested patterns ~~~~~~~~~~~~~~~ Patterns can be arbitrarily nested. For example, if our data is a short list of points, it could be matched like this:: match points: case []: print(""No points in the list."") case [Point(0, 0)]: print(""The origin is the only point in the list."") case [Point(x, y)]: print(f""A single point {x}, {y} is in the list."") case [Point(0, y1), Point(0, y2)]: print(f""Two points on the Y axis at {y1}, {y2} are in the list."") case _: print(""Something else is found in the list."") Complex patterns and the wildcard ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To this point, the examples have used ``_`` alone in the last case statement. A wildcard can be used in more complex patterns, such as ``('error', code, _)``. For example:: match test_variable: case ('warning', code, 40): print(""A warning has been received."") case ('error', code, _): print(f""An error {code} occurred."") In the above case, ``test_variable`` will match for ('error', code, 100) and ('error', code, 800). Guard ~~~~~ We can add an ``if`` clause to a pattern, known as a ""guard"". If the guard is false, ``match`` goes on to try the next case block. Note that value capture happens before the guard is evaluated:: match point: case Point(x, y) if x == y: print(f""The point is located on the diagonal Y=X at {x}."") case Point(x, y): print(f""Point is not on the diagonal."") ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:16736:20574"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-6,dp-Python-whatsnew-3.10.rst,"Other Key Features ~~~~~~~~~~~~~~~~~~ Several other key features: - Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. Technically, the subject must be a sequence. Therefore, an important exception is that patterns don't match iterators. Also, to prevent a common mistake, sequence patterns don't match strings. - Sequence patterns support wildcards: ``[x, y, *rest]`` and ``(x, y, *rest)`` work similar to wildcards in unpacking assignments. The name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence of at least two items without binding the remaining items. - Mapping patterns: ``{""bandwidth"": b, ""latency"": l}`` captures the ``""bandwidth""`` and ``""latency""`` values from a dict. Unlike sequence patterns, extra keys are ignored. A wildcard ``**rest`` is also supported. (But ``**_`` would be redundant, so is not allowed.) - Subpatterns may be captured using the ``as`` keyword:: case (Point(x1, y1), Point(x2, y2) as p2): ... This binds x1, y1, x2, y2 like you would expect without the ``as`` clause, and p2 to the entire second item of the subject. - Most literals are compared by equality. However, the singletons ``True``, ``False`` and ``None`` are compared by identity. - Named constants may be used in patterns. These named constants must be dotted names to prevent the constant from being interpreted as a capture variable:: from enum import Enum class Color(Enum): RED = 0 GREEN = 1 BLUE = 2 color = Color.GREEN match color: case Color.RED: print(""I see red!"") case Color.GREEN: print(""Grass is green"") case Color.BLUE: print(""I'm feeling the blues :("") For the full specification see :pep:`634`. Motivation and rationale are in :pep:`635`, and a longer tutorial is in :pep:`636`. .. _whatsnew310-pep597: Optional ``EncodingWarning`` and ``encoding=""locale""`` option ------------------------------------------------------------- The default encoding of :class:`~io.TextIOWrapper` and :func:`open` is platform and locale dependent. Since UTF-8 is used on most Unix platforms, omitting ``encoding`` option when opening UTF-8 files (e.g. JSON, YAML, TOML, Markdown) is a very common bug. For example:: # BUG: ""rb"" mode or encoding=""utf-8"" should be used. with open(""data.json"") as f: data = json.load(f) To find this type of bug, an optional ``EncodingWarning`` is added. It is emitted when :data:`sys.flags.warn_default_encoding ` is true and locale-specific default encoding is used. ``-X warn_default_encoding`` option and :envvar:`PYTHONWARNDEFAULTENCODING` are added to enable the warning. See :ref:`io-text-encoding` for more information. .. _new-feat-related-type-hints: New Features Related to Type Hints ================================== This section covers major changes affecting :pep:`484` type hints and the :mod:`typing` module. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:20574:23634"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-7,dp-Python-whatsnew-3.10.rst,"PEP 604: New Type Union Operator -------------------------------- A new type union operator was introduced which enables the syntax ``X | Y``. This provides a cleaner way of expressing 'either type X or type Y' instead of using :data:`typing.Union`, especially in type hints. In previous versions of Python, to apply a type hint for functions accepting arguments of multiple types, :data:`typing.Union` was used:: def square(number: Union[int, float]) -> Union[int, float]: return number ** 2 Type hints can now be written in a more succinct manner:: def square(number: int | float) -> int | float: return number ** 2 This new syntax is also accepted as the second argument to :func:`isinstance` and :func:`issubclass`:: >>> isinstance(1, int | str) True See :ref:`types-union` and :pep:`604` for more details. (Contributed by Maggie Moss and Philippe Prados in :issue:`41428`, with additions by Yurii Karabas and Serhiy Storchaka in :issue:`44490`.) PEP 612: Parameter Specification Variables ------------------------------------------ Two new options to improve the information provided to static type checkers for :pep:`484`\ 's ``Callable`` have been added to the :mod:`typing` module. The first is the parameter specification variable. They are used to forward the parameter types of one callable to another callable -- a pattern commonly found in higher order functions and decorators. Examples of usage can be found in :class:`typing.ParamSpec`. Previously, there was no easy way to type annotate dependency of parameter types in such a precise manner. The second option is the new ``Concatenate`` operator. It's used in conjunction with parameter specification variables to type annotate a higher order callable which adds or removes parameters of another callable. Examples of usage can be found in :class:`typing.Concatenate`. See :class:`typing.Callable`, :class:`typing.ParamSpec`, :class:`typing.Concatenate`, :class:`typing.ParamSpecArgs`, :class:`typing.ParamSpecKwargs`, and :pep:`612` for more details. (Contributed by Ken Jin in :issue:`41559`, with minor enhancements by Jelle Zijlstra in :issue:`43783`. PEP written by Mark Mendoza.) PEP 613: TypeAlias ------------------ :pep:`484` introduced the concept of type aliases, only requiring them to be top-level unannotated assignments. This simplicity sometimes made it difficult for type checkers to distinguish between type aliases and ordinary assignments, especially when forward references or invalid types were involved. Compare:: StrCache = 'Cache[str]' # a type alias LOG_PREFIX = 'LOG[DEBUG]' # a module constant Now the :mod:`typing` module has a special value :data:`~typing.TypeAlias` which lets you declare type aliases more explicitly:: StrCache: TypeAlias = 'Cache[str]' # a type alias LOG_PREFIX = 'LOG[DEBUG]' # a module constant See :pep:`613` for more details. (Contributed by Mikhail Golubev in :issue:`41923`.) PEP 647: User-Defined Type Guards --------------------------------- :data:`~typing.TypeGuard` has been added to the :mod:`typing` module to annotate type guard functions and improve information provided to static type checkers during type narrowing. For more information, please see :data:`~typing.TypeGuard`\ 's documentation, and :pep:`647`. (Contributed by Ken Jin and Guido van Rossum in :issue:`43766`. PEP written by Eric Traut.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:23634:27047"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-8,dp-Python-whatsnew-3.10.rst,"Other Language Changes ====================== * The :class:`int` type has a new method :meth:`int.bit_count`, returning the number of ones in the binary expansion of a given integer, also known as the population count. (Contributed by Niklas Fiekas in :issue:`29882`.) * The views returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict.items` now all have a ``mapping`` attribute that gives a :class:`types.MappingProxyType` object wrapping the original dictionary. (Contributed by Dennis Sweeney in :issue:`40890`.) * :pep:`618`: The :func:`zip` function now has an optional ``strict`` flag, used to require that all the iterables have an equal length. * Builtin and extension functions that take integer arguments no longer accept :class:`~decimal.Decimal`\ s, :class:`~fractions.Fraction`\ s and other objects that can be converted to integers only with a loss (e.g. that have the :meth:`~object.__int__` method but do not have the :meth:`~object.__index__` method). (Contributed by Serhiy Storchaka in :issue:`37999`.) * If :func:`object.__ipow__` returns :data:`NotImplemented`, the operator will correctly fall back to :func:`object.__pow__` and :func:`object.__rpow__` as expected. (Contributed by Alex Shkop in :issue:`38302`.) * Assignment expressions can now be used unparenthesized within set literals and set comprehensions, as well as in sequence indexes (but not slices). * Functions have a new ``__builtins__`` attribute which is used to look for builtin symbols when a function is executed, instead of looking into ``__globals__['__builtins__']``. The attribute is initialized from ``__globals__[""__builtins__""]`` if it exists, else from the current builtins. (Contributed by Mark Shannon in :issue:`42990`.) * Two new builtin functions -- :func:`aiter` and :func:`anext` have been added to provide asynchronous counterparts to :func:`iter` and :func:`next`, respectively. (Contributed by Joshua Bronson, Daniel Pope, and Justin Wang in :issue:`31861`.) * Static methods (:func:`@staticmethod `) and class methods (:func:`@classmethod `) now inherit the method attributes (``__module__``, ``__name__``, ``__qualname__``, ``__doc__``, ``__annotations__``) and have a new ``__wrapped__`` attribute. Moreover, static methods are now callable as regular functions. (Contributed by Victor Stinner in :issue:`43682`.) * Annotations for complex targets (everything beside ``simple name`` targets defined by :pep:`526`) no longer cause any runtime effects with ``from __future__ import annotations``. (Contributed by Batuhan Taskaya in :issue:`42737`.) * Class and module objects now lazy-create empty annotations dicts on demand. The annotations dicts are stored in the object’s ``__dict__`` for backwards compatibility. This improves the best practices for working with ``__annotations__``; for more information, please see :ref:`annotations-howto`. (Contributed by Larry Hastings in :issue:`43901`.) * Annotations consist of ``yield``, ``yield from``, ``await`` or named expressions are now forbidden under ``from __future__ import annotations`` due to their side effects. (Contributed by Batuhan Taskaya in :issue:`42725`.) * Usage of unbound variables, ``super()`` and other expressions that might alter the processing of symbol table as annotations are now rendered effectless under ``from __future__ import annotations``. (Contributed by Batuhan Taskaya in :issue:`42725`.) * Hashes of NaN values of both :class:`float` type and :class:`decimal.Decimal` type now depend on object identity. Formerly, they always hashed to ``0`` even though NaN values are not equal to one another. This caused potentially quadratic runtime behavior due to excessive hash collisions when creating dictionaries and sets containing multiple NaNs. (Contributed by Raymond Hettinger in :issue:`43475`.) * A :exc:`SyntaxError` (instead of a :exc:`NameError`) will be raised when deleting the :const:`__debug__` constant. (Contributed by Donghee Na in :issue:`45000`.) * :exc:`SyntaxError` exceptions now have ``end_lineno`` and ``end_offset`` attributes. They will be ``None`` if not determined. (Contributed by Pablo Galindo in :issue:`43914`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:27047:31338"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-9,dp-Python-whatsnew-3.10.rst,"New Modules =========== * None. Improved Modules ================ asyncio ------- Add missing :meth:`~asyncio.events.AbstractEventLoop.connect_accepted_socket` method. (Contributed by Alex Grönholm in :issue:`41332`.) argparse -------- Misleading phrase ""optional arguments"" was replaced with ""options"" in argparse help. Some tests might require adaptation if they rely on exact output match. (Contributed by Raymond Hettinger in :issue:`9694`.) array ----- The :meth:`~array.array.index` method of :class:`array.array` now has optional *start* and *stop* parameters. (Contributed by Anders Lorentsen and Zackery Spytz in :issue:`31956`.) asynchat, asyncore, smtpd ------------------------- These modules have been marked as deprecated in their module documentation since Python 3.6. An import-time :class:`DeprecationWarning` has now been added to all three of these modules. base64 ------ Add :func:`base64.b32hexencode` and :func:`base64.b32hexdecode` to support the Base32 Encoding with Extended Hex Alphabet. bdb --- Add :meth:`~bdb.Breakpoint.clearBreakpoints` to reset all set breakpoints. (Contributed by Irit Katriel in :issue:`24160`.) bisect ------ Added the possibility of providing a *key* function to the APIs in the :mod:`bisect` module. (Contributed by Raymond Hettinger in :issue:`4356`.) codecs ------ Add a :func:`codecs.unregister` function to unregister a codec search function. (Contributed by Hai Shi in :issue:`41842`.) collections.abc --------------- The ``__args__`` of the :ref:`parameterized generic ` for :class:`collections.abc.Callable` are now consistent with :data:`typing.Callable`. :class:`collections.abc.Callable` generic now flattens type parameters, similar to what :data:`typing.Callable` currently does. This means that ``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of ``(int, str, str)``; previously this was ``([int, str], str)``. To allow this change, :class:`types.GenericAlias` can now be subclassed, and a subclass will be returned when subscripting the :class:`collections.abc.Callable` type. Note that a :exc:`TypeError` may be raised for invalid forms of parameterizing :class:`collections.abc.Callable` which may have passed silently in Python 3.9. (Contributed by Ken Jin in :issue:`42195`.) contextlib ---------- Add a :func:`contextlib.aclosing` context manager to safely close async generators and objects representing asynchronously released resources. (Contributed by Joongi Kim and John Belmonte in :issue:`41229`.) Add asynchronous context manager support to :func:`contextlib.nullcontext`. (Contributed by Tom Gringauz in :issue:`41543`.) Add :class:`~contextlib.AsyncContextDecorator`, for supporting usage of async context managers as decorators. curses ------ The extended color functions added in ncurses 6.1 will be used transparently by :func:`curses.color_content`, :func:`curses.init_color`, :func:`curses.init_pair`, and :func:`curses.pair_content`. A new function, :func:`curses.has_extended_color_support`, indicates whether extended color support is provided by the underlying ncurses library. (Contributed by Jeffrey Kintscher and Hans Petter Jansson in :issue:`36982`.) The ``BUTTON5_*`` constants are now exposed in the :mod:`curses` module if they are provided by the underlying curses library. (Contributed by Zackery Spytz in :issue:`39273`.) dataclasses ----------- __slots__ ~~~~~~~~~ Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator. (Contributed by Yurii Karabas in :issue:`42269`) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:31338:34900"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-10,dp-Python-whatsnew-3.10.rst,"Keyword-only fields ~~~~~~~~~~~~~~~~~~~ dataclasses now supports fields that are keyword-only in the generated __init__ method. There are a number of ways of specifying keyword-only fields. You can say that every field is keyword-only: .. code-block:: python from dataclasses import dataclass @dataclass(kw_only=True) class Birthday: name: str birthday: datetime.date Both ``name`` and ``birthday`` are keyword-only parameters to the generated __init__ method. You can specify keyword-only on a per-field basis: .. code-block:: python from dataclasses import dataclass, field @dataclass class Birthday: name: str birthday: datetime.date = field(kw_only=True) Here only ``birthday`` is keyword-only. If you set ``kw_only`` on individual fields, be aware that there are rules about re-ordering fields due to keyword-only fields needing to follow non-keyword-only fields. See the full dataclasses documentation for details. You can also specify that all fields following a KW_ONLY marker are keyword-only. This will probably be the most common usage: .. code-block:: python from dataclasses import dataclass, KW_ONLY @dataclass class Point: x: float y: float _: KW_ONLY z: float = 0.0 t: float = 0.0 Here, ``z`` and ``t`` are keyword-only parameters, while ``x`` and ``y`` are not. (Contributed by Eric V. Smith in :issue:`43532`.) .. _distutils-deprecated: distutils --------- The entire ``distutils`` package is deprecated, to be removed in Python 3.12. Its functionality for specifying package builds has already been completely replaced by third-party packages ``setuptools`` and ``packaging``, and most other commonly used APIs are available elsewhere in the standard library (such as :mod:`platform`, :mod:`shutil`, :mod:`subprocess` or :mod:`sysconfig`). There are no plans to migrate any other functionality from ``distutils``, and applications that are using other functions should plan to make private copies of the code. Refer to :pep:`632` for discussion. The ``bdist_wininst`` command deprecated in Python 3.8 has been removed. The ``bdist_wheel`` command is now recommended to distribute binary packages on Windows. (Contributed by Victor Stinner in :issue:`42802`.) doctest ------- When a module does not define ``__loader__``, fall back to ``__spec__.loader``. (Contributed by Brett Cannon in :issue:`42133`.) encodings --------- :func:`encodings.normalize_encoding` now ignores non-ASCII characters. (Contributed by Hai Shi in :issue:`39337`.) enum ---- :class:`~enum.Enum` :func:`~object.__repr__` now returns ``enum_name.member_name`` and :func:`~object.__str__` now returns ``member_name``. Stdlib enums available as module constants have a :func:`repr` of ``module_name.member_name``. (Contributed by Ethan Furman in :issue:`40066`.) Add :class:`enum.StrEnum` for enums where all members are strings. (Contributed by Ethan Furman in :issue:`41816`.) fileinput --------- Add *encoding* and *errors* parameters in :func:`fileinput.input` and :class:`fileinput.FileInput`. (Contributed by Inada Naoki in :issue:`43712`.) :func:`fileinput.hook_compressed` now returns :class:`~io.TextIOWrapper` object when *mode* is ""r"" and file is compressed, like uncompressed files. (Contributed by Inada Naoki in :issue:`5758`.) faulthandler ------------ The :mod:`faulthandler` module now detects if a fatal error occurs during a garbage collector collection. (Contributed by Victor Stinner in :issue:`44466`.) gc -- Add audit hooks for :func:`gc.get_objects`, :func:`gc.get_referrers` and :func:`gc.get_referents`. (Contributed by Pablo Galindo in :issue:`43439`.) glob ---- Add the *root_dir* and *dir_fd* parameters in :func:`~glob.glob` and :func:`~glob.iglob` which allow to specify the root directory for searching. (Contributed by Serhiy Storchaka in :issue:`38144`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:34900:38828"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-11,dp-Python-whatsnew-3.10.rst,"hashlib ------- The hashlib module requires OpenSSL 1.1.1 or newer. (Contributed by Christian Heimes in :pep:`644` and :issue:`43669`.) The hashlib module has preliminary support for OpenSSL 3.0.0. (Contributed by Christian Heimes in :issue:`38820` and other issues.) The pure-Python fallback of :func:`~hashlib.pbkdf2_hmac` is deprecated. In the future PBKDF2-HMAC will only be available when Python has been built with OpenSSL support. (Contributed by Christian Heimes in :issue:`43880`.) hmac ---- The hmac module now uses OpenSSL's HMAC implementation internally. (Contributed by Christian Heimes in :issue:`40645`.) IDLE and idlelib ---------------- Make IDLE invoke :func:`sys.excepthook` (when started without '-n'). User hooks were previously ignored. (Contributed by Ken Hilton in :issue:`43008`.) Rearrange the settings dialog. Split the General tab into Windows and Shell/Ed tabs. Move help sources, which extend the Help menu, to the Extensions tab. Make space for new options and shorten the dialog. The latter makes the dialog better fit small screens. (Contributed by Terry Jan Reedy in :issue:`40468`.) Move the indent space setting from the Font tab to the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in :issue:`33962`.) The changes above were backported to a 3.9 maintenance release. Add a Shell sidebar. Move the primary prompt ('>>>') to the sidebar. Add secondary prompts ('...') to the sidebar. Left click and optional drag selects one or more lines of text, as with the editor line number sidebar. Right click after selecting text lines displays a context menu with 'copy with prompts'. This zips together prompts from the sidebar with lines from the selected text. This option also appears on the context menu for the text. (Contributed by Tal Einat in :issue:`37903`.) Use spaces instead of tabs to indent interactive code. This makes interactive code entries 'look right'. Making this feasible was a major motivation for adding the shell sidebar. (Contributed by Terry Jan Reedy in :issue:`37892`.) Highlight the new :ref:`soft keywords ` :keyword:`match`, :keyword:`case `, and :keyword:`_ ` in pattern-matching statements. However, this highlighting is not perfect and will be incorrect in some rare cases, including some ``_``-s in ``case`` patterns. (Contributed by Tal Einat in :issue:`44010`.) New in 3.10 maintenance releases. Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex Waygood and Terry Jan Reedy in :issue:`45447`.) Include prompts when saving Shell with inputs and outputs. (Contributed by Terry Jan Reedy in :gh:`95191`.) importlib.metadata ------------------ Feature parity with ``importlib_metadata`` 4.6 (`history `_). :ref:`importlib.metadata entry points ` now provide a nicer experience for selecting entry points by group and name through a new :ref:`importlib.metadata.EntryPoints ` class. See the Compatibility Note in the docs for more info on the deprecation and usage. Added :ref:`importlib.metadata.packages_distributions() ` for resolving top-level Python modules and packages to their :ref:`importlib.metadata.Distribution `. ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:38828:42161"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-12,dp-Python-whatsnew-3.10.rst,"inspect ------- When a module does not define ``__loader__``, fall back to ``__spec__.loader``. (Contributed by Brett Cannon in :issue:`42133`.) Add :func:`inspect.get_annotations`, which safely computes the annotations defined on an object. It works around the quirks of accessing the annotations on various types of objects, and makes very few assumptions about the object it examines. :func:`inspect.get_annotations` can also correctly un-stringize stringized annotations. :func:`inspect.get_annotations` is now considered best practice for accessing the annotations dict defined on any Python object; for more information on best practices for working with annotations, please see :ref:`annotations-howto`. Relatedly, :func:`inspect.signature`, :func:`inspect.Signature.from_callable`, and :func:`!inspect.Signature.from_function` now call :func:`inspect.get_annotations` to retrieve annotations. This means :func:`inspect.signature` and :func:`inspect.Signature.from_callable` can also now un-stringize stringized annotations. (Contributed by Larry Hastings in :issue:`43817`.) itertools --------- Add :func:`itertools.pairwise`. (Contributed by Raymond Hettinger in :issue:`38200`.) linecache --------- When a module does not define ``__loader__``, fall back to ``__spec__.loader``. (Contributed by Brett Cannon in :issue:`42133`.) os -- Add :func:`os.cpu_count` support for VxWorks RTOS. (Contributed by Peixing Xin in :issue:`41440`.) Add a new function :func:`os.eventfd` and related helpers to wrap the ``eventfd2`` syscall on Linux. (Contributed by Christian Heimes in :issue:`41001`.) Add :func:`os.splice` that allows to move data between two file descriptors without copying between kernel address space and user address space, where one of the file descriptors must refer to a pipe. (Contributed by Pablo Galindo in :issue:`41625`.) Add :const:`~os.O_EVTONLY`, :const:`~os.O_FSYNC`, :const:`~os.O_SYMLINK` and :const:`~os.O_NOFOLLOW_ANY` for macOS. (Contributed by Donghee Na in :issue:`43106`.) os.path ------- :func:`os.path.realpath` now accepts a *strict* keyword-only argument. When set to ``True``, :exc:`OSError` is raised if a path doesn't exist or a symlink loop is encountered. (Contributed by Barney Gale in :issue:`43757`.) pathlib ------- Add slice support to :attr:`PurePath.parents `. (Contributed by Joshua Cannon in :issue:`35498`.) Add negative indexing support to :attr:`PurePath.parents `. (Contributed by Yaroslav Pankovych in :issue:`21041`.) Add :meth:`Path.hardlink_to ` method that supersedes :meth:`!link_to`. The new method has the same argument order as :meth:`~pathlib.Path.symlink_to`. (Contributed by Barney Gale in :issue:`39950`.) :meth:`pathlib.Path.stat` and :meth:`~pathlib.Path.chmod` now accept a *follow_symlinks* keyword-only argument for consistency with corresponding functions in the :mod:`os` module. (Contributed by Barney Gale in :issue:`39906`.) platform -------- Add :func:`platform.freedesktop_os_release` to retrieve operation system identification from `freedesktop.org os-release `_ standard file. (Contributed by Christian Heimes in :issue:`28468`.) pprint ------ :func:`pprint.pprint` now accepts a new ``underscore_numbers`` keyword argument. (Contributed by sblondon in :issue:`42914`.) :mod:`pprint` can now pretty-print :class:`dataclasses.dataclass` instances. (Contributed by Lewis Gaul in :issue:`43080`.) py_compile ---------- Add ``--quiet`` option to command-line interface of :mod:`py_compile`. (Contributed by Gregory Schevchenko in :issue:`38731`.) pyclbr ------ Add an ``end_lineno`` attribute to the ``Function`` and ``Class`` objects in the tree returned by :func:`pyclbr.readmodule` and :func:`pyclbr.readmodule_ex`. It matches the existing (start) ``lineno``. (Contributed by Aviral Srivastava in :issue:`38307`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:42161:46136"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-13,dp-Python-whatsnew-3.10.rst,"shelve ------ The :mod:`shelve` module now uses :const:`pickle.DEFAULT_PROTOCOL` by default instead of :mod:`pickle` protocol ``3`` when creating shelves. (Contributed by Zackery Spytz in :issue:`34204`.) statistics ---------- Add :func:`~statistics.covariance`, Pearson's :func:`~statistics.correlation`, and simple :func:`~statistics.linear_regression` functions. (Contributed by Tymoteusz Wołodźko in :issue:`38490`.) site ---- When a module does not define ``__loader__``, fall back to ``__spec__.loader``. (Contributed by Brett Cannon in :issue:`42133`.) socket ------ The exception :exc:`socket.timeout` is now an alias of :exc:`TimeoutError`. (Contributed by Christian Heimes in :issue:`42413`.) Add option to create MPTCP sockets with ``IPPROTO_MPTCP`` (Contributed by Rui Cunha in :issue:`43571`.) Add ``IP_RECVTOS`` option to receive the type of service (ToS) or DSCP/ECN fields (Contributed by Georg Sauthoff in :issue:`44077`.) ssl --- The ssl module requires OpenSSL 1.1.1 or newer. (Contributed by Christian Heimes in :pep:`644` and :issue:`43669`.) The ssl module has preliminary support for OpenSSL 3.0.0 and new option :const:`~ssl.OP_IGNORE_UNEXPECTED_EOF`. (Contributed by Christian Heimes in :issue:`38820`, :issue:`43794`, :issue:`43788`, :issue:`43791`, :issue:`43799`, :issue:`43920`, :issue:`43789`, and :issue:`43811`.) Deprecated function and use of deprecated constants now result in a :exc:`DeprecationWarning`. :attr:`ssl.SSLContext.options` has :data:`~ssl.OP_NO_SSLv2` and :data:`~ssl.OP_NO_SSLv3` set by default and therefore cannot warn about setting the flag again. The :ref:`deprecation section ` has a list of deprecated features. (Contributed by Christian Heimes in :issue:`43880`.) The ssl module now has more secure default settings. Ciphers without forward secrecy or SHA-1 MAC are disabled by default. Security level 2 prohibits weak RSA, DH, and ECC keys with less than 112 bits of security. :class:`~ssl.SSLContext` defaults to minimum protocol version TLS 1.2. Settings are based on Hynek Schlawack's research. (Contributed by Christian Heimes in :issue:`43998`.) The deprecated protocols SSL 3.0, TLS 1.0, and TLS 1.1 are no longer officially supported. Python does not block them actively. However OpenSSL build options, distro configurations, vendor patches, and cipher suites may prevent a successful handshake. Add a *timeout* parameter to the :func:`ssl.get_server_certificate` function. (Contributed by Zackery Spytz in :issue:`31870`.) The ssl module uses heap-types and multi-phase initialization. (Contributed by Christian Heimes in :issue:`42333`.) A new verify flag :const:`~ssl.VERIFY_X509_PARTIAL_CHAIN` has been added. (Contributed by l0x in :issue:`40849`.) sqlite3 ------- Add audit events for :func:`~sqlite3.connect/handle`, :meth:`~sqlite3.Connection.enable_load_extension`, and :meth:`~sqlite3.Connection.load_extension`. (Contributed by Erlend E. Aasland in :issue:`43762`.) sys --- Add :data:`sys.orig_argv` attribute: the list of the original command line arguments passed to the Python executable. (Contributed by Victor Stinner in :issue:`23427`.) Add :data:`sys.stdlib_module_names`, containing the list of the standard library module names. (Contributed by Victor Stinner in :issue:`42955`.) _thread ------- :func:`_thread.interrupt_main` now takes an optional signal number to simulate (the default is still :const:`signal.SIGINT`). (Contributed by Antoine Pitrou in :issue:`43356`.) threading --------- Add :func:`threading.gettrace` and :func:`threading.getprofile` to retrieve the functions set by :func:`threading.settrace` and :func:`threading.setprofile` respectively. (Contributed by Mario Corchero in :issue:`42251`.) Add :data:`threading.__excepthook__` to allow retrieving the original value of :func:`threading.excepthook` in case it is set to a broken or a different value. (Contributed by Mario Corchero in :issue:`42308`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:46136:50099"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-14,dp-Python-whatsnew-3.10.rst,"traceback --------- The :func:`~traceback.format_exception`, :func:`~traceback.format_exception_only`, and :func:`~traceback.print_exception` functions can now take an exception object as a positional-only argument. (Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.) types ----- Reintroduce the :data:`types.EllipsisType`, :data:`types.NoneType` and :data:`types.NotImplementedType` classes, providing a new set of types readily interpretable by type checkers. (Contributed by Bas van Beek in :issue:`41810`.) typing ------ For major changes, see :ref:`new-feat-related-type-hints`. The behavior of :class:`typing.Literal` was changed to conform with :pep:`586` and to match the behavior of static type checkers specified in the PEP. 1. ``Literal`` now de-duplicates parameters. 2. Equality comparisons between ``Literal`` objects are now order independent. 3. ``Literal`` comparisons now respect types. For example, ``Literal[0] == Literal[False]`` previously evaluated to ``True``. It is now ``False``. To support this change, the internally used type cache now supports differentiating types. 4. ``Literal`` objects will now raise a :exc:`TypeError` exception during equality comparisons if any of their parameters are not :term:`hashable`. Note that declaring ``Literal`` with unhashable parameters will not throw an error:: >>> from typing import Literal >>> Literal[{0}] >>> Literal[{0}] == Literal[{False}] Traceback (most recent call last): File """", line 1, in TypeError: unhashable type: 'set' (Contributed by Yurii Karabas in :issue:`42345`.) Add new function :func:`typing.is_typeddict` to introspect if an annotation is a :class:`typing.TypedDict`. (Contributed by Patrick Reader in :issue:`41792`.) Subclasses of ``typing.Protocol`` which only have data variables declared will now raise a ``TypeError`` when checked with ``isinstance`` unless they are decorated with :func:`~typing.runtime_checkable`. Previously, these checks passed silently. Users should decorate their subclasses with the :func:`!runtime_checkable` decorator if they want runtime protocols. (Contributed by Yurii Karabas in :issue:`38908`.) Importing from the ``typing.io`` and ``typing.re`` submodules will now emit :exc:`DeprecationWarning`. These submodules have been deprecated since Python 3.8 and will be removed in a future version of Python. Anything belonging to those submodules should be imported directly from :mod:`typing` instead. (Contributed by Sebastian Rittau in :issue:`38291`.) unittest -------- Add new method :meth:`~unittest.TestCase.assertNoLogs` to complement the existing :meth:`~unittest.TestCase.assertLogs`. (Contributed by Kit Yan Choi in :issue:`39385`.) urllib.parse ------------ Python versions earlier than Python 3.10 allowed using both ``;`` and ``&`` as query parameter separators in :func:`urllib.parse.parse_qs` and :func:`urllib.parse.parse_qsl`. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with ``&`` as the default. This change also affects :func:`!cgi.parse` and :func:`!cgi.parse_multipart` as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in :issue:`42967`.) The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates :rfc:`3986`, ASCII newline ``\n``, ``\r`` and tab ``\t`` characters are stripped from the URL by the parser in :mod:`urllib.parse` preventing such attacks. The removal characters are controlled by a new module level variable ``urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE``. (See :gh:`88048`) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:50099:53951"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-15,dp-Python-whatsnew-3.10.rst,"xml --- Add a :class:`~xml.sax.handler.LexicalHandler` class to the :mod:`xml.sax.handler` module. (Contributed by Jonathan Gossage and Zackery Spytz in :issue:`35018`.) zipimport --------- Add methods related to :pep:`451`: :meth:`~zipimport.zipimporter.find_spec`, :meth:`zipimport.zipimporter.create_module`, and :meth:`zipimport.zipimporter.exec_module`. (Contributed by Brett Cannon in :issue:`42131`.) Add :meth:`~zipimport.zipimporter.invalidate_caches` method. (Contributed by Desmond Cheong in :issue:`14678`.) Optimizations ============= * Constructors :func:`str`, :func:`bytes` and :func:`bytearray` are now faster (around 30--40% for small objects). (Contributed by Serhiy Storchaka in :issue:`41334`.) * The :mod:`runpy` module now imports fewer modules. The ``python3 -m module-name`` command startup time is 1.4x faster in average. On Linux, ``python3 -I -m module-name`` imports 69 modules on Python 3.9, whereas it only imports 51 modules (-18) on Python 3.10. (Contributed by Victor Stinner in :issue:`41006` and :issue:`41718`.) * The ``LOAD_ATTR`` instruction now uses new ""per opcode cache"" mechanism. It is about 36% faster now for regular attributes and 44% faster for slots. (Contributed by Pablo Galindo and Yury Selivanov in :issue:`42093` and Guido van Rossum in :issue:`42927`, based on ideas implemented originally in PyPy and MicroPython.) * When building Python with :option:`--enable-optimizations` now ``-fno-semantic-interposition`` is added to both the compile and link line. This speeds builds of the Python interpreter created with :option:`--enable-shared` with ``gcc`` by up to 30%. See `this article `_ for more details. (Contributed by Victor Stinner and Pablo Galindo in :issue:`38980`.) * Use a new output buffer management code for :mod:`bz2` / :mod:`lzma` / :mod:`zlib` modules, and add ``.readall()`` function to ``_compression.DecompressReader`` class. bz2 decompression is now 1.09x ~ 1.17x faster, lzma decompression 1.20x ~ 1.32x faster, ``GzipFile.read(-1)`` 1.11x ~ 1.18x faster. (Contributed by Ma Lin, reviewed by Gregory P. Smith, in :issue:`41486`) * When using stringized annotations, annotations dicts for functions are no longer created when the function is created. Instead, they are stored as a tuple of strings, and the function object lazily converts this into the annotations dict on demand. This optimization cuts the CPU time needed to define an annotated function by half. (Contributed by Yurii Karabas and Inada Naoki in :issue:`42202`.) * Substring search functions such as ``str1 in str2`` and ``str2.find(str1)`` now sometimes use Crochemore & Perrin's ""Two-Way"" string searching algorithm to avoid quadratic behavior on long strings. (Contributed by Dennis Sweeney in :issue:`41972`) * Add micro-optimizations to ``_PyType_Lookup()`` to improve type attribute cache lookup performance in the common case of cache hits. This makes the interpreter 1.04 times faster on average. (Contributed by Dino Viehland in :issue:`43452`.) * The following built-in functions now support the faster :pep:`590` vectorcall calling convention: :func:`map`, :func:`filter`, :func:`reversed`, :func:`bool` and :func:`float`. (Contributed by Donghee Na and Jeroen Demeyer in :issue:`43575`, :issue:`43287`, :issue:`41922`, :issue:`41873` and :issue:`41870`.) * :class:`~bz2.BZ2File` performance is improved by removing internal ``RLock``. This makes :class:`!BZ2File` thread unsafe in the face of multiple simultaneous readers or writers, just like its equivalent classes in :mod:`gzip` and :mod:`lzma` have always been. (Contributed by Inada Naoki in :issue:`43785`.) .. _whatsnew310-deprecated: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:53951:57805"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-16,dp-Python-whatsnew-3.10.rst,"Deprecated ========== * Currently Python accepts numeric literals immediately followed by keywords, for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and ambiguous expressions like ``[0x1for x in y]`` (which can be interpreted as ``[0x1 for x in y]`` or ``[0x1f or x in y]``). Starting in this release, a deprecation warning is raised if the numeric literal is immediately followed by one of keywords :keyword:`and`, :keyword:`else`, :keyword:`for`, :keyword:`if`, :keyword:`in`, :keyword:`is` and :keyword:`or`. In future releases it will be changed to syntax warning, and finally to syntax error. (Contributed by Serhiy Storchaka in :issue:`43833`.) * Starting in this release, there will be a concerted effort to begin cleaning up old import semantics that were kept for Python 2.7 compatibility. Specifically, :meth:`!find_loader`/:meth:`!find_module` (superseded by :meth:`~importlib.abc.MetaPathFinder.find_spec`), :meth:`~importlib.abc.Loader.load_module` (superseded by :meth:`~importlib.abc.Loader.exec_module`), :meth:`!module_repr` (which the import system takes care of for you), the ``__package__`` attribute (superseded by ``__spec__.parent``), the ``__loader__`` attribute (superseded by ``__spec__.loader``), and the ``__cached__`` attribute (superseded by ``__spec__.cached``) will slowly be removed (as well as other classes and methods in :mod:`importlib`). :exc:`ImportWarning` and/or :exc:`DeprecationWarning` will be raised as appropriate to help identify code which needs updating during this transition. * The entire ``distutils`` namespace is deprecated, to be removed in Python 3.12. Refer to the :ref:`module changes ` section for more information. * Non-integer arguments to :func:`random.randrange` are deprecated. The :exc:`ValueError` is deprecated in favor of a :exc:`TypeError`. (Contributed by Serhiy Storchaka and Raymond Hettinger in :issue:`37319`.) * The various ``load_module()`` methods of :mod:`importlib` have been documented as deprecated since Python 3.6, but will now also trigger a :exc:`DeprecationWarning`. Use :meth:`~importlib.abc.Loader.exec_module` instead. (Contributed by Brett Cannon in :issue:`26131`.) * :meth:`!zimport.zipimporter.load_module` has been deprecated in preference for :meth:`~zipimport.zipimporter.exec_module`. (Contributed by Brett Cannon in :issue:`26131`.) * The use of :meth:`~importlib.abc.Loader.load_module` by the import system now triggers an :exc:`ImportWarning` as :meth:`~importlib.abc.Loader.exec_module` is preferred. (Contributed by Brett Cannon in :issue:`26131`.) * The use of :meth:`!importlib.abc.MetaPathFinder.find_module` and :meth:`!importlib.abc.PathEntryFinder.find_module` by the import system now trigger an :exc:`ImportWarning` as :meth:`importlib.abc.MetaPathFinder.find_spec` and :meth:`importlib.abc.PathEntryFinder.find_spec` are preferred, respectively. You can use :func:`importlib.util.spec_from_loader` to help in porting. (Contributed by Brett Cannon in :issue:`42134`.) * The use of :meth:`!importlib.abc.PathEntryFinder.find_loader` by the import system now triggers an :exc:`ImportWarning` as :meth:`importlib.abc.PathEntryFinder.find_spec` is preferred. You can use :func:`importlib.util.spec_from_loader` to help in porting. (Contributed by Brett Cannon in :issue:`43672`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:57805:61245"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-17,dp-Python-whatsnew-3.10.rst," system now triggers an :exc:`ImportWarning` as :meth:`importlib.abc.PathEntryFinder.find_spec` is preferred. You can use :func:`importlib.util.spec_from_loader` to help in porting. (Contributed by Brett Cannon in :issue:`43672`.) * The various implementations of :meth:`!importlib.abc.MetaPathFinder.find_module` ( :meth:`!importlib.machinery.BuiltinImporter.find_module`, :meth:`!importlib.machinery.FrozenImporter.find_module`, :meth:`!importlib.machinery.WindowsRegistryFinder.find_module`, :meth:`!importlib.machinery.PathFinder.find_module`, :meth:`!importlib.abc.MetaPathFinder.find_module` ), :meth:`!importlib.abc.PathEntryFinder.find_module` ( :meth:`!importlib.machinery.FileFinder.find_module` ), and :meth:`!importlib.abc.PathEntryFinder.find_loader` ( :meth:`!importlib.machinery.FileFinder.find_loader` ) now raise :exc:`DeprecationWarning` and are slated for removal in Python 3.12 (previously they were documented as deprecated in Python 3.4). (Contributed by Brett Cannon in :issue:`42135`.) * :class:`!importlib.abc.Finder` is deprecated (including its sole method, :meth:`!find_module`). Both :class:`importlib.abc.MetaPathFinder` and :class:`importlib.abc.PathEntryFinder` no longer inherit from the class. Users should inherit from one of these two classes as appropriate instead. (Contributed by Brett Cannon in :issue:`42135`.) * The deprecations of :mod:`!imp`, :func:`!importlib.find_loader`, :func:`!importlib.util.set_package_wrapper`, :func:`!importlib.util.set_loader_wrapper`, :func:`!importlib.util.module_for_loader`, :class:`!pkgutil.ImpImporter`, and :class:`!pkgutil.ImpLoader` have all been updated to list Python 3.12 as the slated version of removal (they began raising :exc:`DeprecationWarning` in previous versions of Python). (Contributed by Brett Cannon in :issue:`43720`.) * The import system now uses the ``__spec__`` attribute on modules before falling back on :meth:`!module_repr` for a module's ``__repr__()`` method. Removal of the use of ``module_repr()`` is scheduled for Python 3.12. (Contributed by Brett Cannon in :issue:`42137`.) * :meth:`!importlib.abc.Loader.module_repr`, :meth:`!importlib.machinery.FrozenLoader.module_repr`, and :meth:`!importlib.machinery.BuiltinLoader.module_repr` are deprecated and slated for removal in Python 3.12. (Contributed by Brett Cannon in :issue:`42136`.) * ``sqlite3.OptimizedUnicode`` has been undocumented and obsolete since Python 3.3, when it was made an alias to :class:`str`. It is now deprecated, scheduled for removal in Python 3.12. (Contributed by Erlend E. Aasland in :issue:`42264`.) * The undocumented built-in function ``sqlite3.enable_shared_cache`` is now deprecated, scheduled for removal in Python 3.12. Its use is strongly discouraged by the SQLite3 documentation. See `the SQLite3 docs `_ for more details. If a shared cache must be used, open the database in URI mode using the ``cache=shared`` query parameter. (Contributed by Erlend E. Aasland in :issue:`24464`.) * The following ``threading`` methods are now deprecated: * ``threading.currentThread`` => :func:`threading.current_thread` * ``threading.activeCount`` => :func:`threading.active_count` * ``threading.Condition.notifyAll`` => :meth:`threading.Condition.notify_all` * ``threading.Event.isSet`` => :meth:`threading.Event.is_set` * ``threading.Thread.setName`` => :attr:`threading.Thread.name` * ``threading.thread.getName`` => :attr:`threading.Thread.name` * ``threading.Thread.isDaemon`` => :attr:`threading.Thread.daemon` * ``threading.Thread.setDaemon`` => :attr:`threading.Thread.daemon` (Contributed by Jelle Zijlstra in :gh:`87889`.) * :meth:`!pathlib.Path.link_to` is deprecated and slated for removal in Python 3.12. Use :meth:`pathlib.Path.hardlink_to` instead. (Contributed by Barney Gale in :issue:`39950`.) * ``cgi.log()`` is deprecated and slated for removal in Python 3.12. (Contributed by Inada Naoki in :issue:`41139`.) * The following :mod:`ssl` features have been deprecated since Python 3.6, Python 3.7, or OpenSSL 1.1.0 and will be removed in 3.11: * :data:`!OP_NO_SSLv2`, :data:`!OP_NO_SSLv3`, :data:`!OP_NO_TLSv1`, :data:`!OP_NO_TLSv1_1`, :data:`!OP_NO_TLSv1_2`, and :data:`!OP_NO_TLSv1_3` are replaced by :attr:`~ssl.SSLContext.minimum_version` and :attr:`~ssl.SSLContext.maximum_version`. * :data:`!PROTOCOL_SSLv2`, :data:`!PROTOCOL_SSLv3`, :data:`!PROTOCOL_SSLv23`, :data:`!PROTOCOL_TLSv1`, :data:`!PROTOCOL_TLSv1_1`, :data:`!PROTOCOL_TLSv1_2`, and :const:`!PROTOCOL_TLS` are deprecated in favor of :const:`~ssl.PROTOCOL_TLS_CLIENT` and :const:`~ssl.PROTOCOL_TLS_SERVER` * :func:`!wrap_socket` is replaced by :meth:`ssl.SSLContext.wrap_socket` * :func:`!match_hostname` * :func:`!RAND_pseudo_bytes`, :func:`!RAND_egd` * NPN features like :meth:`ssl.SSLSocket.selected_npn_protocol` and :meth:`ssl.SSLContext.set_npn_protocols` are replaced by ALPN. * The threading debug (:envvar:`!PYTHONTHREADDEBUG` environment variable) is deprecated in Python 3.10 and will be removed in Python 3.12. This feature requires a :ref:`debug build of Python `. (Contributed by Victor Stinner in :issue:`44584`.) * Importing from the ``typing.io`` and ``typing.re`` submodules will now emit :exc:`DeprecationWarning`. These submodules will be removed in a future version of Python. Anything belonging to these submodules should be imported directly from :mod:`typing` instead. (Contributed by Sebastian Rittau in :issue:`38291`.) .. _whatsnew310-removed: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:61006:66727"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-18,dp-Python-whatsnew-3.10.rst,"Removed ======= * Removed special methods ``__int__``, ``__float__``, ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__rfloordiv__``, ``__rmod__`` and ``__rdivmod__`` of the :class:`complex` class. They always raised a :exc:`TypeError`. (Contributed by Serhiy Storchaka in :issue:`41974`.) * The ``ParserBase.error()`` method from the private and undocumented ``_markupbase`` module has been removed. :class:`html.parser.HTMLParser` is the only subclass of ``ParserBase`` and its ``error()`` implementation was already removed in Python 3.5. (Contributed by Berker Peksag in :issue:`31844`.) * Removed the ``unicodedata.ucnhash_CAPI`` attribute which was an internal PyCapsule object. The related private ``_PyUnicode_Name_CAPI`` structure was moved to the internal C API. (Contributed by Victor Stinner in :issue:`42157`.) * Removed the ``parser`` module, which was deprecated in 3.9 due to the switch to the new PEG parser, as well as all the C source and header files that were only being used by the old parser, including ``node.h``, ``parser.h``, ``graminit.h`` and ``grammar.h``. * Removed the Public C API functions ``PyParser_SimpleParseStringFlags``, ``PyParser_SimpleParseStringFlagsFilename``, ``PyParser_SimpleParseFileFlags`` and ``PyNode_Compile`` that were deprecated in 3.9 due to the switch to the new PEG parser. * Removed the ``formatter`` module, which was deprecated in Python 3.4. It is somewhat obsolete, little used, and not tested. It was originally scheduled to be removed in Python 3.6, but such removals were delayed until after Python 2.7 EOL. Existing users should copy whatever classes they use into their code. (Contributed by Donghee Na and Terry J. Reedy in :issue:`42299`.) * Removed the :c:func:`!PyModule_GetWarningsModule` function that was useless now due to the :mod:`!_warnings` module was converted to a builtin module in 2.6. (Contributed by Hai Shi in :issue:`42599`.) * Remove deprecated aliases to :ref:`collections-abstract-base-classes` from the :mod:`collections` module. (Contributed by Victor Stinner in :issue:`37324`.) * The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's :doc:`high-level API <../library/asyncio-api-index>` following deprecation in Python 3.8. The motivation behind this change is multifold: 1. This simplifies the high-level API. 2. The functions in the high-level API have been implicitly getting the current thread's running event loop since Python 3.7. There isn't a need to pass the event loop to the API in most normal use cases. 3. Event loop passing is error-prone especially when dealing with loops running in different threads. Note that the low-level API will still accept ``loop``. See :ref:`changes-python-api` for examples of how to replace existing code. (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley in :issue:`42392`.) Porting to Python 3.10 ====================== This section lists previously described changes and other bugfixes that may require changes to your code. Changes in the Python syntax ---------------------------- * Deprecation warning is now emitted when compiling previously valid syntax if the numeric literal is immediately followed by a keyword (like in ``0in x``). In future releases it will be changed to syntax warning, and finally to a syntax error. To get rid of the warning and make the code compatible with future releases just add a space between the numeric literal and the following keyword. (Contributed by Serhiy Storchaka in :issue:`43833`.) .. _changes-python-api: ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:66727:70392"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-19,dp-Python-whatsnew-3.10.rst,"Changes in the Python API ------------------------- * The *etype* parameters of the :func:`~traceback.format_exception`, :func:`~traceback.format_exception_only`, and :func:`~traceback.print_exception` functions in the :mod:`traceback` module have been renamed to *exc*. (Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.) * :mod:`atexit`: At Python exit, if a callback registered with :func:`atexit.register` fails, its exception is now logged. Previously, only some exceptions were logged, and the last exception was always silently ignored. (Contributed by Victor Stinner in :issue:`42639`.) * :class:`collections.abc.Callable` generic now flattens type parameters, similar to what :data:`typing.Callable` currently does. This means that ``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of ``(int, str, str)``; previously this was ``([int, str], str)``. Code which accesses the arguments via :func:`typing.get_args` or ``__args__`` need to account for this change. Furthermore, :exc:`TypeError` may be raised for invalid forms of parameterizing :class:`collections.abc.Callable` which may have passed silently in Python 3.9. (Contributed by Ken Jin in :issue:`42195`.) * :meth:`socket.htons` and :meth:`socket.ntohs` now raise :exc:`OverflowError` instead of :exc:`DeprecationWarning` if the given parameter will not fit in a 16-bit unsigned integer. (Contributed by Erlend E. Aasland in :issue:`42393`.) * The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's :doc:`high-level API <../library/asyncio-api-index>` following deprecation in Python 3.8. A coroutine that currently looks like this:: async def foo(loop): await asyncio.sleep(1, loop=loop) Should be replaced with this:: async def foo(): await asyncio.sleep(1) If ``foo()`` was specifically designed *not* to run in the current thread's running event loop (e.g. running in another thread's event loop), consider using :func:`asyncio.run_coroutine_threadsafe` instead. (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley in :issue:`42392`.) * The :data:`types.FunctionType` constructor now inherits the current builtins if the *globals* dictionary has no ``""__builtins__""`` key, rather than using ``{""None"": None}`` as builtins: same behavior as :func:`eval` and :func:`exec` functions. Defining a function with ``def function(...): ...`` in Python is not affected, globals cannot be overridden with this syntax: it also inherits the current builtins. (Contributed by Victor Stinner in :issue:`42990`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:70392:73058"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-20,dp-Python-whatsnew-3.10.rst,"Changes in the C API -------------------- * The C API functions ``PyParser_SimpleParseStringFlags``, ``PyParser_SimpleParseStringFlagsFilename``, ``PyParser_SimpleParseFileFlags``, ``PyNode_Compile`` and the type used by these functions, ``struct _node``, were removed due to the switch to the new PEG parser. Source should be now be compiled directly to a code object using, for example, :c:func:`Py_CompileString`. The resulting code object can then be evaluated using, for example, :c:func:`PyEval_EvalCode`. Specifically: * A call to ``PyParser_SimpleParseStringFlags`` followed by ``PyNode_Compile`` can be replaced by calling :c:func:`Py_CompileString`. * There is no direct replacement for ``PyParser_SimpleParseFileFlags``. To compile code from a ``FILE *`` argument, you will need to read the file in C and pass the resulting buffer to :c:func:`Py_CompileString`. * To compile a file given a ``char *`` filename, explicitly open the file, read it and compile the result. One way to do this is using the :py:mod:`io` module with :c:func:`PyImport_ImportModule`, :c:func:`PyObject_CallMethod`, :c:func:`PyBytes_AsString` and :c:func:`Py_CompileString`, as sketched below. (Declarations and error handling are omitted.) :: io_module = Import_ImportModule(""io""); fileobject = PyObject_CallMethod(io_module, ""open"", ""ss"", filename, ""rb""); source_bytes_object = PyObject_CallMethod(fileobject, ""read"", """"); result = PyObject_CallMethod(fileobject, ""close"", """"); source_buf = PyBytes_AsString(source_bytes_object); code = Py_CompileString(source_buf, filename, Py_file_input); * For ``FrameObject`` objects, the :attr:`~frame.f_lasti` member now represents a wordcode offset instead of a simple offset into the bytecode string. This means that this number needs to be multiplied by 2 to be used with APIs that expect a byte offset instead (like :c:func:`PyCode_Addr2Line` for example). Notice as well that the :attr:`!f_lasti` member of ``FrameObject`` objects is not considered stable: please use :c:func:`PyFrame_GetLineNumber` instead. CPython bytecode changes ======================== * The ``MAKE_FUNCTION`` instruction now accepts either a dict or a tuple of strings as the function's annotations. (Contributed by Yurii Karabas and Inada Naoki in :issue:`42202`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:73058:75459"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-21,dp-Python-whatsnew-3.10.rst,"Build Changes ============= * :pep:`644`: Python now requires OpenSSL 1.1.1 or newer. OpenSSL 1.0.2 is no longer supported. (Contributed by Christian Heimes in :issue:`43669`.) * The C99 functions :c:func:`snprintf` and :c:func:`vsnprintf` are now required to build Python. (Contributed by Victor Stinner in :issue:`36020`.) * :mod:`sqlite3` requires SQLite 3.7.15 or higher. (Contributed by Sergey Fedoseev and Erlend E. Aasland in :issue:`40744` and :issue:`40810`.) * The :mod:`atexit` module must now always be built as a built-in module. (Contributed by Victor Stinner in :issue:`42639`.) * Add :option:`--disable-test-modules` option to the ``configure`` script: don't build nor install test modules. (Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in :issue:`27640`.) * Add :option:`--with-wheel-pkg-dir=PATH option <--with-wheel-pkg-dir>` to the ``./configure`` script. If specified, the :mod:`ensurepip` module looks for ``setuptools`` and ``pip`` wheel packages in this directory: if both are present, these wheel packages are used instead of ensurepip bundled wheel packages. Some Linux distribution packaging policies recommend against bundling dependencies. For example, Fedora installs wheel packages in the ``/usr/share/python-wheels/`` directory and don't install the ``ensurepip._bundled`` package. (Contributed by Victor Stinner in :issue:`42856`.) * Add a new :option:`configure --without-static-libpython option <--without-static-libpython>` to not build the ``libpythonMAJOR.MINOR.a`` static library and not install the ``python.o`` object file. (Contributed by Victor Stinner in :issue:`43103`.) * The ``configure`` script now uses the ``pkg-config`` utility, if available, to detect the location of Tcl/Tk headers and libraries. As before, those locations can be explicitly specified with the ``--with-tcltk-includes`` and ``--with-tcltk-libs`` configuration options. (Contributed by Manolis Stamatogiannakis in :issue:`42603`.) * Add :option:`--with-openssl-rpath` option to ``configure`` script. The option simplifies building Python with a custom OpenSSL installation, e.g. ``./configure --with-openssl=/path/to/openssl --with-openssl-rpath=auto``. (Contributed by Christian Heimes in :issue:`43466`.) C API Changes ============= PEP 652: Maintaining the Stable ABI ----------------------------------- The Stable ABI (Application Binary Interface) for extension modules or embedding Python is now explicitly defined. :ref:`stable` describes C API and ABI stability guarantees along with best practices for using the Stable ABI. (Contributed by Petr Viktorin in :pep:`652` and :issue:`43795`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:75459:78168"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-22,dp-Python-whatsnew-3.10.rst,"New Features ------------ * The result of :c:func:`PyNumber_Index` now always has exact type :class:`int`. Previously, the result could have been an instance of a subclass of ``int``. (Contributed by Serhiy Storchaka in :issue:`40792`.) * Add a new :c:member:`~PyConfig.orig_argv` member to the :c:type:`PyConfig` structure: the list of the original command line arguments passed to the Python executable. (Contributed by Victor Stinner in :issue:`23427`.) * The :c:func:`PyDateTime_DATE_GET_TZINFO` and :c:func:`PyDateTime_TIME_GET_TZINFO` macros have been added for accessing the ``tzinfo`` attributes of :class:`datetime.datetime` and :class:`datetime.time` objects. (Contributed by Zackery Spytz in :issue:`30155`.) * Add a :c:func:`PyCodec_Unregister` function to unregister a codec search function. (Contributed by Hai Shi in :issue:`41842`.) * The :c:func:`PyIter_Send` function was added to allow sending value into iterator without raising ``StopIteration`` exception. (Contributed by Vladimir Matveev in :issue:`41756`.) * Add :c:func:`PyUnicode_AsUTF8AndSize` to the limited C API. (Contributed by Alex Gaynor in :issue:`41784`.) * Add :c:func:`PyModule_AddObjectRef` function: similar to :c:func:`PyModule_AddObject` but don't steal a reference to the value on success. (Contributed by Victor Stinner in :issue:`1635741`.) * Add :c:func:`Py_NewRef` and :c:func:`Py_XNewRef` functions to increment the reference count of an object and return the object. (Contributed by Victor Stinner in :issue:`42262`.) * The :c:func:`PyType_FromSpecWithBases` and :c:func:`PyType_FromModuleAndSpec` functions now accept a single class as the *bases* argument. (Contributed by Serhiy Storchaka in :issue:`42423`.) * The :c:func:`PyType_FromModuleAndSpec` function now accepts NULL ``tp_doc`` slot. (Contributed by Hai Shi in :issue:`41832`.) * The :c:func:`PyType_GetSlot` function can accept :ref:`static types `. (Contributed by Hai Shi and Petr Viktorin in :issue:`41073`.) * Add a new :c:func:`PySet_CheckExact` function to the C-API to check if an object is an instance of :class:`set` but not an instance of a subtype. (Contributed by Pablo Galindo in :issue:`43277`.) * Add :c:func:`PyErr_SetInterruptEx` which allows passing a signal number to simulate. (Contributed by Antoine Pitrou in :issue:`43356`.) * The limited C API is now supported if :ref:`Python is built in debug mode ` (if the ``Py_DEBUG`` macro is defined). In the limited C API, the :c:func:`Py_INCREF` and :c:func:`Py_DECREF` functions are now implemented as opaque function calls, rather than accessing directly the :c:member:`PyObject.ob_refcnt` member, if Python is built in debug mode and the ``Py_LIMITED_API`` macro targets Python 3.10 or newer. It became possible to support the limited C API in debug mode because the :c:type:`PyObject` structure is the same in release and debug mode since Python 3.8 (see :issue:`36465`). The limited C API is still not supported in the :option:`--with-trace-refs` special build (``Py_TRACE_REFS`` macro). (Contributed by Victor Stinner in :issue:`43688`.) * Add the :c:func:`Py_Is(x, y) ` function to test if the *x* object is the *y* object, the same as ``x is y`` in Python. Add also the :c:func:`Py_IsNone`, :c:func:`Py_IsTrue`, :c:func:`Py_IsFalse` functions to test if an object is, respectively, the ``None`` singleton, the ``True`` singleton or the ``False`` singleton. (Contributed by Victor Stinner in :issue:`43753`.) * Add new functions to control the garbage collector from C code: :c:func:`PyGC_Enable()`, :c:func:`PyGC_Disable()`, :c:func:`PyGC_IsEnabled()`. These functions allow to activate, deactivate and query the state of the garbage collector from C code without having to import the :mod:`gc` module. * Add a new :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` type flag to disallow creating type instances. (Contributed by Victor Stinner in :issue:`43916`.) * Add a new :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag for creating immutable type objects: type attributes cannot be set nor deleted. (Contributed by Victor Stinner and Erlend E. Aasland in :issue:`43908`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:78168:82434"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-23,dp-Python-whatsnew-3.10.rst,"Porting to Python 3.10 ---------------------- * The ``PY_SSIZE_T_CLEAN`` macro must now be defined to use :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` formats which use ``#``: ``es#``, ``et#``, ``s#``, ``u#``, ``y#``, ``z#``, ``U#`` and ``Z#``. See :ref:`arg-parsing` and :pep:`353`. (Contributed by Victor Stinner in :issue:`40943`.) * Since :c:func:`Py_REFCNT()` is changed to the inline static function, ``Py_REFCNT(obj) = new_refcnt`` must be replaced with ``Py_SET_REFCNT(obj, new_refcnt)``: see :c:func:`Py_SET_REFCNT()` (available since Python 3.9). For backward compatibility, this macro can be used:: #if PY_VERSION_HEX < 0x030900A4 # define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0) #endif (Contributed by Victor Stinner in :issue:`39573`.) * Calling :c:func:`PyDict_GetItem` without :term:`GIL` held had been allowed for historical reason. It is no longer allowed. (Contributed by Victor Stinner in :issue:`40839`.) * ``PyUnicode_FromUnicode(NULL, size)`` and ``PyUnicode_FromStringAndSize(NULL, size)`` raise ``DeprecationWarning`` now. Use :c:func:`PyUnicode_New` to allocate Unicode object without initial data. (Contributed by Inada Naoki in :issue:`36346`.) * The private ``_PyUnicode_Name_CAPI`` structure of the PyCapsule API ``unicodedata.ucnhash_CAPI`` has been moved to the internal C API. (Contributed by Victor Stinner in :issue:`42157`.) * :c:func:`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome` and :c:func:`Py_GetProgramName` functions now return ``NULL`` if called before :c:func:`Py_Initialize` (before Python is initialized). Use the new :ref:`init-config` API to get the :ref:`init-path-config`. (Contributed by Victor Stinner in :issue:`42260`.) * :c:func:`PyList_SET_ITEM`, :c:func:`PyTuple_SET_ITEM` and :c:func:`PyCell_SET` macros can no longer be used as l-value or r-value. For example, ``x = PyList_SET_ITEM(a, b, c)`` and ``PyList_SET_ITEM(a, b, c) = x`` now fail with a compiler error. It prevents bugs like ``if (PyList_SET_ITEM (a, b, c) < 0) ...`` test. (Contributed by Zackery Spytz and Victor Stinner in :issue:`30459`.) * The non-limited API files ``odictobject.h``, ``parser_interface.h``, ``picklebufobject.h``, ``pyarena.h``, ``pyctype.h``, ``pydebug.h``, ``pyfpe.h``, and ``pytime.h`` have been moved to the ``Include/cpython`` directory. These files must not be included directly, as they are already included in ``Python.h``; see :ref:`api-includes`. If they have been included directly, consider including ``Python.h`` instead. (Contributed by Nicholas Sim in :issue:`35134`.) * Use the :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag to create immutable type objects. Do not rely on :c:macro:`Py_TPFLAGS_HEAPTYPE` to decide if a type object is mutable or not; check if :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` is set instead. (Contributed by Victor Stinner and Erlend E. Aasland in :issue:`43908`.) * The undocumented function ``Py_FrozenMain`` has been removed from the limited API. The function is mainly useful for custom builds of Python. (Contributed by Petr Viktorin in :issue:`26241`.) Deprecated ---------- * The ``PyUnicode_InternImmortal()`` function is now deprecated and will be removed in Python 3.12: use :c:func:`PyUnicode_InternInPlace` instead. (Contributed by Victor Stinner in :issue:`41692`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:82434:85920"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-24,dp-Python-whatsnew-3.10.rst,"Removed ------- * Removed ``Py_UNICODE_str*`` functions manipulating ``Py_UNICODE*`` strings. (Contributed by Inada Naoki in :issue:`41123`.) * ``Py_UNICODE_strlen``: use :c:func:`PyUnicode_GetLength` or :c:macro:`PyUnicode_GET_LENGTH` * ``Py_UNICODE_strcat``: use :c:func:`PyUnicode_CopyCharacters` or :c:func:`PyUnicode_FromFormat` * ``Py_UNICODE_strcpy``, ``Py_UNICODE_strncpy``: use :c:func:`PyUnicode_CopyCharacters` or :c:func:`PyUnicode_Substring` * ``Py_UNICODE_strcmp``: use :c:func:`PyUnicode_Compare` * ``Py_UNICODE_strncmp``: use :c:func:`PyUnicode_Tailmatch` * ``Py_UNICODE_strchr``, ``Py_UNICODE_strrchr``: use :c:func:`PyUnicode_FindChar` * Removed ``PyUnicode_GetMax()``. Please migrate to new (:pep:`393`) APIs. (Contributed by Inada Naoki in :issue:`41103`.) * Removed ``PyLong_FromUnicode()``. Please migrate to :c:func:`PyLong_FromUnicodeObject`. (Contributed by Inada Naoki in :issue:`41103`.) * Removed ``PyUnicode_AsUnicodeCopy()``. Please use :c:func:`PyUnicode_AsUCS4Copy` or :c:func:`PyUnicode_AsWideCharString` (Contributed by Inada Naoki in :issue:`41103`.) * Removed ``_Py_CheckRecursionLimit`` variable: it has been replaced by ``ceval.recursion_limit`` of the :c:type:`PyInterpreterState` structure. (Contributed by Victor Stinner in :issue:`41834`.) * Removed undocumented macros ``Py_ALLOW_RECURSION`` and ``Py_END_ALLOW_RECURSION`` and the ``recursion_critical`` field of the :c:type:`PyInterpreterState` structure. (Contributed by Serhiy Storchaka in :issue:`41936`.) * Removed the undocumented ``PyOS_InitInterrupts()`` function. Initializing Python already implicitly installs signal handlers: see :c:member:`PyConfig.install_signal_handlers`. (Contributed by Victor Stinner in :issue:`41713`.) * Remove the ``PyAST_Validate()`` function. It is no longer possible to build a AST object (``mod_ty`` type) with the public C API. The function was already excluded from the limited C API (:pep:`384`). (Contributed by Victor Stinner in :issue:`43244`.) * Remove the ``symtable.h`` header file and the undocumented functions: * ``PyST_GetScope()`` * ``PySymtable_Build()`` * ``PySymtable_BuildObject()`` * ``PySymtable_Free()`` * ``Py_SymtableString()`` * ``Py_SymtableStringObject()`` The ``Py_SymtableString()`` function was part the stable ABI by mistake but it could not be used, because the ``symtable.h`` header file was excluded from the limited C API. Use Python :mod:`symtable` module instead. (Contributed by Victor Stinner in :issue:`43244`.) * Remove :c:func:`PyOS_ReadlineFunctionPointer` from the limited C API headers and from ``python3.dll``, the library that provides the stable ABI on Windows. Since the function takes a ``FILE*`` argument, its ABI stability cannot be guaranteed. (Contributed by Petr Viktorin in :issue:`43868`.) * Remove ``ast.h``, ``asdl.h``, and ``Python-ast.h`` header files. These functions were undocumented and excluded from the limited C API. Most names defined by these header files were not prefixed by ``Py`` and so could create names conflicts. For example, ``Python-ast.h`` defined a ``Yield`` macro which was conflict with the ``Yield`` name used by the Windows ```` header. Use the Python :mod:`ast` module instead. (Contributed by Victor Stinner in :issue:`43244`.) * Remove the compiler and parser functions using ``struct _mod`` type, because the public AST C API was removed: * ``PyAST_Compile()`` * ``PyAST_CompileEx()`` * ``PyAST_CompileObject()`` * ``PyFuture_FromAST()`` * ``PyFuture_FromASTObject()`` * ``PyParser_ASTFromFile()`` * ``PyParser_ASTFromFileObject()`` * ``PyParser_ASTFromFilename()`` * ``PyParser_ASTFromString()`` * ``PyParser_ASTFromStringObject()`` These functions were undocumented and excluded from the limited C API. (Contributed by Victor Stinner in :issue:`43244`.) * Remove the ``pyarena.h`` header file with functions: * ``PyArena_New()`` * ``PyArena_Free()`` * ``PyArena_Malloc()`` * ``PyArena_AddPyObject()`` These functions were undocumented, excluded from the limited C API, and were only used internally by the compiler. (Contributed by Victor Stinner in :issue:`43244`.) * The ``PyThreadState.use_tracing`` member has been removed to optimize Python. (Contributed by Mark Shannon in :issue:`43760`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:85920:90321"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.13-whatsnew-3.10.rst-25,dp-Python-whatsnew-3.10.rst,"Notable security feature in 3.10.7 ================================== Converting between :class:`int` and :class:`str` in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a :exc:`ValueError` if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for :cve:`2020-10735`. This limit can be configured or disabled by environment variable, command line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion length limitation ` documentation. The default limit is 4300 digits in string form. Notable security feature in 3.10.8 ================================== The deprecated :mod:`!mailcap` module now refuses to inject unsafe text (filenames, MIME types, parameters) into shell commands. Instead of using such text, it will warn and act as if a match was not found (or for test commands, as if the test failed). (Contributed by Petr Viktorin in :gh:`98966`.) Notable changes in 3.10.12 ========================== tarfile ------- * The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`, have a new a *filter* argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. See :ref:`tarfile-extraction-filter` for details. In Python 3.12, use without the *filter* argument will show a :exc:`DeprecationWarning`. In Python 3.14, the default will switch to ``'data'``. (Contributed by Petr Viktorin in :pep:`706`.) ",en,software_docs,Python 3.13.0,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.13.0/Doc/whatsnew/3.10.rst#codepoints:90321:91938"", ""revision"": ""3.13.0+sha256:12445c7b3db3126c41190bfdc1c8239c39c719404e844babbd015a1bc3fafcd4"", ""source_id"": ""cpython-3.13:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz""}]" dp-pt-cpython-3.12-whatsnew-3.10.rst-14,dp-Python-whatsnew-3.10.rst,"traceback --------- The :func:`~traceback.format_exception`, :func:`~traceback.format_exception_only`, and :func:`~traceback.print_exception` functions can now take an exception object as a positional-only argument. (Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.) types ----- Reintroduce the :data:`types.EllipsisType`, :data:`types.NoneType` and :data:`types.NotImplementedType` classes, providing a new set of types readily interpretable by type checkers. (Contributed by Bas van Beek in :issue:`41810`.) typing ------ For major changes, see :ref:`new-feat-related-type-hints`. The behavior of :class:`typing.Literal` was changed to conform with :pep:`586` and to match the behavior of static type checkers specified in the PEP. 1. ``Literal`` now de-duplicates parameters. 2. Equality comparisons between ``Literal`` objects are now order independent. 3. ``Literal`` comparisons now respect types. For example, ``Literal[0] == Literal[False]`` previously evaluated to ``True``. It is now ``False``. To support this change, the internally used type cache now supports differentiating types. 4. ``Literal`` objects will now raise a :exc:`TypeError` exception during equality comparisons if any of their parameters are not :term:`hashable`. Note that declaring ``Literal`` with unhashable parameters will not throw an error:: >>> from typing import Literal >>> Literal[{0}] >>> Literal[{0}] == Literal[{False}] Traceback (most recent call last): File """", line 1, in TypeError: unhashable type: 'set' (Contributed by Yurii Karabas in :issue:`42345`.) Add new function :func:`typing.is_typeddict` to introspect if an annotation is a :class:`typing.TypedDict`. (Contributed by Patrick Reader in :issue:`41792`.) Subclasses of ``typing.Protocol`` which only have data variables declared will now raise a ``TypeError`` when checked with ``isinstance`` unless they are decorated with :func:`~typing.runtime_checkable`. Previously, these checks passed silently. Users should decorate their subclasses with the :func:`!runtime_checkable` decorator if they want runtime protocols. (Contributed by Yurii Karabas in :issue:`38908`.) Importing from the ``typing.io`` and ``typing.re`` submodules will now emit :exc:`DeprecationWarning`. These submodules have been deprecated since Python 3.8 and will be removed in a future version of Python. Anything belonging to those submodules should be imported directly from :mod:`typing` instead. (Contributed by Sebastian Rittau in :issue:`38291`.) unittest -------- Add new method :meth:`~unittest.TestCase.assertNoLogs` to complement the existing :meth:`~unittest.TestCase.assertLogs`. (Contributed by Kit Yan Choi in :issue:`39385`.) urllib.parse ------------ Python versions earlier than Python 3.10 allowed using both ``;`` and ``&`` as query parameter separators in :func:`urllib.parse.parse_qs` and :func:`urllib.parse.parse_qsl`. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with ``&`` as the default. This change also affects :func:`cgi.parse` and :func:`cgi.parse_multipart` as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in :issue:`42967`.) The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates :rfc:`3986`, ASCII newline ``\n``, ``\r`` and tab ``\t`` characters are stripped from the URL by the parser in :mod:`urllib.parse` preventing such attacks. The removal characters are controlled by a new module level variable ``urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE``. (See :gh:`88048`) ",en,software_docs,Python 3.12.7,"[{""license"": ""PSF-2.0"", ""locator"": ""Python-3.12.7/Doc/whatsnew/3.10.rst#codepoints:50099:53949"", ""revision"": ""3.12.7+sha256:73ac8fe780227bf371add8373c3079f42a0dc62deff8d612cd15a618082ab623"", ""source_id"": ""cpython-3.12:whatsnew/3.10.rst"", ""uri"": ""https://www.python.org/ftp/python/3.12.7/Python-3.12.7.tgz""}]" dp-pt-werkzeug-3.1-datastructures.rst-0,dp-Werkzeug-datastructures.rst,"=============== Data Structures =============== .. module:: werkzeug.datastructures Werkzeug provides some subclasses of common Python objects to extend them with additional features. Some of them are used to make them immutable, others are used to change some semantics to better work with HTTP. General Purpose =============== .. versionchanged:: 0.6 The general purpose classes are now pickleable in each protocol as long as the contained objects are pickleable. This means that the :class:`FileMultiDict` won't be pickleable as soon as it contains a file. .. autoclass:: TypeConversionDict :members: .. autoclass:: ImmutableTypeConversionDict :members: copy .. autoclass:: MultiDict :members: :inherited-members: .. class:: OrderedMultiDict Works like a regular :class:`MultiDict` but preserves the order of the fields. To convert the ordered multi dict into a list you can use the :meth:`items` method and pass it ``multi=True``. In general an :class:`OrderedMultiDict` is an order of magnitude slower than a :class:`MultiDict`. .. admonition:: note Due to a limitation in Python you cannot convert an ordered multi dict into a regular dict by using ``dict(multidict)``. Instead you have to use the :meth:`to_dict` method, otherwise the internal bucket objects are exposed. .. deprecated:: 3.1 Will be removed in Werkzeug 3.2. Use ``MultiDict`` instead. .. class:: ImmutableOrderedMultiDict An immutable :class:`OrderedMultiDict`. .. deprecated:: 3.1 Will be removed in Werkzeug 3.2. Use ``ImmutableMultiDict`` instead. .. versionadded:: 0.6 .. autoclass:: CombinedMultiDict .. autoclass:: ImmutableDict :members: copy .. autoclass:: ImmutableList .. autoclass:: FileMultiDict :members: .. _http-datastructures: HTTP Related ============ .. autoclass:: Headers([defaults]) :members: .. autoclass:: EnvironHeaders .. autoclass:: HeaderSet :members: .. autoclass:: Accept :members: .. autoclass:: MIMEAccept :members: accept_html, accept_xhtml, accept_json .. autoclass:: CharsetAccept .. autoclass:: LanguageAccept .. autoclass:: RequestCacheControl :members: :inherited-members: ImmutableDictMixin, CallbackDict :member-order: groupwise .. autoclass:: ResponseCacheControl :members: :inherited-members: CallbackDict :member-order: groupwise .. autoclass:: ETags :members: .. autoclass:: Authorization :members: .. autoclass:: WWWAuthenticate :members: .. autoclass:: IfRange :members: .. autoclass:: Range :members: .. autoclass:: ContentRange :members: Others ====== .. autoclass:: FileStorage :members: .. attribute:: stream The input stream for the uploaded file. This usually points to an open temporary file. .. attribute:: filename The filename of the file on the client. Can be a ``str``, or an instance of ``os.PathLike``. .. attribute:: name The name of the form field. .. attribute:: headers The multipart headers as :class:`Headers` object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting. .. versionadded:: 0.6 ",en,software_docs,Werkzeug 3.1.9,"[{""license"": ""BSD-3-Clause"", ""locator"": ""werkzeug-3.1.9/docs/datastructures.rst#codepoints:0:3304"", ""revision"": ""3.1.9+sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060"", ""source_id"": ""werkzeug-3.1:datastructures.rst"", ""uri"": ""https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz""}]" dp-pt-werkzeug-3.1-index.rst-0,dp-Werkzeug-index.rst,".. rst-class:: hide-header Werkzeug ======== .. image:: _static/werkzeug-name.svg :align: center :height: 200px *werkzeug* German noun: ""tool"". Etymology: *werk* (""work""), *zeug* (""stuff"") Werkzeug is a comprehensive `WSGI`_ web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries. Werkzeug doesn't enforce any dependencies. It is up to the developer to choose a template engine, database adapter, and even how to handle requests. .. _WSGI: https://wsgi.readthedocs.io/en/latest/ Getting Started --------------- .. toctree:: :maxdepth: 2 installation tutorial levels quickstart Serving and Testing ------------------- .. toctree:: :maxdepth: 2 serving test debug Reference --------- .. toctree:: :maxdepth: 2 wrappers routing wsgi http datastructures utils urls local middleware/index exceptions Deployment ---------- .. toctree:: :maxdepth: 3 deployment/index Additional Information ---------------------- .. toctree:: :maxdepth: 2 terms request_data license changes ",en,software_docs,Werkzeug 3.1.9,"[{""license"": ""BSD-3-Clause"", ""locator"": ""werkzeug-3.1.9/docs/index.rst#codepoints:0:1195"", ""revision"": ""3.1.9+sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060"", ""source_id"": ""werkzeug-3.1:index.rst"", ""uri"": ""https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz""}]" dp-pt-werkzeug-3.1-installation.rst-0,dp-Werkzeug-installation.rst,"Installation ============ Python Version -------------- We recommend using the latest version of Python. Werkzeug supports Python 3.9 and newer. Optional dependencies ~~~~~~~~~~~~~~~~~~~~~ These distributions will not be installed automatically. Werkzeug will detect and use them if you install them. * `Colorama`_ provides request log highlighting when using the development server on Windows. This works automatically on other systems. * `Watchdog`_ provides a faster, more efficient reloader for the development server. .. _Colorama: https://pypi.org/project/colorama/ .. _Watchdog: https://pypi.org/project/watchdog/ greenlet ~~~~~~~~ You may choose to use gevent or eventlet with your application. In this case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is required. These are not minimum supported versions, they only indicate the first versions that added necessary features. You should use the latest versions of each. Virtual environments -------------------- Use a virtual environment to manage the dependencies for your project, both in development and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system's packages. Python comes bundled with the :mod:`venv` module to create virtual environments. Create an environment ~~~~~~~~~~~~~~~~~~~~~ Create a project folder and a :file:`venv` folder within: .. code-block:: sh mkdir myproject cd myproject python3 -m venv venv On Windows: .. code-block:: bat py -3 -m venv venv Activate the environment ~~~~~~~~~~~~~~~~~~~~~~~~ Before you work on your project, activate the corresponding environment: .. code-block:: sh . venv/bin/activate On Windows: .. code-block:: bat venv\Scripts\activate Your shell prompt will change to show the name of the activated environment. Install Werkzeug ---------------- Within the activated environment, use the following command to install Werkzeug: .. code-block:: sh pip install Werkzeug ",en,software_docs,Werkzeug 3.1.9,"[{""license"": ""BSD-3-Clause"", ""locator"": ""werkzeug-3.1.9/docs/installation.rst#codepoints:0:2389"", ""revision"": ""3.1.9+sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060"", ""source_id"": ""werkzeug-3.1:installation.rst"", ""uri"": ""https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz""}]" dp-pt-attrs-26.1-api.rst-0,dp-attrs-api.rst,"API Reference ============= .. module:: attrs *attrs* works by decorating a class using `attrs.define` or `attr.s` and then defining attributes on the class using `attrs.field`, `attr.ib`, or type annotations. What follows is the dry API explanation for people who understand how *attrs* works. If you'd like a hands-on tutorial, have a look at `examples`. If you're confused by the many names, please check out `names` for clarification, but the `TL;DR `_ is that as of version 21.3.0, *attrs* consists of **two** top-level package names: - The classic ``attr`` that powers the venerable `attr.s` and `attr.ib`. - The newer ``attrs`` that only contains most modern APIs and relies on `attrs.define` and `attrs.field` to define your classes. Additionally, some of the APIs that also exist in ``attr`` have nicer defaults (for example, `attrs.asdict`). The ``attrs`` namespace is built *on top of* ``attr`` -- which will *never* go away -- and is just as stable, since it doesn't constitute a rewrite. To keep repetition low and this document at a reasonable size, the ``attr`` namespace is `documented on a separate page `. Core ---- .. autofunction:: attrs.define .. function:: mutable(same_as_define) Same as `attrs.define`. .. versionadded:: 20.1.0 .. function:: frozen(same_as_define) Behaves the same as `attrs.define` but sets *frozen=True* and *on_setattr=None*. .. versionadded:: 20.1.0 .. autofunction:: field .. autoclass:: Attribute :members: evolve For example: .. doctest:: >>> import attrs >>> from attrs import define, field >>> @define ... class C: ... x = field() >>> attrs.fields(C).x Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x') .. autofunction:: make_class This is handy if you want to programmatically create classes. For example: .. doctest:: >>> C1 = attrs.make_class(""C1"", [""x"", ""y""]) >>> C1(1, 2) C1(x=1, y=2) >>> C2 = attrs.make_class(""C2"", { ... ""x"": field(default=42), ... ""y"": field(factory=list) ... }) >>> C2() C2(x=42, y=[]) .. autoclass:: Factory For example: .. doctest:: >>> @define ... class C: ... x = field(default=attrs.Factory(list)) ... y = field(default=attrs.Factory( ... lambda self: set(self.x), ... takes_self=True) ... ) >>> C() C(x=[], y=set()) >>> C([1, 2, 3]) C(x=[1, 2, 3], y={1, 2, 3}) .. autodata:: attrs.NOTHING :no-value: Exceptions ---------- .. module:: attrs.exceptions All exceptions are available from both ``attr.exceptions`` and ``attrs.exceptions`` and are the same thing. That means that it doesn't matter from from which namespace they've been raised and/or caught: .. doctest:: >>> import attrs, attr >>> try: ... raise attrs.exceptions.FrozenError() ... except attr.exceptions.FrozenError: ... print(""this works!"") this works! .. autoexception:: PythonTooOldError .. autoexception:: FrozenError .. autoexception:: FrozenInstanceError .. autoexception:: FrozenAttributeError .. autoexception:: AttrsAttributeNotFoundError .. autoexception:: NotAnAttrsClassError .. autoexception:: DefaultAlreadySetError .. autoexception:: NotCallableError .. autoexception:: UnannotatedAttributeError For example:: @attr.s(auto_attribs=True) class C: x: int y = attr.ib() # <- ERROR! .. _helpers: ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:0:3754"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-api.rst-1,dp-attrs-api.rst,"Helpers ------- *attrs* comes with a bunch of helper methods that make working with it easier: .. currentmodule:: attrs .. autofunction:: attrs.cmp_using .. autofunction:: attrs.fields For example: .. doctest:: >>> @define ... class C: ... x = field() ... y = field() >>> attrs.fields(C) (Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x'), Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y')) >>> attrs.fields(C(1, 2)) is attrs.fields(C) True >>> attrs.fields(C)[1] Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y') >>> attrs.fields(C).y is attrs.fields(C)[1] True .. autofunction:: attrs.fields_dict For example: .. doctest:: >>> @attr.s ... class C: ... x = attr.ib() ... y = attr.ib() >>> attrs.fields_dict(C) {'x': Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x'), 'y': Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y')} >>> attr.fields_dict(C)['y'] Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y') >>> attrs.fields_dict(C)['y'] is attrs.fields(C).y True .. autofunction:: attrs.has For example: .. doctest:: >>> @define ... class C: ... pass >>> attrs.has(C) True >>> attrs.has(object) False .. autofunction:: attrs.inspect For example: .. doctest:: >>> @define ... class CInspect: ... pass >>> attrs.inspect(CInspect) # doctest: +ELLIPSIS ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=True, added_ordering=False, hashability=, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=.wrapped_pipe at ...>, field_transformer=None) .. autoclass:: attrs.ClassProps .. autoclass:: attrs.ClassProps.Hashability :members: HASHABLE, HASHABLE_CACHED, UNHASHABLE, LEAVE_ALONE .. autoclass:: attrs.ClassProps.KeywordOnly :members: NO, YES, FORCE .. autofunction:: attrs.resolve_types For example: .. doctest:: >>> import typing >>> @define ... class A: ... a: typing.List['A'] ... b: 'B' ... >>> @define ... class B: ... a: A ... >>> attrs.fields(A).a.type typing.List[ForwardRef('A')] >>> attrs.fields(A).b.type 'B' >>> attrs.resolve_types(A, globals(), locals()) >>> attrs.fields(A).a.type typing.List[A] >>> attrs.fields(A).b.type .. autofunction:: attrs.asdict For example: .. doctest:: >>> @define ... class C: ... x: int ... y: int >>> attrs.asdict(C(1, C(2, 3))) {'x': 1, 'y': {'x': 2, 'y': 3}} .. autofunction:: attrs.astuple For example: .. doctest:: >>> @define ... class C: ... x = field() ... y = field() >>> attrs.astuple(C(1,2)) (1, 2) .. module:: attrs.filters *attrs* includes helpers for filtering the attributes in `attrs.asdict` and `attrs.astuple`: .. autofunction:: include .. autofunction:: exclude See :func:`attrs.asdict` for examples. All objects from ``attrs.filters`` are also available from ``attr.filters`` (it's the same module in a different namespace). ---- .. currentmodule:: attrs .. autofunction:: attrs.evolve For example: .. doctest:: >>> @define ... class C: ... x: int ... y: int >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = attrs.evolve(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False ``evolve`` creates a new instance using ``__init__``. This fact has several implications: * private attributes should be specified without the leading underscore, just like in ``__init__``. * attributes with ``init=False`` can't be set with ``evolve``. * the usual ``__init__`` validators will validate the new values. .. autofunction:: attrs.validate For example: .. doctest:: >>> @define(on_setattr=attrs.setters.NO_OP) ... class C: ... x = field(validator=attrs.validators.instance_of(int)) >>> i = C(1) >>> i.x = ""1"" >>> attrs.validate(i) Traceback (most recent call last): ... TypeError: (""'x' must be (got '1' that is a )."", ...) .. _api-validators: ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:3754:9570"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-api.rst-2,dp-attrs-api.rst,"Validators ---------- .. module:: attrs.validators *attrs* comes with some common validators in the ``attrs.validators`` module. All objects from ``attrs.validators`` are also available from ``attr.validators`` (it's the same module in a different namespace). .. autofunction:: attrs.validators.lt For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.lt(42)) >>> C(41) C(x=41) >>> C(42) Traceback (most recent call last): ... ValueError: (""'x' must be < 42: 42"") .. autofunction:: attrs.validators.le For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.le(42)) >>> C(42) C(x=42) >>> C(43) Traceback (most recent call last): ... ValueError: (""'x' must be <= 42: 43"") .. autofunction:: attrs.validators.ge For example: .. doctest:: >>> @define ... class C: ... x = attrs.field(validator=attrs.validators.ge(42)) >>> C(42) C(x=42) >>> C(41) Traceback (most recent call last): ... ValueError: (""'x' must be => 42: 41"") .. autofunction:: attrs.validators.gt For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.gt(42)) >>> C(43) C(x=43) >>> C(42) Traceback (most recent call last): ... ValueError: (""'x' must be > 42: 42"") .. autofunction:: attrs.validators.max_len For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.max_len(4)) >>> C(""spam"") C(x='spam') >>> C(""bacon"") Traceback (most recent call last): ... ValueError: (""Length of 'x' must be <= 4: 5"") .. autofunction:: attrs.validators.min_len For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.min_len(1)) >>> C(""bacon"") C(x='bacon') >>> C("""") Traceback (most recent call last): ... ValueError: (""Length of 'x' must be => 1: 0"") .. autofunction:: attrs.validators.instance_of For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.instance_of(int)) >>> C(42) C(x=42) >>> C(""42"") Traceback (most recent call last): ... TypeError: (""'x' must be (got '42' that is a )."", Attribute(name='x', default=NOTHING, validator=>, type=None, kw_only=False), , '42') >>> C(None) Traceback (most recent call last): ... TypeError: (""'x' must be (got None that is a )."", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=None, init=True, type=None, kw_only=False), , None) .. autofunction:: attrs.validators.in_ For example: ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:9570:12690"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-api.rst-3,dp-attrs-api.rst," .. autofunction:: attrs.validators.in_ For example: .. doctest:: >>> import enum >>> class State(enum.Enum): ... ON = ""on"" ... OFF = ""off"" >>> @define ... class C: ... state = field(validator=attrs.validators.in_(State)) ... val = field(validator=attrs.validators.in_([1, 2, 3])) >>> C(State.ON, 1) C(state=, val=1) >>> C(""On"", 1) Traceback (most recent call last): ... ValueError: 'state' must be in (got 'On'), Attribute(name='state', default=NOTHING, validator=>, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None), , 'on') >>> C(State.ON, 4) Traceback (most recent call last): ... ValueError: 'val' must be in [1, 2, 3] (got 4), Attribute(name='val', default=NOTHING, validator=, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None), [1, 2, 3], 4) .. autofunction:: attrs.validators.and_ For convenience, it's also possible to pass a list to `attrs.field`'s validator argument. Thus the following two statements are equivalent:: x = field(validator=attrs.validators.and_(v1, v2, v3)) x = field(validator=[v1, v2, v3]) .. autofunction:: attrs.validators.or_ For example: .. doctest:: >>> @define ... class C: ... val: int | list[int] = field( ... validator=attrs.validators.or_( ... attrs.validators.instance_of(int), ... attrs.validators.deep_iterable(attrs.validators.instance_of(int)), ... ) ... ) >>> C(42) C(val=42) >>> C([1, 2, 3]) C(val=[1, 2, 3]) >>> C(val='42') Traceback (most recent call last): ... ValueError: None of (>, >>) satisfied for value '42' .. autofunction:: attrs.validators.not_ For example: .. doctest:: >>> reserved_names = {""id"", ""time"", ""source""} >>> @define ... class Measurement: ... tags = field( ... validator=attrs.validators.deep_mapping( ... key_validator=attrs.validators.not_( ... attrs.validators.in_(reserved_names), ... msg=""reserved tag key"", ... ), ... value_validator=attrs.validators.instance_of((str, int)), ... ) ... ) >>> Measurement(tags={""source"": ""universe""}) Traceback (most recent call last): ... ValueError: (""reserved tag key"", Attribute(name='tags', default=NOTHING, validator=, capturing (, )>, type=None, kw_only=False), , {'source_': 'universe'}, (, )) >>> Measurement(tags={""source_"": ""universe""}) Measurement(tags={'source_': 'universe'}) .. autofunction:: attrs.validators.optional For example: ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:12632:16161"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-api.rst-4,dp-attrs-api.rst," >>> Measurement(tags={""source_"": ""universe""}) Measurement(tags={'source_': 'universe'}) .. autofunction:: attrs.validators.optional For example: .. doctest:: >>> @define ... class C: ... x = field( ... validator=attrs.validators.optional( ... attrs.validators.instance_of(int) ... )) >>> C(42) C(x=42) >>> C(""42"") Traceback (most recent call last): ... TypeError: (""'x' must be (got '42' that is a )."", Attribute(name='x', default=NOTHING, validator=>, type=None, kw_only=False), , '42') >>> C(None) C(x=None) .. autofunction:: attrs.validators.is_callable For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.is_callable()) >>> C(isinstance) C(x=) >>> C(""not a callable"") Traceback (most recent call last): ... attr.exceptions.NotCallableError: 'x' must be callable (got 'not a callable' that is a ). .. autofunction:: attrs.validators.matches_re For example: .. doctest:: >>> @define ... class User: ... email = field(validator=attrs.validators.matches_re( ... r""(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"")) >>> User(email=""user@example.com"") User(email='user@example.com') >>> User(email=""user@example.com@test.com"") Traceback (most recent call last): ... ValueError: (""'email' must match regex '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$)' ('user@example.com@test.com' doesn't)"", Attribute(name='email', default=NOTHING, validator=, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)'), 'user@example.com@test.com') .. autofunction:: attrs.validators.deep_iterable For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.deep_iterable( ... member_validator=attrs.validators.instance_of(int), ... iterable_validator=attrs.validators.instance_of(list) ... )) >>> C(x=[1, 2, 3]) C(x=[1, 2, 3]) >>> C(x=set([1, 2, 3])) Traceback (most recent call last): ... TypeError: (""'x' must be (got {1, 2, 3} that is a )."", Attribute(name='x', default=NOTHING, validator=> iterables of >>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), , {1, 2, 3}) >>> C(x=[1, 2, ""3""]) Traceback (most recent call last): ... TypeError: (""'x' must be (got '3' that is a )."", Attribute(name='x', default=NOTHING, validator=> iterables of >>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), , '3') .. autofunction:: attrs.validators.deep_mapping For example: .. doctest:: >>> @define ... class C: ... x = field(validator=attrs.validators.deep_mapping( ... key_validator=attrs.validators.instance_of(str), ... value_validator=attrs.validators.instance_of(int), ... mapping_validator=attrs.validators.instance_of(dict) ... )) >>> C(x={""a"": 1, ""b"": 2}) C(x={'a': 1, 'b': 2}) >>> C(x=None) Traceback (most recent call last): ... TypeError: (""'x' must be (got None that is a )."", Attribute(name='x', default=NOTHING, validator=> to >>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), , None) >>> C(x={""a"": 1.0, ""b"": 2}) Traceback (most recent call last): ... TypeError: (""'x' must be (got 1.0 that is a )."", Attribute(name='x', default=NOTHING, validator=> to >>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), , 1.0) >>> C(x={""a"": 1, 7: 2}) Traceback (most recent call last): ... TypeError: (""'x' must be (got 7 that is a )."", Attribute(name='x', default=NOTHING, validator=> to >>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), , 7) Validators can be both globally and locally disabled: .. autofunction:: attrs.validators.set_disabled .. autofunction:: attrs.validators.get_disabled .. autofunction:: attrs.validators.disabled ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:15997:21786"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-api.rst-5,dp-attrs-api.rst,"Converters ---------- .. autoclass:: attrs.Converter For example: .. doctest:: >>> def complicated(value, self_, field): ... return int(value) * self_.factor + field.metadata[""offset""] >>> @define ... class C: ... factor = 5 # not an *attrs* field ... x = field( ... metadata={""offset"": 200}, ... converter=attrs.Converter( ... complicated, ... takes_self=True, takes_field=True ... )) >>> C(""42"") C(x=410) .. module:: attrs.converters All objects from ``attrs.converters`` are also available from ``attr.converters`` (it's the same module in a different namespace). .. autofunction:: attrs.converters.pipe For convenience, it's also possible to pass a list to `attrs.field` / `attr.ib`'s converter arguments. Thus the following two statements are equivalent:: x = attrs.field(converter=attrs.converter.pipe(c1, c2, c3)) x = attrs.field(converter=[c1, c2, c3]) .. autofunction:: attrs.converters.optional For example: .. doctest:: >>> @define ... class C: ... x = field(converter=attrs.converters.optional(int)) >>> C(None) C(x=None) >>> C(42) C(x=42) .. autofunction:: attrs.converters.default_if_none For example: .. doctest:: >>> @define ... class C: ... x = field( ... converter=attrs.converters.default_if_none("""") ... ) >>> C(None) C(x='') .. autofunction:: attrs.converters.to_bool(val) For example: .. doctest:: >>> @define ... class C: ... x = field( ... converter=attrs.converters.to_bool ... ) >>> C(""yes"") C(x=True) >>> C(0) C(x=False) >>> C(""norway"") Traceback (most recent call last): File """", line 1, in ValueError: Cannot convert value to bool: norway .. _api_setters: Setters ------- .. module:: attrs.setters These are helpers that you can use together with `attrs.define`'s and `attrs.field`'s ``on_setattr`` arguments. All setters in ``attrs.setters`` are also available from ``attr.setters`` (it's the same module in a different namespace). .. autofunction:: frozen .. autofunction:: validate .. autofunction:: convert .. autofunction:: pipe .. data:: NO_OP Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. Does not work in `attrs.setters.pipe` or within lists. .. versionadded:: 20.1.0 For example, only ``x`` is frozen here: .. doctest:: >>> @define(on_setattr=attr.setters.frozen) ... class C: ... x = field() ... y = field(on_setattr=attr.setters.NO_OP) >>> c = C(1, 2) >>> c.y = 3 >>> c.y 3 >>> c.x = 4 Traceback (most recent call last): ... attrs.exceptions.FrozenAttributeError: () .. tip:: Use `attrs.define`'s *frozen* argument (or `attrs.frozen`) to freeze whole classes; it is more efficient. ",en,software_docs,attrs 26.1.0,"[{""license"": ""MIT"", ""locator"": ""attrs-26.1.0/docs/api.rst#codepoints:21786:24870"", ""revision"": ""26.1.0+sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"", ""source_id"": ""attrs-26.1:api.rst"", ""uri"": ""https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz""}]" dp-pt-attrs-26.1-index.md-0,dp-attrs-index.md,"# *attrs*: Classes Without Boilerplate Release **{sub-ref}`release`** ([What's new?](changelog.md)) ```{include} ../README.md :start-after: 'teaser-begin -->' :end-before: ' ```{include} ../README.md :start-after: 'sponsor-break-end -->' :end-before: '