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?
Why am I getting strange results with simple arithmetic operations?
-------------------------------------------------------------------
See the next question.
Why are floating-point calculations so inaccurate?
--------------------------------------------------
Users are often surprised by results like this::
>>> 1.2 - 1.0
0.19999999999999996
Why are floating-point calculations so inaccurate?
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. A
영어 원문 발췌, 줄 95-107. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 112-124. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 154-166. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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))?
영어 원문 발췌, 줄 169-181. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
----------------------------------------------------------------------------------------------------------------
As Guido said:
(a) For some operations, prefix notation just reads better than
postfix -- prefix (and infix!) operations have a long tradition in
mathematics which likes notations where the visuals help the
mathematician thinking about a problem. Compare the easy with which we
rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I *know* that it is asking for
Why is join() a string method instead of a list or tuple method?
영어 원문 발췌, 줄 193-205. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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::
영어 원문 발췌, 줄 233-245. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 260-272. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 302-314. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 314-326. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 330-342. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 339-351. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 377-389. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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()``,
영어 원문 발췌, 줄 394-406. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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.
영어 원문 발췌, 줄 408-420. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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>`
영어 원문 발췌, 줄 434-446. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 454-466. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 473-485. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 556-568. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 574-586. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
영어 원문 발췌, 줄 615-627. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 645-657. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 671-683. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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.
영어 원문 발췌, 줄 730-742. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 740-752. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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?
영어 원문 발췌, 줄 762-774. 일부 발췌입니다. 연결된 전체 파일에서 이어 읽으세요.
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
}