General / 23 matching questions
Complete retained English RST / PSF License v2
What is Python?
Source occurrences: 1 / Link to question
[1] general.rst L16-16Read the retained source context
English original, selected lines 16-28. Excerpt only; continue in the linked complete file.
What is Python?
---------------
Python is an interpreted, interactive, object-oriented programming language. It
incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes. It supports multiple programming paradigms beyond
object-oriented programming, such as procedural and functional programming.
Python combines remarkable power with very clear syntax. It has interfaces to
many system calls and libraries, as well as to various window systems, and is
extensible in C or C++. It is also usable as an extension language for
applications that need a programmable interface. Finally, Python is portable:
it runs on many Unix variants including Linux and macOS, and on Windows.
What is the Python Software Foundation?
Source occurrences: 1 / Link to question
[1] general.rst L34-34Read the retained source context
English original, selected lines 34-46. Excerpt only; continue in the linked complete file.
What is the Python Software Foundation?
---------------------------------------
The Python Software Foundation is an independent non-profit organization that
holds the copyright on Python versions 2.1 and newer. The PSF's mission is to
advance open source technology related to the Python programming language and to
publicize the use of Python. The PSF's home page is at
https://www.python.org/psf/.
Donations to the PSF are tax-exempt in the US. If you use Python and find it
helpful, please contribute via `the PSF donation page
<https://www.python.org/psf/donations/>`_.
Are there copyright restrictions on the use of Python?
Source occurrences: 1 / Link to question
[1] general.rst L48-48Read the retained source context
English original, selected lines 48-60. Excerpt only; continue in the linked complete file.
Are there copyright restrictions on the use of Python?
------------------------------------------------------
You can do anything you want with the source, as long as you leave the
copyrights in and display those copyrights in any documentation about Python
that you produce. If you honor the copyright rules, it's OK to use Python for
commercial use, to sell copies of Python in source or binary form (modified or
unmodified), or to sell products that incorporate Python in some form. We would
still like to know about all commercial use of Python, of course.
See `the license page <https://docs.python.org/3/license.html>`_ to find further
explanations and the full text of the PSF License.
Why was Python created in the first place?
Source occurrences: 1 / Link to question
[1] general.rst L66-66Read the retained source context
English original, selected lines 66-78. Excerpt only; continue in the linked complete file.
Why was Python created in the first place?
------------------------------------------
Here's a *very* brief summary of what started it all, written by Guido van
Rossum:
I had extensive experience with implementing an interpreted language in the
ABC group at CWI, and from working with this group I had learned a lot about
language design. This is the origin of many Python features, including the
use of indentation for statement grouping and the inclusion of
very-high-level data types (although the details are all different in
Python).
What is Python good for?
Source occurrences: 1 / Link to question
[1] general.rst L109-109Read the retained source context
English original, selected lines 109-121. Excerpt only; continue in the linked complete file.
What is Python good for?
------------------------
Python is a high-level general-purpose programming language that can be applied
to many different classes of problems.
The language comes with a large standard library that covers areas such as
string processing (regular expressions, Unicode, calculating differences between
files), internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP),
software engineering (unit testing, logging, profiling, parsing
Python code), and operating system interfaces (system calls, filesystems, TCP/IP
sockets). Look at the table of contents for :ref:`library-index` to get an idea
of what's available. A wide variety of third-party extensions are also
How does the Python version numbering scheme work?
Source occurrences: 1 / Link to question
[1] general.rst L128-128Read the retained source context
English original, selected lines 128-140. Excerpt only; continue in the linked complete file.
How does the Python version numbering scheme work?
--------------------------------------------------
Python versions are numbered "A.B.C" or "A.B":
* *A* is the major version number -- it is only incremented for really major
changes in the language.
* *B* is the minor version number -- it is incremented for less earth-shattering
changes.
* *C* is the micro version number -- it is incremented for each bugfix release.
Not all releases are bugfix releases. In the run-up to a new feature release, a
series of development releases are made, denoted as alpha, beta, or release
How do I obtain a copy of the Python source?
Source occurrences: 1 / Link to question
[1] general.rst L169-169Read the retained source context
English original, selected lines 169-181. Excerpt only; continue in the linked complete file.
How do I obtain a copy of the Python source?
--------------------------------------------
The latest Python source distribution is always available from python.org, at
https://www.python.org/downloads/. The latest development sources can be obtained
at https://github.com/python/cpython/.
The source distribution is a gzipped tar file containing the complete C source,
Sphinx-formatted documentation, Python library modules, example programs, and
several useful pieces of freely distributable software. The source will compile
and run out of the box on most UNIX platforms.
Consult the `Getting Started section of the Python Developer's Guide
How do I get documentation on Python?
Source occurrences: 1 / Link to question
[1] general.rst L186-186Read the retained source context
English original, selected lines 186-198. Excerpt only; continue in the linked complete file.
How do I get documentation on Python?
-------------------------------------
The standard documentation for the current stable version of Python is available
at https://docs.python.org/3/. EPUB, plain text, and downloadable HTML versions are
also available at https://docs.python.org/3/download.html.
The documentation is written in reStructuredText and processed by `the Sphinx
documentation tool <https://www.sphinx-doc.org/>`__. The reStructuredText source for
the documentation is part of the Python source distribution.
I've never programmed before. Is there a Python tutorial?
I've never programmed before. Is there a Python tutorial?
Source occurrences: 1 / Link to question
[1] general.rst L198-198Read the retained source context
English original, selected lines 198-210. Excerpt only; continue in the linked complete file.
I've never programmed before. Is there a Python tutorial?
---------------------------------------------------------
There are numerous tutorials and books available. The standard documentation
includes :ref:`tutorial-index`.
Consult `the Beginner's Guide <https://wiki.python.org/moin/BeginnersGuide>`_ to
find information for beginning Python programmers, including lists of tutorials.
Is there a newsgroup or mailing list devoted to Python?
-------------------------------------------------------
Is there a newsgroup or mailing list devoted to Python?
Source occurrences: 1 / Link to question
[1] general.rst L208-208Read the retained source context
English original, selected lines 208-220. Excerpt only; continue in the linked complete file.
Is there a newsgroup or mailing list devoted to Python?
-------------------------------------------------------
There is a newsgroup, :newsgroup:`comp.lang.python`, and a mailing list,
`python-list <https://mail.python.org/mailman/listinfo/python-list>`_. The
newsgroup and mailing list are gatewayed into each other -- if you can read news
it's unnecessary to subscribe to the mailing list.
:newsgroup:`comp.lang.python` is high-traffic, receiving hundreds of postings
every day, and Usenet readers are often more able to cope with this volume.
Announcements of new software releases and events can be found in
comp.lang.python.announce, a low-traffic moderated list that receives about five
postings per day. It's available as `the python-announce mailing list
How do I get a beta test version of Python?
Source occurrences: 1 / Link to question
[1] general.rst L227-227Read the retained source context
English original, selected lines 227-239. Excerpt only; continue in the linked complete file.
How do I get a beta test version of Python?
-------------------------------------------
Alpha and beta releases are available from https://www.python.org/downloads/. All
releases are announced on the comp.lang.python and comp.lang.python.announce
newsgroups and on the Python home page at https://www.python.org/; an RSS feed of
news is available.
You can also access the development version of Python through Git. See
`The Python Developer's Guide <https://devguide.python.org/>`_ for details.
How do I submit bug reports and patches for Python?
How do I submit bug reports and patches for Python?
Source occurrences: 1 / Link to question
[1] general.rst L239-239Read the retained source context
English original, selected lines 239-251. Excerpt only; continue in the linked complete file.
How do I submit bug reports and patches for Python?
---------------------------------------------------
To report a bug or submit a patch, use the issue tracker at
https://github.com/python/cpython/issues.
For more information on how Python is developed, consult `the Python Developer's
Guide <https://devguide.python.org/>`_.
Are there any published articles about Python that I can reference?
-------------------------------------------------------------------
Are there any published articles about Python that I can reference?
Source occurrences: 1 / Link to question
[1] general.rst L249-249Read the retained source context
English original, selected lines 249-261. Excerpt only; continue in the linked complete file.
Are there any published articles about Python that I can reference?
-------------------------------------------------------------------
It's probably best to cite your favorite book about Python.
The `very first article <https://ir.cwi.nl/pub/18204>`_ about Python was
written in 1991 and is now quite outdated.
Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers
Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4
(December 1991), Amsterdam, pp 283--303.
Are there any books on Python?
Source occurrences: 1 / Link to question
[1] general.rst L262-262Read the retained source context
English original, selected lines 262-274. Excerpt only; continue in the linked complete file.
Are there any books on Python?
------------------------------
Yes, there are many, and more are being published. See the python.org wiki at
https://wiki.python.org/moin/PythonBooks for a list.
You can also search online bookstores for "Python" and filter out the Monty
Python references; or perhaps search for "Python" and "language".
Where in the world is www.python.org located?
---------------------------------------------
Where in the world is www.python.org located?
Source occurrences: 1 / Link to question
[1] general.rst L272-272Read the retained source context
English original, selected lines 272-284. Excerpt only; continue in the linked complete file.
Where in the world is www.python.org located?
---------------------------------------------
The Python project's infrastructure is located all over the world and is managed
by the Python Infrastructure Team. Details `here <https://infra.psf.io>`__.
Why is it called Python?
------------------------
When he began implementing Python, Guido van Rossum was also reading the
published scripts from `"Monty Python's Flying Circus"
<https://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s. Van Rossum
Why is it called Python?
Source occurrences: 1 / Link to question
[1] general.rst L279-279Read the retained source context
English original, selected lines 279-291. Excerpt only; continue in the linked complete file.
Why is it called Python?
------------------------
When he began implementing Python, Guido van Rossum was also reading the
published scripts from `"Monty Python's Flying Circus"
<https://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s. Van Rossum
thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python.
Do I have to like "Monty Python's Flying Circus"?
-------------------------------------------------
Do I have to like "Monty Python's Flying Circus"?
Source occurrences: 1 / Link to question
[1] general.rst L289-289Read the retained source context
English original, selected lines 289-301. Excerpt only; continue in the linked complete file.
Do I have to like "Monty Python's Flying Circus"?
-------------------------------------------------
No, but it helps. :)
Python in the real world
========================
How stable is Python?
---------------------
Very stable. New, stable releases have been coming out roughly every 6 to 18
How stable is Python?
Source occurrences: 1 / Link to question
[1] general.rst L298-298Read the retained source context
English original, selected lines 298-310. Excerpt only; continue in the linked complete file.
How stable is Python?
---------------------
Very stable. New, stable releases have been coming out roughly every 6 to 18
months since 1991, and this seems likely to continue. As of version 3.9,
Python will have a new feature release every 12 months (:pep:`602`).
The developers issue bugfix releases of older versions, so the stability of
existing releases gradually improves. Bugfix releases, indicated by a third
component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability;
only fixes for known problems are included in a bugfix release, and it's
guaranteed that interfaces will remain the same throughout a series of bugfix
releases.
How many people are using Python?
Source occurrences: 1 / Link to question
[1] general.rst L317-317Read the retained source context
English original, selected lines 317-329. Excerpt only; continue in the linked complete file.
How many people are using Python?
---------------------------------
There are probably millions of users, though it's difficult to obtain an exact
count.
Python is available for free download, so there are no sales figures, and it's
available from many different sites and packaged with many Linux distributions,
so download statistics don't tell the whole story either.
The comp.lang.python newsgroup is very active, but not all Python users post to
the group or even read it.
Have any significant projects been done in Python?
Source occurrences: 1 / Link to question
[1] general.rst L331-331Read the retained source context
English original, selected lines 331-343. Excerpt only; continue in the linked complete file.
Have any significant projects been done in Python?
--------------------------------------------------
See https://www.python.org/about/success for a list of projects that use Python.
Consulting the proceedings for `past Python conferences
<https://www.python.org/community/workshops/>`_ will reveal contributions from many
different companies and organizations.
High-profile Python projects include `the Mailman mailing list manager
<https://www.list.org>`_ and `the Zope application server
<https://www.zope.dev>`_. Several Linux distributions, most notably `Red Hat
<https://www.redhat.com>`_, have written part or all of their installer and
system administration software in Python. Companies that use Python internally
What new developments are expected for Python in the future?
Source occurrences: 1 / Link to question
[1] general.rst L347-347Read the retained source context
English original, selected lines 347-359. Excerpt only; continue in the linked complete file.
What new developments are expected for Python in the future?
------------------------------------------------------------
See https://peps.python.org/ for the Python Enhancement Proposals
(PEPs). PEPs are design documents describing a suggested new feature for Python,
providing a concise technical specification and a rationale. Look for a PEP
titled "Python X.Y Release Schedule", where X.Y is a version that hasn't been
publicly released yet.
New development is discussed on `the python-dev mailing list
<https://mail.python.org/mailman3/lists/python-dev.python.org/>`_.
Is it reasonable to propose incompatible changes to Python?
Source occurrences: 1 / Link to question
[1] general.rst L360-360Read the retained source context
English original, selected lines 360-372. Excerpt only; continue in the linked complete file.
Is it reasonable to propose incompatible changes to Python?
-----------------------------------------------------------
In general, no. There are already millions of lines of Python code around the
world, so any change in the language that invalidates more than a very small
fraction of existing programs has to be frowned upon. Even if you can provide a
conversion program, there's still the problem of updating all documentation;
many books have been written about Python, and we don't want to invalidate them
all at a single stroke.
Providing a gradual upgrade path is necessary if a feature has to be changed.
:pep:`5` describes the procedure followed for introducing backward-incompatible
changes while minimizing disruption for users.
Is Python a good language for beginning programmers?
Source occurrences: 1 / Link to question
[1] general.rst L375-375Read the retained source context
English original, selected lines 375-387. Excerpt only; continue in the linked complete file.
Is Python a good language for beginning programmers?
----------------------------------------------------
Yes.
It is still common to start students with a procedural and statically typed
language such as Pascal, C, or a subset of C++ or Java. Students may be better
served by learning Python as their first language. Python has a very simple and
consistent syntax and a large standard library and, most importantly, using
Python in a beginning programming course lets students concentrate on important
programming skills such as problem decomposition and data type design. With
Python, students can be quickly introduced to basic concepts such as loops and
procedures. They can probably even work with user-defined objects in their very
Programming / 65 matching questions
Complete retained English RST / PSF License v2
Is there a source code-level debugger with breakpoints and single-stepping?
Source occurrences: 1 / Link to question
[2] programming.rst L15-15Read the retained source context
English original, selected lines 15-27. Excerpt only; continue in the linked complete file.
Is there a source code-level debugger with breakpoints and single-stepping?
---------------------------------------------------------------------------
Yes.
Several debuggers for Python are described below, and the built-in function
:func:`breakpoint` allows you to drop into any of them.
The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is :mod:`documented in the Library
Reference Manual <pdb>`. You can also write your own debugger by using the code
for pdb as an example.
Are there tools to help find bugs or perform static analysis?
Source occurrences: 1 / Link to question
[2] programming.rst L54-54Read the retained source context
English original, selected lines 54-66. Excerpt only; continue in the linked complete file.
Are there tools to help find bugs or perform static analysis?
-------------------------------------------------------------
Yes.
`Ruff <https://docs.astral.sh/ruff/>`__,
`Pylint <https://pylint.readthedocs.io/>`__ and
`Pyflakes <https://github.com/PyCQA/pyflakes>`__ do basic checking that will
help you catch bugs sooner.
Static type checkers such as `mypy <https://mypy-lang.org/>`__,
`ty <https://docs.astral.sh/ty/>`__,
`Pyrefly <https://pyrefly.org/>`__, and
How can I create a stand-alone binary from a Python script?
Source occurrences: 1 / Link to question
[2] programming.rst L73-73Read the retained source context
English original, selected lines 73-85. Excerpt only; continue in the linked complete file.
How can I create a stand-alone binary from a Python script?
-----------------------------------------------------------
You don't need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first. There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.
One is to use the freeze tool, which is included in the Python source tree as
:source:`Tools/freeze`.
It converts Python byte code to C arrays; with a C compiler you can
embed all your modules into a new program, which is then linked with the
Are there coding standards or a style guide for Python programs?
Source occurrences: 1 / Link to question
[2] programming.rst L108-108Read the retained source context
English original, selected lines 108-120. Excerpt only; continue in the linked complete file.
Are there coding standards or a style guide for Python programs?
----------------------------------------------------------------
Yes. The coding style required for standard library modules is documented as
:pep:`8`.
Core language
=============
.. _faq-unboundlocalerror:
Why am I getting an UnboundLocalError when the variable has a value?
Why am I getting an UnboundLocalError when the variable has a value?
Source occurrences: 1 / Link to question
[2] programming.rst L120-120Read the retained source context
English original, selected lines 120-132. Excerpt only; continue in the linked complete file.
Why am I getting an UnboundLocalError when the variable has a value?
--------------------------------------------------------------------
It can be a surprise to get the :exc:`UnboundLocalError` in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.
This code:
>>> x = 10
>>> def bar():
... print(x)
...
What are the rules for local and global variables in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L193-193Read the retained source context
English original, selected lines 193-205. Excerpt only; continue in the linked complete file.
What are the rules for local and global variables in Python?
------------------------------------------------------------
In Python, variables that are only referenced inside a function are implicitly
global. If a variable is assigned a value anywhere within the function's body,
it's assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment's consideration explains this. On
one hand, requiring :keyword:`global` for assigned variables provides a bar
against unintended side-effects. On the other hand, if ``global`` was required
for all global references, you'd be using ``global`` all the time. You'd have
to declare as global every reference to a built-in function or to a component of
an imported module. This clutter would defeat the usefulness of the ``global``
Why do lambdas defined in a loop with different values all return the same result?
Source occurrences: 1 / Link to question
[2] programming.rst L209-209Read the retained source context
English original, selected lines 209-221. Excerpt only; continue in the linked complete file.
Why do lambdas defined in a loop with different values all return the same result?
----------------------------------------------------------------------------------
Assume you use a for loop to define a few different lambdas (or even plain
functions), for example::
>>> squares = []
>>> for x in range(5):
... squares.append(lambda: x**2)
This gives you a list that contains 5 lambdas that calculate ``x**2``. You
might expect that, when called, they would return, respectively, ``0``, ``1``,
``4``, ``9``, and ``16``. However, when you actually try you will see that
How do I share global variables across modules?
Source occurrences: 1 / Link to question
[2] programming.rst L261-261Read the retained source context
English original, selected lines 261-273. Excerpt only; continue in the linked complete file.
How do I share global variables across modules?
------------------------------------------------
The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg). Just import the config
module in all modules of your application; the module then becomes available as
a global name. Because there is only one instance of each module, any changes
made to the module object get reflected everywhere. For example:
config.py::
x = 0 # Default value of the 'x' configuration setting
What are the "best practices" for using import in a module?
Source occurrences: 1 / Link to question
[2] programming.rst L289-289Read the retained source context
English original, selected lines 289-301. Excerpt only; continue in the linked complete file.
What are the "best practices" for using import in a module?
-----------------------------------------------------------
In general, don't use ``from modulename import *``. Doing so clutters the
importer's namespace, and makes it much harder for linters to detect undefined
names.
Import modules at the top of a file. Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.
It's good practice if you import modules in the following order:
Why are default values shared between objects?
Source occurrences: 1 / Link to question
[2] programming.rst L339-339Read the retained source context
English original, selected lines 339-351. Excerpt only; continue in the linked complete file.
Why are default values shared between objects?
----------------------------------------------
This type of bug commonly bites neophyte programmers. Consider this function::
def foo(mydict={}): # Danger: shared reference to one dict for all calls
... compute something ...
mydict[key] = value
return mydict
The first time you call this function, ``mydict`` contains a single item. The
second time, ``mydict`` contains two items because when ``foo()`` begins
executing, ``mydict`` starts out with an item already in it.How can I pass optional or keyword parameters from one function to another?
Source occurrences: 1 / Link to question
[2] programming.rst L395-395Read the retained source context
English original, selected lines 395-407. Excerpt only; continue in the linked complete file.
How can I pass optional or keyword parameters from one function to another?
---------------------------------------------------------------------------
Collect the arguments using the ``*`` and ``**`` specifiers in the function's
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary. You can then pass these arguments when
calling another function by using ``*`` and ``**``::
def f(x, *args, **kwargs):
...
kwargs['width'] = '14.3c'
...
g(x, *args, **kwargs)What is the difference between arguments and parameters?
Source occurrences: 1 / Link to question
[2] programming.rst L416-416Read the retained source context
English original, selected lines 416-428. Excerpt only; continue in the linked complete file.
What is the difference between arguments and parameters?
--------------------------------------------------------
:term:`Parameters <parameter>` are defined by the names that appear in a
function definition, whereas :term:`arguments <argument>` are the values
actually passed to a function when calling it. Parameters define what
:term:`kind of arguments <parameter>` a function can accept. For
example, given the function definition::
def func(foo, bar=None, **kwargs):
pass
*foo*, *bar* and *kwargs* are parameters of ``func``. However, when callingWhy did changing list 'y' also change list 'x'?
Source occurrences: 1 / Link to question
[2] programming.rst L436-436Read the retained source context
English original, selected lines 436-448. Excerpt only; continue in the linked complete file.
Why did changing list 'y' also change list 'x'?
------------------------------------------------
If you wrote code like::
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
How do I write a function with output parameters (call by reference)?
Source occurrences: 1 / Link to question
[2] programming.rst L511-511Read the retained source context
English original, selected lines 511-523. Excerpt only; continue in the linked complete file.
How do I write a function with output parameters (call by reference)?
---------------------------------------------------------------------
Remember that arguments are passed by assignment in Python. Since assignment
just creates references to objects, there's no alias between an argument name in
the caller and callee, and consequently no call-by-reference. You can achieve the
desired effect in a number of ways.
1) By returning a tuple of the results::
>>> def func1(a, b):
... a = 'new-value' # a and b are local names
... b = b + 1 # assigned to new objectsHow do you make a higher order function in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L578-578Read the retained source context
English original, selected lines 578-590. Excerpt only; continue in the linked complete file.
How do you make a higher order function in Python?
--------------------------------------------------
You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define ``linear(a,b)`` which returns a
function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
def linear(a, b):
def result(x):
return a * x + b
return result
Or using a callable object::How do I copy an object in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L637-637Read the retained source context
English original, selected lines 637-649. Excerpt only; continue in the linked complete file.
How do I copy an object in Python?
----------------------------------
In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
method::
newdict = olddict.copy()
Sequences can be copied by slicing::
How can I find the methods or attributes of an object?
Source occurrences: 1 / Link to question
[2] programming.rst L653-653Read the retained source context
English original, selected lines 653-665. Excerpt only; continue in the linked complete file.
How can I find the methods or attributes of an object?
------------------------------------------------------
For an instance ``x`` of a user-defined class, :func:`dir(x) <dir>` returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.
How can my code discover the name of an object?
-----------------------------------------------
Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of
How can my code discover the name of an object?
Source occurrences: 1 / Link to question
[2] programming.rst L661-661Read the retained source context
English original, selected lines 661-673. Excerpt only; continue in the linked complete file.
How can my code discover the name of an object?
-----------------------------------------------
Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of
``def`` and ``class`` statements, but in that case the value is a
callable. Consider the following code::
>>> class A:
... pass
...
>>> B = A
>>> a = B()
What's up with the comma operator's precedence?
Source occurrences: 1 / Link to question
[2] programming.rst L702-702Read the retained source context
English original, selected lines 702-714. Excerpt only; continue in the linked complete file.
What's up with the comma operator's precedence?
-----------------------------------------------
Comma is not an operator in Python. Consider this session::
>>> "a" in "b", "a"
(False, 'a')
Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered::
("a" in "b"), "a"
Is there an equivalent of C's "?:" ternary operator?
Source occurrences: 1 / Link to question
[2] programming.rst L723-723Read the retained source context
English original, selected lines 723-735. Excerpt only; continue in the linked complete file.
Is there an equivalent of C's "?:" ternary operator?
----------------------------------------------------
Yes, there is. The syntax is as follows::
[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y
Before this syntax was introduced in Python 2.5, a common idiom was to use
logical operators::
Is it possible to write obfuscated one-liners in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L743-743Read the retained source context
English original, selected lines 743-755. Excerpt only; continue in the linked complete file.
Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------
Yes. Usually this is done by nesting :keyword:`lambda` within
:keyword:`!lambda`. See the following three examples, slightly adapted from Ulf Bartelt::
from functools import reduce
# Primes < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
# First 10 Fibonacci numbers
What does the slash(/) in the parameter list of a function mean?
Source occurrences: 1 / Link to question
[2] programming.rst L778-778Read the retained source context
English original, selected lines 778-790. Excerpt only; continue in the linked complete file.
What does the slash(/) in the parameter list of a function mean?
----------------------------------------------------------------
A slash in the argument list of a function denotes that the parameters prior to
it are positional-only. Positional-only parameters are the ones without an
externally usable name. Upon calling a function that accepts positional-only
parameters, arguments are mapped to parameters based solely on their position.
For example, :func:`divmod` is a function that accepts positional-only
parameters. Its documentation looks like this::
>>> help(divmod)
Help on built-in function divmod in module builtins:
How do I specify hexadecimal and octal integers?
Source occurrences: 1 / Link to question
[2] programming.rst L807-807Read the retained source context
English original, selected lines 807-819. Excerpt only; continue in the linked complete file.
How do I specify hexadecimal and octal integers?
------------------------------------------------
To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase "o". For example, to set the variable "a" to the octal value "10"
(8 in decimal), type::
>>> a = 0o10
>>> a
8
Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
Why does -22 // 10 return -3?
Source occurrences: 1 / Link to question
[2] programming.rst L830-830Read the retained source context
English original, selected lines 830-842. Excerpt only; continue in the linked complete file.
Why does -22 // 10 return -3?
-----------------------------
It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
If you want that, and also want::
i == (i // j) * j + (i % j)
then integer division has to return the floor. C also requires that identity to
hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
the same sign as ``i``.
There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``How do I get int literal attribute instead of SyntaxError?
Source occurrences: 1 / Link to question
[2] programming.rst L849-849Read the retained source context
English original, selected lines 849-861. Excerpt only; continue in the linked complete file.
How do I get int literal attribute instead of SyntaxError?
----------------------------------------------------------
Trying to lookup an ``int`` literal attribute in the normal manner gives
a :exc:`SyntaxError` because the period is seen as a decimal point::
>>> 1.__class__
File "<stdin>", line 1
1.__class__
^
SyntaxError: invalid decimal literal
The solution is to separate the literal from the periodHow do I convert a string to a number?
Source occurrences: 1 / Link to question
[2] programming.rst L870-870Read the retained source context
English original, selected lines 870-882. Excerpt only; continue in the linked complete file.
How do I convert a string to a number?
--------------------------------------
For integers, use the built-in :func:`int` type constructor, for example, ``int('144')
== 144``. Similarly, :func:`float` converts to a floating-point number,
for example, ``float('144') == 144.0``.
By default, these interpret the number as decimal, so that ``int('0144') ==
144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string,
base)`` takes the base to convert from as a second optional argument, so ``int(
'0x144', 16) == 324``. If the base is specified as 0, the number is interpreted
using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex
number.How do I convert a number to a string?
Source occurrences: 1 / Link to question
[2] programming.rst L896-896Read the retained source context
English original, selected lines 896-908. Excerpt only; continue in the linked complete file.
How do I convert a number to a string?
--------------------------------------
For example, to convert the number ``144`` to the string ``'144'``, use the built-in type
constructor :func:`str`. If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
the :ref:`f-strings` and :ref:`formatstrings` sections.
For example, ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
How do I modify a string in place?
----------------------------------How do I modify a string in place?
Source occurrences: 1 / Link to question
[2] programming.rst L907-907Read the retained source context
English original, selected lines 907-919. Excerpt only; continue in the linked complete file.
How do I modify a string in place?
----------------------------------
You can't, because strings are immutable. In most situations, you should
simply construct a new string from the various parts you want to assemble
it from. However, if you need an object with the ability to modify in-place
Unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
module::
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
How do I use strings to call functions/methods?
Source occurrences: 1 / Link to question
[2] programming.rst L939-939Read the retained source context
English original, selected lines 939-951. Excerpt only; continue in the linked complete file.
How do I use strings to call functions/methods?
-----------------------------------------------
There are various techniques.
* The best is to use a dictionary that maps strings to functions. The primary
advantage of this technique is that the strings do not need to match the names
of the functions. This is also the primary technique used to emulate a case
construct::
def a():
pass
Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?
Source occurrences: 1 / Link to question
[2] programming.rst L991-991Read the retained source context
English original, selected lines 991-1003. Excerpt only; continue in the linked complete file.
Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?
-----------------------------------------------------------------------------------------
You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
terminator from the end of the string ``S`` without removing other trailing
whitespace. If the string ``S`` represents more than one line, with several
empty lines at the end, the line terminators for all the blank lines will
be removed::
>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")Is there a ``scanf()`` or ``sscanf()`` equivalent?
Source occurrences: 1 / Link to question
[2] programming.rst L1010-1010Read the retained source context
English original, selected lines 1010-1022. Excerpt only; continue in the linked complete file.
Is there a ``scanf()`` or ``sscanf()`` equivalent?
--------------------------------------------------
Not as such.
For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the :meth:`~str.split` method of string objects
and then convert decimal strings to numeric values using :func:`int` or
:func:`float`. :meth:`!split` supports an optional "sep" parameter which is useful
if the line uses something other than whitespace as a separator.
For more complicated input parsing, regular expressions are more powerful
than C's ``sscanf`` and better suited for the task.
What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?
Source occurrences: 1 / Link to question
[2] programming.rst L1025-1025Read the retained source context
English original, selected lines 1025-1037. Excerpt only; continue in the linked complete file.
What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?
----------------------------------------------------------------------
See the :ref:`unicode-howto`.
.. _faq-programming-raw-string-backslash:
Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------
A raw string ending with an odd number of backslashes will escape the string's quote::
Can I end a raw string with an odd number of backslashes?
Source occurrences: 1 / Link to question
[2] programming.rst L1033-1033Read the retained source context
English original, selected lines 1033-1045. Excerpt only; continue in the linked complete file.
Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------
A raw string ending with an odd number of backslashes will escape the string's quote::
>>> r'C:\this\will\not\work\'
File "<stdin>", line 1
r'C:\this\will\not\work\'
^
SyntaxError: unterminated string literal (detected at line 1)
There are several workarounds for this. One is to use regular strings and double
the backslashes::My program is too slow. How do I speed it up?
Source occurrences: 1 / Link to question
[2] programming.rst L1075-1075Read the retained source context
English original, selected lines 1075-1087. Excerpt only; continue in the linked complete file.
My program is too slow. How do I speed it up?
---------------------------------------------
That's a tough one, in general. First, here is a list of things to
remember before diving further:
* Performance characteristics vary across Python implementations. This FAQ
focuses on :term:`CPython`.
* Behaviour can vary across operating systems, especially when talking about
I/O or multi-threading.
* You should always find the hot spots in your program *before* attempting to
optimize any code (see the :mod:`profile` module).
* Writing benchmark scripts will allow you to iterate quickly when searching
What is the most efficient way to concatenate many strings together?
Source occurrences: 1 / Link to question
[2] programming.rst L1134-1134Read the retained source context
English original, selected lines 1134-1146. Excerpt only; continue in the linked complete file.
What is the most efficient way to concatenate many strings together?
--------------------------------------------------------------------
:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
many strings together is inefficient as each concatenation creates a new
object. In the general case, the total runtime cost is quadratic in the
total string length. See :ref:`time-complexity` for more information.
To accumulate many :class:`str` objects, the recommended idiom is to place
them into a list and call :meth:`str.join` at the end::
chunks = []
for s in my_strings:
How do I convert between tuples and lists?
Source occurrences: 1 / Link to question
[2] programming.rst L1163-1163Read the retained source context
English original, selected lines 1163-1175. Excerpt only; continue in the linked complete file.
How do I convert between tuples and lists?
------------------------------------------
The type constructor ``tuple(seq)`` converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.
For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
but returns the same object, so it is cheap to call :func:`tuple` when you
aren't sure that an object is already a tuple.
The type constructor ``list(seq)`` converts any sequence or iterable into a list
with the same items in the same order. For example, ``list((1, 2, 3))`` yieldsWhat's a negative index?
Source occurrences: 1 / Link to question
[2] programming.rst L1180-1180Read the retained source context
English original, selected lines 1180-1192. Excerpt only; continue in the linked complete file.
What's a negative index?
------------------------
Python sequences are indexed with positive numbers and negative numbers. For
positive numbers 0 is the first index 1 is the second index and so forth. For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
Using negative indices can be very convenient. For example ``S[:-1]`` is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.
How do I iterate over a sequence in reverse order?
Source occurrences: 1 / Link to question
[2] programming.rst L1193-1193Read the retained source context
English original, selected lines 1193-1205. Excerpt only; continue in the linked complete file.
How do I iterate over a sequence in reverse order?
--------------------------------------------------
Use the :func:`reversed` built-in function::
for x in reversed(sequence):
... # do something with x ...
This returns a reverse iterator without modifying your original sequence.
How do you remove duplicates from a list?
-----------------------------------------How do you remove duplicates from a list?
Source occurrences: 1 / Link to question
[2] programming.rst L1204-1204Read the retained source context
English original, selected lines 1204-1216. Excerpt only; continue in the linked complete file.
How do you remove duplicates from a list?
-----------------------------------------
See the Python Cookbook for a long discussion of many ways to do this:
https://code.activestate.com/recipes/52560/
If you don't mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go::
if mylist:
mylist.sort()
last = mylist[-1]How do you remove multiple items from a list?
Source occurrences: 1 / Link to question
[2] programming.rst L1232-1232Read the retained source context
English original, selected lines 1232-1244. Excerpt only; continue in the linked complete file.
How do you remove multiple items from a list?
---------------------------------------------
As with removing duplicates, explicitly iterating in reverse with a
delete condition is one possibility. However, it is easier and faster
to use slice replacement with an implicit or explicit forward iteration.
Here are three variations::
mylist[:] = filter(keep_function, mylist)
mylist[:] = (x for x in mylist if keep_condition)
mylist[:] = [x for x in mylist if keep_condition]
The list comprehension may be fastest.
How do you make an array in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L1247-1247Read the retained source context
English original, selected lines 1247-1259. Excerpt only; continue in the linked complete file.
How do you make an array in Python?
-----------------------------------
Use a list::
["this", 1, "is", "an", "array"]
Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.
The ``array`` module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists. Also
note that `NumPy <https://numpy.org/>`_
How do I create a multidimensional list?
Source occurrences: 1 / Link to question
[2] programming.rst L1275-1275Read the retained source context
English original, selected lines 1275-1287. Excerpt only; continue in the linked complete file.
How do I create a multidimensional list?
----------------------------------------
You probably tried to make a multidimensional array like this::
>>> A = [[None] * 2] * 3
This looks correct if you print it:
.. testsetup::
A = [[None] * 2] * 3
How do I apply a method or function to a sequence of objects?
Source occurrences: 1 / Link to question
[2] programming.rst L1327-1327Read the retained source context
English original, selected lines 1327-1339. Excerpt only; continue in the linked complete file.
How do I apply a method or function to a sequence of objects?
-------------------------------------------------------------
To call a method or function and accumulate the return values in a list,
a :term:`list comprehension` is an elegant solution::
result = [obj.method() for obj in mylist]
result = [function(obj) for obj in mylist]
To just run the method or function without saving the return values,
a plain :keyword:`for` loop will suffice::
Why does a_tuple[i] += ['item'] raise an exception when the addition works?
Source occurrences: 1 / Link to question
[2] programming.rst L1349-1349Read the retained source context
English original, selected lines 1349-1361. Excerpt only; continue in the linked complete file.
Why does a_tuple[i] += ['item'] raise an exception when the addition works?
---------------------------------------------------------------------------
This is because of a combination of the fact that augmented assignment
operators are *assignment* operators, and the difference between mutable and
immutable objects in Python.
This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we'll use
a ``list`` and ``+=`` as our exemplar.
If you wrote::
I want to do a complicated sort: can you do a Schwartzian Transform in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L1436-1436Read the retained source context
English original, selected lines 1436-1448. Excerpt only; continue in the linked complete file.
I want to do a complicated sort: can you do a Schwartzian Transform in Python?
------------------------------------------------------------------------------
The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its "sort value". In
Python, use the ``key`` argument for the :meth:`list.sort` method::
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
How can I sort one list by values from another list?
----------------------------------------------------
How can I sort one list by values from another list?
Source occurrences: 1 / Link to question
[2] programming.rst L1447-1447Read the retained source context
English original, selected lines 1447-1459. Excerpt only; continue in the linked complete file.
How can I sort one list by values from another list?
----------------------------------------------------
Merge them into an iterator of tuples, sort the resulting list, and then pick
out the element you want.
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]What is a class?
Source occurrences: 1 / Link to question
[2] programming.rst L1467-1467Read the retained source context
English original, selected lines 1467-1479. Excerpt only; continue in the linked complete file.
What is a class?
----------------
A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.
A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance. You might have a
generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
that handle various specific mailbox formats.
What is a method?
Source occurrences: 1 / Link to question
[2] programming.rst L1482-1482Read the retained source context
English original, selected lines 1482-1494. Excerpt only; continue in the linked complete file.
What is a method?
-----------------
A method is a function on some object ``x`` that you normally call as
``x.name(arguments...)``. Methods are defined as functions inside the class
definition::
class C:
def meth(self, arg):
return arg * 2 + self.attribute
What is self?What is self?
Source occurrences: 1 / Link to question
[2] programming.rst L1494-1494Read the retained source context
English original, selected lines 1494-1506. Excerpt only; continue in the linked complete file.
What is self?
-------------
Self is merely a conventional name for the first argument of a method. A method
defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
some instance ``x`` of the class in which the definition occurs; the called
method will think it is called as ``meth(x, a, b, c)``.
See also :ref:`why-self`.
How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------
How do I check if an object is an instance of a given class or of a subclass of it?
Source occurrences: 1 / Link to question
[2] programming.rst L1505-1505Read the retained source context
English original, selected lines 1505-1517. Excerpt only; continue in the linked complete file.
How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------
Use the built-in function :func:`isinstance(obj, cls) <isinstance>`. You can
check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, for example, ``isinstance(obj, (class1, class2, ...))``, and can also
check whether an object is one of Python's built-in types, for example,
``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Note that :func:`isinstance` also checks for virtual inheritance from an
:term:`abstract base class`. So, the test will return ``True`` for a
registered class even if hasn't directly or indirectly inherited from it. To
What is delegation?
Source occurrences: 1 / Link to question
[2] programming.rst L1579-1579Read the retained source context
English original, selected lines 1579-1591. Excerpt only; continue in the linked complete file.
What is delegation?
-------------------
Delegation is an object-oriented technique (also called a design pattern).
Let's say you have an object ``x`` and want to change the behaviour of just one
of its methods. You can create a new class that provides a new implementation
of the method you're interested in changing and delegates all other methods to
the corresponding method of ``x``.
Python programmers can easily implement delegation. For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase::
How do I call a method defined in a base class from a derived class that extends it?
Source occurrences: 1 / Link to question
[2] programming.rst L1633-1633Read the retained source context
English original, selected lines 1633-1645. Excerpt only; continue in the linked complete file.
How do I call a method defined in a base class from a derived class that extends it?
------------------------------------------------------------------------------------
Use the built-in :func:`super` function::
class Derived(Base):
def meth(self):
super().meth() # calls Base.meth
In the example, :func:`super` will automatically determine the instance from
which it was called (the ``self`` value), look up the :term:`method resolution
order` (MRO) with ``type(self).__mro__``, and return a proxy that searches for
methods starting with the next class after ``Derived`` in the MRO: ``Base``.How can I organize my code to make it easier to change the base class?
Source occurrences: 1 / Link to question
[2] programming.rst L1648-1648Read the retained source context
English original, selected lines 1648-1660. Excerpt only; continue in the linked complete file.
How can I organize my code to make it easier to change the base class?
----------------------------------------------------------------------
You could assign the base class to an alias and derive from the alias. Then all
you have to change is the value assigned to the alias. Incidentally, this trick
is also handy if you want to decide dynamically (such as depending on availability
of resources) which base class to use. Example::
class Base:
...
BaseAlias = Base
How do I create static class data and static class methods?
Source occurrences: 1 / Link to question
[2] programming.rst L1665-1665Read the retained source context
English original, selected lines 1665-1677. Excerpt only; continue in the linked complete file.
How do I create static class data and static class methods?
-----------------------------------------------------------
Both static data and static methods (in the sense of C++ or Java) are supported
in Python.
For static data, simply define a class attribute. To assign a new value to the
attribute, you have to explicitly use the class name in the assignment::
class C:
count = 0 # number of times C.__init__ called
def __init__(self):How can I overload constructors (or methods) in Python?
Source occurrences: 1 / Link to question
[2] programming.rst L1712-1712Read the retained source context
English original, selected lines 1712-1724. Excerpt only; continue in the linked complete file.
How can I overload constructors (or methods) in Python?
-------------------------------------------------------
This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.
In C++ you'd write:
.. code-block:: c++
class C {
C() { cout << "No arguments\n"; }
C(int i) { cout << "Argument is " << i << "\n"; }How do I get a list of all instances of a given class?
Source occurrences: 1 / Link to question
[2] programming.rst L1827-1827Read the retained source context
English original, selected lines 1827-1839. Excerpt only; continue in the linked complete file.
How do I get a list of all instances of a given class?
------------------------------------------------------
Python does not keep track of all instances of a class (or of a built-in type).
You can program the class's constructor to keep track of all instances by
keeping a list of weak references to each instance.
Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------
The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object. Since in CPython, this is the object's memory
Why does the result of ``id()`` appear to be not unique?
Source occurrences: 1 / Link to question
[2] programming.rst L1835-1835Read the retained source context
English original, selected lines 1835-1847. Excerpt only; continue in the linked complete file.
Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------
The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object. Since in CPython, this is the object's memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory. This
is illustrated by this example:
>>> id(1000) # doctest: +SKIP
13901272
>>> id(2000) # doctest: +SKIP
13901272
When can I rely on identity tests with the *is* operator?
Source occurrences: 1 / Link to question
[2] programming.rst L1863-1863Read the retained source context
English original, selected lines 1863-1875. Excerpt only; continue in the linked complete file.
When can I rely on identity tests with the *is* operator?
---------------------------------------------------------
The ``is`` operator tests for object identity. The test ``a is b`` is
equivalent to ``id(a) == id(b)``.
The most important property of an identity test is that an object is always
identical to itself, ``a is a`` always returns ``True``. Identity tests are
usually faster than equality tests. And unlike equality tests, identity tests
are guaranteed to return a boolean ``True`` or ``False``.
However, identity tests can *only* be substituted for equality tests when
object identity is assured. Generally, there are three circumstances where
How can a subclass control what data is stored in an immutable instance?
Source occurrences: 1 / Link to question
[2] programming.rst L1952-1952Read the retained source context
English original, selected lines 1952-1964. Excerpt only; continue in the linked complete file.
How can a subclass control what data is stored in an immutable instance?
------------------------------------------------------------------------
When subclassing an immutable type, override the :meth:`~object.__new__` method
instead of the :meth:`~object.__init__` method. The latter only runs *after* an
instance is created, which is too late to alter data in an immutable
instance.
All of these immutable classes have a different signature than their
parent class:
.. testcode::
How do I cache method calls?
Source occurrences: 1 / Link to question
[2] programming.rst L2002-2002Read the retained source context
English original, selected lines 2002-2014. Excerpt only; continue in the linked complete file.
How do I cache method calls?
----------------------------
The two principal tools for caching methods are
:deco:`functools.cached_property` and :deco:`functools.lru_cache`. The
former stores results at the instance level and the latter at the class
level.
The ``cached_property`` approach only works with methods that do not take
any arguments. It does not create a reference to the instance. The
cached method result will be kept only as long as the instance is alive.
The advantage is that when an instance is no longer used, the cached
How do I create a .pyc file?
Source occurrences: 1 / Link to question
[2] programming.rst L2061-2061Read the retained source context
English original, selected lines 2061-2073. Excerpt only; continue in the linked complete file.
How do I create a .pyc file?
----------------------------
When a module is imported for the first time (or when the source file has
changed since the current compiled file was created) a ``.pyc`` file containing
the compiled code should be created in a ``__pycache__`` subdirectory of the
directory containing the ``.py`` file. The ``.pyc`` file will have a
filename that starts with the same name as the ``.py`` file, and ends with
``.pyc``, with a middle component that depends on the particular ``python``
binary that created it. (See :pep:`3147` for details.)
One reason that a ``.pyc`` file may not be created is a permissions problem
with the directory containing the source file, meaning that the ``__pycache__``
How do I find the current module name?
Source occurrences: 1 / Link to question
[2] programming.rst L2111-2111Read the retained source context
English original, selected lines 2111-2123. Excerpt only; continue in the linked complete file.
How do I find the current module name?
--------------------------------------
A module can find out its own module name by looking at the predefined global
variable ``__name__``. If this has the value ``'__main__'``, the program is
running as a script. Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking ``__name__``::
def main():
print('Running test...')
...
How can I have modules that mutually import each other?
Source occurrences: 1 / Link to question
[2] programming.rst L2128-2128Read the retained source context
English original, selected lines 2128-2140. Excerpt only; continue in the linked complete file.
How can I have modules that mutually import each other?
-------------------------------------------------------
Suppose you have the following modules:
:file:`foo.py`::
from bar import bar_var
foo_var = 1
:file:`bar.py`::
from foo import foo_var
__import__('x.y.z') returns <module 'x'>; how do I get z?
Source occurrences: 1 / Link to question
[2] programming.rst L2183-2183Read the retained source context
English original, selected lines 2183-2195. Excerpt only; continue in the linked complete file.
__import__('x.y.z') returns <module 'x'>; how do I get z?
---------------------------------------------------------
Consider using the convenience function :func:`~importlib.import_module` from
:mod:`importlib` instead::
z = importlib.import_module('x.y.z')
When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
-------------------------------------------------------------------------------------------------
For reasons of efficiency as well as consistency, Python only reads the moduleWhen I edit an imported module and reimport it, the changes don't show up. Why does this happen?
Source occurrences: 1 / Link to question
[2] programming.rst L2192-2192Read the retained source context
English original, selected lines 2192-2204. Excerpt only; continue in the linked complete file.
When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
-------------------------------------------------------------------------------------------------
For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported. If it didn't, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times. To force re-reading of a
changed module, do this::
import importlib
import modname
importlib.reload(modname)
Design and history / 28 matching questions
Complete retained English RST / PSF License v2
Why does Python use indentation for grouping of statements?
Source occurrences: 1 / Link to question
[3] design.rst L11-11Read the retained source context
English original, selected lines 11-23. Excerpt only; continue in the linked complete file.
Why does Python use indentation for grouping of statements?
-----------------------------------------------------------
Guido van Rossum believes that using indentation for grouping is extremely
elegant and contributes a lot to the clarity of the average Python program.
Most people learn to love this feature after a while.
Since there are no begin/end brackets there cannot be a disagreement between
grouping perceived by the parser and the human reader. Occasionally C
programmers will encounter a fragment of code like this::
if (x <= y)
x++;Why am I getting strange results with simple arithmetic operations?
Source occurrences: 1 / Link to question
[3] design.rst L48-48Read the retained source context
English original, selected lines 48-60. Excerpt only; continue in the linked complete file.
Why am I getting strange results with simple arithmetic operations?
-------------------------------------------------------------------
See the next question.
Why are floating-point calculations so inaccurate?
--------------------------------------------------
Users are often surprised by results like this::
>>> 1.2 - 1.0
0.19999999999999996Why are floating-point calculations so inaccurate?
Source occurrences: 1 / Link to question
[3] design.rst L54-54Read the retained source context
English original, selected lines 54-66. Excerpt only; continue in the linked complete file.
Why are floating-point calculations so inaccurate?
--------------------------------------------------
Users are often surprised by results like this::
>>> 1.2 - 1.0
0.19999999999999996
and think it is a bug in Python. It's not. This has little to do with Python,
and much more to do with how the underlying platform handles floating-point
numbers.
The :class:`float` type in CPython uses a C ``double`` for storage. AWhy are Python strings immutable?
Source occurrences: 1 / Link to question
[3] design.rst L95-95Read the retained source context
English original, selected lines 95-107. Excerpt only; continue in the linked complete file.
Why are Python strings immutable?
---------------------------------
There are several advantages.
One is performance: knowing that a string is immutable means we can allocate
space for it at creation time, and the storage requirements are fixed and
unchanging. This is also one of the reasons for the distinction between tuples
and lists.
Another advantage is that strings in Python are considered as "elemental" as
numbers. No amount of activity will change the value 8 to anything else, and in
Python, no amount of activity will change the string "eight" to anything else.
Why must 'self' be used explicitly in method definitions and calls?
Source occurrences: 1 / Link to question
[3] design.rst L112-112Read the retained source context
English original, selected lines 112-124. Excerpt only; continue in the linked complete file.
Why must 'self' be used explicitly in method definitions and calls?
-------------------------------------------------------------------
The idea was borrowed from Modula-3. It turns out to be very useful, for a
variety of reasons.
First, it's more obvious that you are using a method or instance attribute
instead of a local variable. Reading ``self.x`` or ``self.meth()`` makes it
absolutely clear that an instance variable or method is used even if you don't
know the class definition by heart. In C++, you can sort of tell by the lack of
a local variable declaration (assuming globals are rare or easily recognizable)
-- but in Python, there are no local variable declarations, so you'd have to
look up the class definition to be sure. Some C++ and Java coding standards
Why can't I use an assignment in an expression?
Source occurrences: 1 / Link to question
[3] design.rst L154-154Read the retained source context
English original, selected lines 154-166. Excerpt only; continue in the linked complete file.
Why can't I use an assignment in an expression?
-----------------------------------------------
Starting in Python 3.8, you can!
Assignment expressions using the walrus operator ``:=`` assign a variable in an
expression::
while chunk := fp.read(200):
print(chunk)
See :pep:`572` for more information.
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
Source occurrences: 1 / Link to question
[3] design.rst L169-169Read the retained source context
English original, selected lines 169-181. Excerpt only; continue in the linked complete file.
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
----------------------------------------------------------------------------------------------------------------
As Guido said:
(a) For some operations, prefix notation just reads better than
postfix -- prefix (and infix!) operations have a long tradition in
mathematics which likes notations where the visuals help the
mathematician thinking about a problem. Compare the easy with which we
rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I *know* that it is asking forWhy is join() a string method instead of a list or tuple method?
Source occurrences: 1 / Link to question
[3] design.rst L193-193Read the retained source context
English original, selected lines 193-205. Excerpt only; continue in the linked complete file.
Why is join() a string method instead of a list or tuple method?
----------------------------------------------------------------
Strings became much more like other standard types starting in Python 1.6, when
methods were added which give the same functionality that has always been
available using the functions of the string module. Most of these new methods
have been widely accepted, but the one which appears to make some programmers
feel uncomfortable is::
", ".join(['1', '2', '4', '8', '16'])
which gives the result::
How fast are exceptions?
Source occurrences: 1 / Link to question
[3] design.rst L233-233Read the retained source context
English original, selected lines 233-245. Excerpt only; continue in the linked complete file.
How fast are exceptions?
------------------------
A :keyword:`try`/:keyword:`except` block is extremely efficient if no exceptions
are raised. Actually
catching an exception is expensive. In versions of Python prior to 2.0 it was
common to use this idiom::
try:
value = mydict[key]
except KeyError:
mydict[key] = getvalue(key)
value = mydict[key]Why isn't there a switch or case statement in Python?
Source occurrences: 1 / Link to question
[3] design.rst L260-260Read the retained source context
English original, selected lines 260-272. Excerpt only; continue in the linked complete file.
Why isn't there a switch or case statement in Python?
-----------------------------------------------------
In general, structured switch statements execute one block of code
when an expression has a particular value or set of values.
Since Python 3.10 one can easily match literal values, or constants
within a namespace, with a ``match ... case`` statement.
See :ref:`the specification <match>` and :ref:`the tutorial <tut-match>`
for more information about :keyword:`match` statements.
An older alternative is a sequence of ``if... elif... elif... else``.
For cases where you need to choose from a very large number of possibilities,
you can create a dictionary mapping case values to functions to call. For
Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
Source occurrences: 1 / Link to question
[3] design.rst L302-302Read the retained source context
English original, selected lines 302-314. Excerpt only; continue in the linked complete file.
Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
--------------------------------------------------------------------------------------------------------
Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for
each Python stack frame. Also, extensions can call back into Python at almost
random moments. Therefore, a complete threads implementation requires thread
support for C.
Answer 2: Fortunately, there is `Stackless Python <https://github.com/stackless-dev/stackless/wiki>`_,
which has a completely redesigned interpreter loop that avoids the C stack.
Why can't lambda expressions contain statements?
Why can't lambda expressions contain statements?
Source occurrences: 1 / Link to question
[3] design.rst L314-314Read the retained source context
English original, selected lines 314-326. Excerpt only; continue in the linked complete file.
Why can't lambda expressions contain statements?
------------------------------------------------
Python lambda expressions cannot contain statements because Python's syntactic
framework can't handle statements nested inside expressions. However, in
Python, this is not a serious problem. Unlike lambda forms in other languages,
where they add functionality, Python lambdas are only a shorthand notation if
you're too lazy to define a function.
Functions are already first class objects in Python, and can be declared in a
local scope. Therefore the only advantage of using a lambda instead of a
locally defined function is that you don't need to invent a name for the
function -- but that's just a local variable to which the function object (which
Can Python be compiled to machine code, C or some other language?
Source occurrences: 1 / Link to question
[3] design.rst L330-330Read the retained source context
English original, selected lines 330-342. Excerpt only; continue in the linked complete file.
Can Python be compiled to machine code, C or some other language?
-----------------------------------------------------------------
`Cython <https://cython.org/>`_ compiles a modified version of Python with
optional annotations into C extensions. `Nuitka <https://nuitka.net/>`_ is
an up-and-coming compiler of Python into C++ code, aiming to support the full
Python language.
How does Python manage memory?
------------------------------
The details of Python memory management depend on the implementation. The
How does Python manage memory?
Source occurrences: 1 / Link to question
[3] design.rst L339-339Read the retained source context
English original, selected lines 339-351. Excerpt only; continue in the linked complete file.
How does Python manage memory?
------------------------------
The details of Python memory management depend on the implementation. The
standard implementation of Python, :term:`CPython`, uses reference counting to
detect inaccessible objects, and another mechanism to collect reference cycles,
periodically executing a cycle detection algorithm which looks for inaccessible
cycles and deletes the objects involved. The :mod:`gc` module provides functions
to perform a garbage collection, obtain debugging statistics, and tune the
collector's parameters.
Other implementations (such as `Jython <https://www.jython.org>`_ or
`PyPy <https://pypy.org>`_), however, can rely on a different mechanism
Why doesn't CPython use a more traditional garbage collection scheme?
Source occurrences: 1 / Link to question
[3] design.rst L377-377Read the retained source context
English original, selected lines 377-389. Excerpt only; continue in the linked complete file.
Why doesn't CPython use a more traditional garbage collection scheme?
---------------------------------------------------------------------
For one thing, this is not a C standard feature and hence it's not portable.
(Yes, we know about the Boehm GC library. It has bits of assembler code for
*most* common platforms, not for all of them, and although it is mostly
transparent, it isn't completely transparent; patches are required to get
Python to work with it.)
Traditional GC also becomes a problem when Python is embedded into other
applications. While in a standalone Python it's fine to replace the standard
``malloc()`` and ``free()`` with versions provided by the GC library, an application
embedding Python may want to have its *own* substitute for ``malloc()`` and ``free()``,
Why isn't all memory freed when CPython exits?
Source occurrences: 1 / Link to question
[3] design.rst L394-394Read the retained source context
English original, selected lines 394-406. Excerpt only; continue in the linked complete file.
Why isn't all memory freed when CPython exits?
----------------------------------------------
Objects referenced from the global namespaces of Python modules are not always
deallocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C
library that are impossible to free (e.g. a tool like Purify will complain about
these). Python is, however, aggressive about cleaning up memory on exit and
does try to destroy every single object.
If you want to force Python to delete certain things when Python exits, use the
:mod:`atexit` module to run a function that will force those deletions.
Why are there separate tuple and list data types?
Source occurrences: 1 / Link to question
[3] design.rst L408-408Read the retained source context
English original, selected lines 408-420. Excerpt only; continue in the linked complete file.
Why are there separate tuple and list data types?
-------------------------------------------------
Lists and tuples, while similar in many respects, are generally used in
fundamentally different ways. Tuples can be thought of as being similar to
Pascal ``records`` or C ``structs``; they're small collections of related data which may
be of different types which are operated on as a group. For example, a
Cartesian coordinate is appropriately represented as a tuple of two or three
numbers.
Lists, on the other hand, are more like arrays in other languages. They tend to
hold a varying number of objects all of which have the same type and which are
operated on one-by-one. For example, :func:`os.listdir('.') <os.listdir>`How are lists implemented in CPython?
Source occurrences: 1 / Link to question
[3] design.rst L434-434Read the retained source context
English original, selected lines 434-446. Excerpt only; continue in the linked complete file.
How are lists implemented in CPython?
-------------------------------------
CPython's lists are really variable-length arrays, not Lisp-style linked lists.
The implementation uses a contiguous array of references to other objects, and
keeps a pointer to this array and the array's length in a list head structure.
This makes indexing a list ``a[i]`` an operation whose cost is independent of
the size of the list or the value of the index.
When items are appended or inserted, the array of references is resized. Some
cleverness is applied to improve the performance of appending items repeatedly;
when the array must be grown, some extra space is allocated so the next few
How are dictionaries implemented in CPython?
Source occurrences: 1 / Link to question
[3] design.rst L454-454Read the retained source context
English original, selected lines 454-466. Excerpt only; continue in the linked complete file.
How are dictionaries implemented in CPython?
--------------------------------------------
CPython's dictionaries are implemented as resizable hash tables. Compared to
B-trees, this gives better performance for lookup (the most common operation by
far) under most circumstances, and the implementation is simpler.
Dictionaries work by computing a hash code for each key stored in the dictionary
using the :func:`hash` built-in function. The hash code varies widely depending
on the key and a per-process seed; for example, ``'Python'`` could hash to
``-539294296`` while ``'python'``, a string that differs by a single bit, could hash
to ``1142331976``. The hash code is then used to calculate a location in an
internal array where the value will be stored. Assuming that you're storing
Why must dictionary keys be immutable?
Source occurrences: 1 / Link to question
[3] design.rst L473-473Read the retained source context
English original, selected lines 473-485. Excerpt only; continue in the linked complete file.
Why must dictionary keys be immutable?
--------------------------------------
The hash table implementation of dictionaries uses a hash value calculated from
the key value to find the key. If the key were a mutable object, its value
could change, and thus its hash could also change. But since whoever changes
the key object can't tell that it was being used as a dictionary key, it can't
move the entry around in the dictionary. Then, when you try to look up the same
object in the dictionary it won't be found because its hash value is different.
If you tried to look up the old value it wouldn't be found either, because the
value of the object found in that hash bin would be different.
If you want a dictionary indexed with a list, simply convert the list to a tuple
Why doesn't list.sort() return the sorted list?
Source occurrences: 1 / Link to question
[3] design.rst L556-556Read the retained source context
English original, selected lines 556-568. Excerpt only; continue in the linked complete file.
Why doesn't list.sort() return the sorted list?
-----------------------------------------------
In situations where performance matters, making a copy of the list just to sort
it would be wasteful. Therefore, :meth:`list.sort` sorts the list in place. In
order to remind you of that fact, it does not return the sorted list. This way,
you won't be fooled into accidentally overwriting a list when you need a sorted
copy but also need to keep the unsorted version around.
If you want to return a new list, use the built-in :func:`sorted` function
instead. This function creates a new list from a provided iterable, sorts
it and returns it. For example, here's how to iterate over the keys of a
dictionary in sorted order::
How do you specify and enforce an interface spec in Python?
Source occurrences: 1 / Link to question
[3] design.rst L574-574Read the retained source context
English original, selected lines 574-586. Excerpt only; continue in the linked complete file.
How do you specify and enforce an interface spec in Python?
-----------------------------------------------------------
An interface specification for a module as provided by languages such as C++ and
Java describes the prototypes for the methods and functions of the module. Many
feel that compile-time enforcement of interface specifications helps in the
construction of large programs.
Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes
(ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check
whether an instance or a class implements a particular ABC. The
:mod:`collections.abc` module defines a set of useful ABCs such as
:class:`~collections.abc.Iterable`, :class:`~collections.abc.Container`, and
Why is there no goto?
Source occurrences: 1 / Link to question
[3] design.rst L615-615Read the retained source context
English original, selected lines 615-627. Excerpt only; continue in the linked complete file.
Why is there no goto?
---------------------
In the 1970s people realized that unrestricted goto could lead
to messy "spaghetti" code that was hard to understand and revise.
In a high-level language, it is also unneeded as long as there
are ways to branch (in Python, with :keyword:`if` statements and :keyword:`or`,
:keyword:`and`, and :keyword:`if`/:keyword:`else` expressions) and loop (with :keyword:`while`
and :keyword:`for` statements, possibly containing :keyword:`continue` and :keyword:`break`).
One can also use exceptions to provide a "structured goto"
that works even across
function calls. Many feel that exceptions can conveniently emulate all
Why can't raw strings (r-strings) end with a backslash?
Source occurrences: 1 / Link to question
[3] design.rst L645-645Read the retained source context
English original, selected lines 645-657. Excerpt only; continue in the linked complete file.
Why can't raw strings (r-strings) end with a backslash?
-------------------------------------------------------
More precisely, they can't end with an odd number of backslashes: the unpaired
backslash at the end escapes the closing quote character, leaving an
unterminated string.
Raw strings were designed to ease creating input for processors (chiefly regular
expression engines) that want to do their own backslash escape processing. Such
processors consider an unmatched trailing backslash to be an error anyway, so
raw strings disallow that. In return, they allow you to pass on the string
quote character by escaping it with a backslash. These rules work well when
r-strings are used for their intended purpose.
Why doesn't Python have a "with" statement for attribute assignments?
Source occurrences: 1 / Link to question
[3] design.rst L671-671Read the retained source context
English original, selected lines 671-683. Excerpt only; continue in the linked complete file.
Why doesn't Python have a "with" statement for attribute assignments?
---------------------------------------------------------------------
Python has a :keyword:`with` statement that wraps the execution of a block, calling code
on the entrance and exit from the block. Some languages have a construct that
looks like this::
with obj:
a = 1 # equivalent to obj.a = 1
total = total + 1 # obj.total = obj.total + 1
In Python, such a construct would be ambiguous.
Why don't generators support the with statement?
Source occurrences: 1 / Link to question
[3] design.rst L730-730Read the retained source context
English original, selected lines 730-742. Excerpt only; continue in the linked complete file.
Why don't generators support the with statement?
------------------------------------------------
For technical reasons, a generator used directly as a context manager
would not work correctly. When, as is most common, a generator is used as
an iterator run to completion, no closing is needed. When it is, wrap
it as :func:`contextlib.closing(generator) <contextlib.closing>`
in the :keyword:`with` statement.
Why are colons required for the if/while/def/class statements?
--------------------------------------------------------------
Why are colons required for the if/while/def/class statements?
Source occurrences: 1 / Link to question
[3] design.rst L740-740Read the retained source context
English original, selected lines 740-752. Excerpt only; continue in the linked complete file.
Why are colons required for the if/while/def/class statements?
--------------------------------------------------------------
The colon is required primarily to enhance readability (one of the results of
the experimental ABC language). Consider this::
if a == b
print(a)
versus ::
if a == b:
print(a)Why does Python allow commas at the end of lists and tuples?
Source occurrences: 1 / Link to question
[3] design.rst L762-762Read the retained source context
English original, selected lines 762-774. Excerpt only; continue in the linked complete file.
Why does Python allow commas at the end of lists and tuples?
------------------------------------------------------------
Python lets you add a trailing comma at the end of lists, tuples, and
dictionaries::
[1, 2, 3,]
('a', 'b', 'c',)
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}