# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.15\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-09-14 20:17+0000\n" "PO-Revision-Date: 2025-09-16 00:00+0000\n" "Last-Translator: python-doc bot, 2025\n" "Language-Team: German (https://app.transifex.com/python-doc/teams/5390/de/)\n" "Language: de\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../../faq/programming.rst:5 msgid "Programming FAQ" msgstr "" #: ../../faq/programming.rst:8 msgid "Contents" msgstr "Inhalt" #: ../../faq/programming.rst:12 msgid "General questions" msgstr "" #: ../../faq/programming.rst:15 msgid "" "Is there a source code-level debugger with breakpoints and single-stepping?" msgstr "" #: ../../faq/programming.rst:17 ../../faq/programming.rst:56 msgid "Yes." msgstr "" #: ../../faq/programming.rst:19 msgid "" "Several debuggers for Python are described below, and the built-in function :" "func:`breakpoint` allows you to drop into any of them." msgstr "" #: ../../faq/programming.rst:22 msgid "" "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 `. You can also write your own debugger by " "using the code for pdb as an example." msgstr "" #: ../../faq/programming.rst:27 msgid "" "The IDLE interactive development environment, which is part of the standard " "Python distribution (normally available as :mod:`idlelib`), includes a " "graphical debugger." msgstr "" #: ../../faq/programming.rst:31 msgid "" "PythonWin is a Python IDE that includes a GUI debugger based on pdb. The " "PythonWin debugger colors breakpoints and has quite a few cool features such " "as debugging non-PythonWin programs. PythonWin is available as part of " "`pywin32 `_ project and as a part of " "the `ActivePython `_ " "distribution." msgstr "" #: ../../faq/programming.rst:38 msgid "" "`Eric `_ is an IDE built on PyQt and " "the Scintilla editing component." msgstr "" #: ../../faq/programming.rst:41 msgid "" "`trepan3k `_ is a gdb-like " "debugger." msgstr "" #: ../../faq/programming.rst:43 msgid "" "`Visual Studio Code `_ is an IDE with " "debugging tools that integrates with version-control software." msgstr "" #: ../../faq/programming.rst:46 msgid "" "There are a number of commercial Python IDEs that include graphical " "debuggers. They include:" msgstr "" #: ../../faq/programming.rst:49 msgid "`Wing IDE `_" msgstr "" #: ../../faq/programming.rst:50 msgid "`PyCharm `_" msgstr "" #: ../../faq/programming.rst:54 msgid "Are there tools to help find bugs or perform static analysis?" msgstr "" #: ../../faq/programming.rst:58 msgid "" "`Ruff `__, `Pylint `__ and `Pyflakes `__ do basic " "checking that will help you catch bugs sooner." msgstr "" #: ../../faq/programming.rst:63 msgid "" "Static type checkers such as `mypy `__, `ty `__, `Pyrefly `__, and `pytype " "`__ can check type hints in Python source " "code." msgstr "" #: ../../faq/programming.rst:73 msgid "How can I create a stand-alone binary from a Python script?" msgstr "" #: ../../faq/programming.rst:75 msgid "" "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." msgstr "" #: ../../faq/programming.rst:81 msgid "" "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 standard Python modules." msgstr "" #: ../../faq/programming.rst:87 msgid "" "It works by scanning your source recursively for import statements (in both " "forms) and looking for the modules in the standard Python path as well as in " "the source directory (for built-in modules). It then turns the bytecode for " "modules written in Python into C code (array initializers that can be turned " "into code objects using the marshal module) and creates a custom-made config " "file that only contains those built-in modules which are actually used in " "the program. It then compiles the generated C code and links it with the " "rest of the Python interpreter to form a self-contained binary which acts " "exactly like your script." msgstr "" #: ../../faq/programming.rst:96 msgid "" "The following packages can help with the creation of console and GUI " "executables:" msgstr "" #: ../../faq/programming.rst:99 msgid "`Nuitka `_ (Cross-platform)" msgstr "" #: ../../faq/programming.rst:100 msgid "`PyInstaller `_ (Cross-platform)" msgstr "" #: ../../faq/programming.rst:101 msgid "" "`PyOxidizer `_ (Cross-platform)" msgstr "" #: ../../faq/programming.rst:102 msgid "" "`cx_Freeze `_ (Cross-platform)" msgstr "" #: ../../faq/programming.rst:103 msgid "`py2app `_ (macOS only)" msgstr "" #: ../../faq/programming.rst:104 msgid "`py2exe `_ (Windows only)" msgstr "" #: ../../faq/programming.rst:108 msgid "Are there coding standards or a style guide for Python programs?" msgstr "" #: ../../faq/programming.rst:110 msgid "" "Yes. The coding style required for standard library modules is documented " "as :pep:`8`." msgstr "" #: ../../faq/programming.rst:115 msgid "Core language" msgstr "" #: ../../faq/programming.rst:120 msgid "Why am I getting an UnboundLocalError when the variable has a value?" msgstr "" #: ../../faq/programming.rst:122 msgid "" "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." msgstr "" #: ../../faq/programming.rst:126 msgid "This code:" msgstr "" #: ../../faq/programming.rst:135 msgid "works, but this code:" msgstr "" #: ../../faq/programming.rst:142 msgid "results in an :exc:`!UnboundLocalError`:" msgstr "" #: ../../faq/programming.rst:149 msgid "" "This is because when you make an assignment to a variable in a scope, that " "variable becomes local to that scope and shadows any similarly named " "variable in the outer scope. Since the last statement in foo assigns a new " "value to ``x``, the compiler recognizes it as a local variable. " "Consequently when the earlier ``print(x)`` attempts to print the " "uninitialized local variable and an error results." msgstr "" #: ../../faq/programming.rst:156 msgid "" "In the example above you can access the outer scope variable by declaring it " "global:" msgstr "" #: ../../faq/programming.rst:168 msgid "" "This explicit declaration is required in order to remind you that (unlike " "the superficially analogous situation with class and instance variables) you " "are actually modifying the value of the variable in the outer scope:" msgstr "" #: ../../faq/programming.rst:175 msgid "" "You can do a similar thing in a nested scope using the :keyword:`nonlocal` " "keyword:" msgstr "" #: ../../faq/programming.rst:193 msgid "What are the rules for local and global variables in Python?" msgstr "" #: ../../faq/programming.rst:195 msgid "" "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." msgstr "" #: ../../faq/programming.rst:199 msgid "" "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`` declaration for identifying side-effects." msgstr "" #: ../../faq/programming.rst:209 msgid "" "Why do lambdas defined in a loop with different values all return the same " "result?" msgstr "" #: ../../faq/programming.rst:211 msgid "" "Assume you use a for loop to define a few different lambdas (or even plain " "functions), for example::" msgstr "" #: ../../faq/programming.rst:214 msgid "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda: x**2)" msgstr "" #: ../../faq/programming.rst:218 msgid "" "This gives you a list that contains 5 lambdas that calculate ``x**2``. You " "might expect that, when called, they would return, respectively, ``0``, " "``1``, ``4``, ``9``, and ``16``. However, when you actually try you will " "see that they all return ``16``::" msgstr "" #: ../../faq/programming.rst:223 msgid "" ">>> squares[2]()\n" "16\n" ">>> squares[4]()\n" "16" msgstr "" #: ../../faq/programming.rst:228 msgid "" "This happens because ``x`` is not local to the lambdas, but is defined in " "the outer scope, and it is accessed when the lambda is called --- not when " "it is defined. At the end of the loop, the value of ``x`` is ``4``, so all " "the functions now return ``4**2``, that is ``16``. You can also verify this " "by changing the value of ``x`` and see how the results of the lambdas " "change::" msgstr "" #: ../../faq/programming.rst:234 msgid "" ">>> x = 8\n" ">>> squares[2]()\n" "64" msgstr "" #: ../../faq/programming.rst:238 msgid "" "In order to avoid this, you need to save the values in variables local to " "the lambdas, so that they don't rely on the value of the global ``x``::" msgstr "" #: ../../faq/programming.rst:241 msgid "" ">>> squares = []\n" ">>> for x in range(5):\n" "... squares.append(lambda n=x: n**2)" msgstr "" #: ../../faq/programming.rst:245 msgid "" "Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed " "when the lambda is defined so that it has the same value that ``x`` had at " "that point in the loop. This means that the value of ``n`` will be ``0`` in " "the first lambda, ``1`` in the second, ``2`` in the third, and so on. " "Therefore each lambda will now return the correct result::" msgstr "" #: ../../faq/programming.rst:251 msgid "" ">>> squares[2]()\n" "4\n" ">>> squares[4]()\n" "16" msgstr "" #: ../../faq/programming.rst:256 msgid "" "Note that this behaviour is not peculiar to lambdas, but applies to regular " "functions too." msgstr "" #: ../../faq/programming.rst:261 msgid "How do I share global variables across modules?" msgstr "" #: ../../faq/programming.rst:263 msgid "" "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:" msgstr "" #: ../../faq/programming.rst:269 msgid "config.py::" msgstr "" #: ../../faq/programming.rst:271 msgid "x = 0 # Default value of the 'x' configuration setting" msgstr "" #: ../../faq/programming.rst:273 msgid "mod.py::" msgstr "" #: ../../faq/programming.rst:275 msgid "" "import config\n" "config.x = 1" msgstr "" #: ../../faq/programming.rst:278 msgid "main.py::" msgstr "" #: ../../faq/programming.rst:280 msgid "" "import config\n" "import mod\n" "print(config.x)" msgstr "" #: ../../faq/programming.rst:284 msgid "" "Note that using a module is also the basis for implementing the singleton " "design pattern, for the same reason." msgstr "" #: ../../faq/programming.rst:289 msgid "What are the \"best practices\" for using import in a module?" msgstr "" #: ../../faq/programming.rst:291 msgid "" "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." msgstr "" #: ../../faq/programming.rst:295 msgid "" "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." msgstr "" #: ../../faq/programming.rst:300 msgid "It's good practice if you import modules in the following order:" msgstr "" #: ../../faq/programming.rst:302 msgid "" "standard library modules -- such as :mod:`sys`, :mod:`os`, :mod:`argparse`, :" "mod:`re`" msgstr "" #: ../../faq/programming.rst:303 msgid "" "third-party library modules (anything installed in Python's site-packages " "directory) -- such as :pypi:`dateutil`, :pypi:`requests`, :pypi:`tzdata`" msgstr "" #: ../../faq/programming.rst:305 msgid "locally developed modules" msgstr "" #: ../../faq/programming.rst:307 msgid "" "It is sometimes necessary to move imports to a function or class to avoid " "problems with circular imports. Gordon McMillan says:" msgstr "" #: ../../faq/programming.rst:310 msgid "" "Circular imports are fine where both modules use the \"import \" " "form of import. They fail when the 2nd module wants to grab a name out of " "the first (\"from module import name\") and the import is at the top level. " "That's because names in the 1st are not yet available, because the first " "module is busy importing the 2nd." msgstr "" #: ../../faq/programming.rst:316 msgid "" "In this case, if the second module is only used in one function, then the " "import can easily be moved into that function. By the time the import is " "called, the first module will have finished initializing, and the second " "module can do its import." msgstr "" #: ../../faq/programming.rst:321 msgid "" "It may also be necessary to move imports out of the top level of code if " "some of the modules are platform-specific. In that case, it may not even be " "possible to import all of the modules at the top of the file. In this case, " "importing the correct modules in the corresponding platform-specific code is " "a good option." msgstr "" #: ../../faq/programming.rst:326 msgid "" "Only move imports into a local scope, such as inside a function definition, " "if it's necessary to solve a problem such as avoiding a circular import or " "are trying to reduce the initialization time of a module. This technique is " "especially helpful if many of the imports are unnecessary depending on how " "the program executes. You may also want to move imports into a function if " "the modules are only ever used in that function. Note that loading a module " "the first time may be expensive because of the one time initialization of " "the module, but loading a module multiple times is virtually free, costing " "only a couple of dictionary lookups. Even if the module name has gone out " "of scope, the module is probably available in :data:`sys.modules`." msgstr "" #: ../../faq/programming.rst:339 msgid "Why are default values shared between objects?" msgstr "" #: ../../faq/programming.rst:341 msgid "" "This type of bug commonly bites neophyte programmers. Consider this " "function::" msgstr "" #: ../../faq/programming.rst:343 msgid "" "def foo(mydict={}): # Danger: shared reference to one dict for all calls\n" " ... compute something ...\n" " mydict[key] = value\n" " return mydict" msgstr "" #: ../../faq/programming.rst:348 msgid "" "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." msgstr "" #: ../../faq/programming.rst:352 msgid "" "It is often expected that a function call creates new objects for default " "values. This is not what happens. Default values are created exactly once, " "when the function is defined. If that object is changed, like the " "dictionary in this example, subsequent calls to the function will refer to " "this changed object." msgstr "" #: ../../faq/programming.rst:357 msgid "" "By definition, immutable objects such as numbers, strings, tuples, and " "``None``, are safe from change. Changes to mutable objects such as " "dictionaries, lists, and class instances can lead to confusion." msgstr "" #: ../../faq/programming.rst:361 msgid "" "Because of this feature, it is good programming practice to not use mutable " "objects as default values. Instead, use ``None`` as the default value and " "inside the function, check if the parameter is ``None`` and create a new " "list/dictionary/whatever if it is. For example, don't write::" msgstr "" #: ../../faq/programming.rst:366 msgid "" "def foo(mydict={}):\n" " ..." msgstr "" #: ../../faq/programming.rst:369 msgid "but::" msgstr "" #: ../../faq/programming.rst:371 msgid "" "def foo(mydict=None):\n" " if mydict is None:\n" " mydict = {} # create a new dict for local namespace" msgstr "" #: ../../faq/programming.rst:375 msgid "" "This feature can be useful. When you have a function that's time-consuming " "to compute, a common technique is to cache the parameters and the resulting " "value of each call to the function, and return the cached value if the same " "value is requested again. This is called \"memoizing\", and can be " "implemented like this::" msgstr "" #: ../../faq/programming.rst:380 msgid "" "# Callers can only provide two parameters and optionally pass _cache by " "keyword\n" "def expensive(arg1, arg2, *, _cache={}):\n" " if (arg1, arg2) in _cache:\n" " return _cache[(arg1, arg2)]\n" "\n" " # Calculate the value\n" " result = ... expensive computation ...\n" " _cache[(arg1, arg2)] = result # Store result in the cache\n" " return result" msgstr "" #: ../../faq/programming.rst:390 msgid "" "You could use a global variable containing a dictionary instead of the " "default value; it's a matter of taste." msgstr "" #: ../../faq/programming.rst:395 msgid "" "How can I pass optional or keyword parameters from one function to another?" msgstr "" #: ../../faq/programming.rst:397 msgid "" "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 ``**``::" msgstr "" #: ../../faq/programming.rst:402 msgid "" "def f(x, *args, **kwargs):\n" " ...\n" " kwargs['width'] = '14.3c'\n" " ...\n" " g(x, *args, **kwargs)" msgstr "" #: ../../faq/programming.rst:416 msgid "What is the difference between arguments and parameters?" msgstr "" #: ../../faq/programming.rst:418 msgid "" ":term:`Parameters ` are defined by the names that appear in a " "function definition, whereas :term:`arguments ` are the values " "actually passed to a function when calling it. Parameters define what :term:" "`kind of arguments ` a function can accept. For example, given " "the function definition::" msgstr "" #: ../../faq/programming.rst:424 msgid "" "def func(foo, bar=None, **kwargs):\n" " pass" msgstr "" #: ../../faq/programming.rst:427 msgid "" "*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling " "``func``, for example::" msgstr "" #: ../../faq/programming.rst:430 msgid "func(42, bar=314, extra=somevar)" msgstr "" #: ../../faq/programming.rst:432 msgid "the values ``42``, ``314``, and ``somevar`` are arguments." msgstr "" #: ../../faq/programming.rst:436 msgid "Why did changing list 'y' also change list 'x'?" msgstr "" #: ../../faq/programming.rst:438 msgid "If you wrote code like::" msgstr "" #: ../../faq/programming.rst:440 msgid "" ">>> x = []\n" ">>> y = x\n" ">>> y.append(10)\n" ">>> y\n" "[10]\n" ">>> x\n" "[10]" msgstr "" #: ../../faq/programming.rst:448 msgid "" "you might be wondering why appending an element to ``y`` changed ``x`` too." msgstr "" #: ../../faq/programming.rst:450 msgid "There are two factors that produce this result:" msgstr "" #: ../../faq/programming.rst:452 msgid "" "Variables are simply names that refer to objects. Doing ``y = x`` doesn't " "create a copy of the list -- it creates a new variable ``y`` that refers to " "the same object ``x`` refers to. This means that there is only one object " "(the list), and both ``x`` and ``y`` refer to it." msgstr "" #: ../../faq/programming.rst:456 msgid "" "Lists are :term:`mutable`, which means that you can change their content." msgstr "" #: ../../faq/programming.rst:458 msgid "" "After the call to :meth:`~sequence.append`, the content of the mutable " "object has changed from ``[]`` to ``[10]``. Since both the variables refer " "to the same object, using either name accesses the modified value ``[10]``." msgstr "" #: ../../faq/programming.rst:462 msgid "If we instead assign an immutable object to ``x``::" msgstr "" #: ../../faq/programming.rst:464 msgid "" ">>> x = 5 # ints are immutable\n" ">>> y = x\n" ">>> x = x + 1 # 5 can't be mutated, we are creating a new object here\n" ">>> x\n" "6\n" ">>> y\n" "5" msgstr "" #: ../../faq/programming.rst:472 msgid "" "we can see that in this case ``x`` and ``y`` are not equal anymore. This is " "because integers are :term:`immutable`, and when we do ``x = x + 1`` we are " "not mutating the int ``5`` by incrementing its value; instead, we are " "creating a new object (the int ``6``) and assigning it to ``x`` (that is, " "changing which object ``x`` refers to). After this assignment we have two " "objects (the ints ``6`` and ``5``) and two variables that refer to them " "(``x`` now refers to ``6`` but ``y`` still refers to ``5``)." msgstr "" #: ../../faq/programming.rst:480 msgid "" "Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the " "object, whereas superficially similar operations (for example ``y = y + " "[10]`` and :func:`sorted(y) `) create a new object. In general in " "Python (and in all cases in the standard library) a method that mutates an " "object will return ``None`` to help avoid getting the two types of " "operations confused. So if you mistakenly write ``y.sort()`` thinking it " "will give you a sorted copy of ``y``, you'll instead end up with ``None``, " "which will likely cause your program to generate an easily diagnosed error." msgstr "" #: ../../faq/programming.rst:489 msgid "" "However, there is one class of operations where the same operation sometimes " "has different behaviors with different types: the augmented assignment " "operators. For example, ``+=`` mutates lists but not tuples or ints " "(``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and " "mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += " "1`` create new objects)." msgstr "" #: ../../faq/programming.rst:496 msgid "In other words:" msgstr "" #: ../../faq/programming.rst:498 msgid "" "If we have a mutable object (such as :class:`list`, :class:`dict`, :class:" "`set`), we can use some specific operations to mutate it and all the " "variables that refer to it will see the change." msgstr "" #: ../../faq/programming.rst:501 msgid "" "If we have an immutable object (such as :class:`str`, :class:`int`, :class:" "`tuple`), all the variables that refer to it will always see the same value, " "but operations that transform that value into a new value always return a " "new object." msgstr "" #: ../../faq/programming.rst:506 msgid "" "If you want to know if two variables refer to the same object or not, you " "can use the :keyword:`is` operator, or the built-in function :func:`id`." msgstr "" #: ../../faq/programming.rst:511 msgid "How do I write a function with output parameters (call by reference)?" msgstr "" #: ../../faq/programming.rst:513 msgid "" "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." msgstr "" #: ../../faq/programming.rst:518 msgid "By returning a tuple of the results::" msgstr "" #: ../../faq/programming.rst:520 msgid "" ">>> def func1(a, b):\n" "... a = 'new-value' # a and b are local names\n" "... b = b + 1 # assigned to new objects\n" "... return a, b # return new values\n" "...\n" ">>> x, y = 'old-value', 99\n" ">>> func1(x, y)\n" "('new-value', 100)" msgstr "" #: ../../faq/programming.rst:529 msgid "This is almost always the clearest solution." msgstr "" #: ../../faq/programming.rst:531 msgid "" "By using global variables. This isn't thread-safe, and is not recommended." msgstr "" #: ../../faq/programming.rst:533 msgid "By passing a mutable (changeable in-place) object::" msgstr "" #: ../../faq/programming.rst:535 msgid "" ">>> def func2(a):\n" "... a[0] = 'new-value' # 'a' references a mutable list\n" "... a[1] = a[1] + 1 # changes a shared object\n" "...\n" ">>> args = ['old-value', 99]\n" ">>> func2(args)\n" ">>> args\n" "['new-value', 100]" msgstr "" #: ../../faq/programming.rst:544 msgid "By passing in a dictionary that gets mutated::" msgstr "" #: ../../faq/programming.rst:546 msgid "" ">>> def func3(args):\n" "... args['a'] = 'new-value' # args is a mutable dictionary\n" "... args['b'] = args['b'] + 1 # change it in-place\n" "...\n" ">>> args = {'a': 'old-value', 'b': 99}\n" ">>> func3(args)\n" ">>> args\n" "{'a': 'new-value', 'b': 100}" msgstr "" #: ../../faq/programming.rst:555 msgid "Or bundle up values in a class instance::" msgstr "" #: ../../faq/programming.rst:557 msgid "" ">>> class Namespace:\n" "... def __init__(self, /, **args):\n" "... for key, value in args.items():\n" "... setattr(self, key, value)\n" "...\n" ">>> def func4(args):\n" "... args.a = 'new-value' # args is a mutable Namespace\n" "... args.b = args.b + 1 # change object in-place\n" "...\n" ">>> args = Namespace(a='old-value', b=99)\n" ">>> func4(args)\n" ">>> vars(args)\n" "{'a': 'new-value', 'b': 100}" msgstr "" #: ../../faq/programming.rst:572 msgid "There's almost never a good reason to get this complicated." msgstr "" #: ../../faq/programming.rst:574 msgid "Your best choice is to return a tuple containing the multiple results." msgstr "" #: ../../faq/programming.rst:578 msgid "How do you make a higher order function in Python?" msgstr "" #: ../../faq/programming.rst:580 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:584 msgid "" "def linear(a, b):\n" " def result(x):\n" " return a * x + b\n" " return result" msgstr "" #: ../../faq/programming.rst:589 msgid "Or using a callable object::" msgstr "" #: ../../faq/programming.rst:591 msgid "" "class linear:\n" "\n" " def __init__(self, a, b):\n" " self.a, self.b = a, b\n" "\n" " def __call__(self, x):\n" " return self.a * x + self.b" msgstr "" #: ../../faq/programming.rst:599 msgid "In both cases, ::" msgstr "" #: ../../faq/programming.rst:601 msgid "taxes = linear(0.3, 2)" msgstr "" #: ../../faq/programming.rst:603 msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``." msgstr "" #: ../../faq/programming.rst:605 msgid "" "The callable object approach has the disadvantage that it is a bit slower " "and results in slightly longer code. However, note that a collection of " "callables can share their signature via inheritance::" msgstr "" #: ../../faq/programming.rst:609 msgid "" "class exponential(linear):\n" " # __init__ inherited\n" " def __call__(self, x):\n" " return self.a * (x ** self.b)" msgstr "" #: ../../faq/programming.rst:614 msgid "Object can encapsulate state for several methods::" msgstr "" #: ../../faq/programming.rst:616 msgid "" "class counter:\n" "\n" " value = 0\n" "\n" " def set(self, x):\n" " self.value = x\n" "\n" " def up(self):\n" " self.value = self.value + 1\n" "\n" " def down(self):\n" " self.value = self.value - 1\n" "\n" "count = counter()\n" "inc, dec, reset = count.up, count.down, count.set" msgstr "" #: ../../faq/programming.rst:632 msgid "" "Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the " "same counting variable." msgstr "" #: ../../faq/programming.rst:637 msgid "How do I copy an object in Python?" msgstr "" #: ../../faq/programming.rst:639 msgid "" "In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general " "case. Not all objects can be copied, but most can." msgstr "" #: ../../faq/programming.rst:642 msgid "" "Some objects can be copied more easily. Dictionaries have a :meth:`~dict." "copy` method::" msgstr "" #: ../../faq/programming.rst:645 msgid "newdict = olddict.copy()" msgstr "" #: ../../faq/programming.rst:647 msgid "Sequences can be copied by slicing::" msgstr "" #: ../../faq/programming.rst:649 msgid "new_l = l[:]" msgstr "" #: ../../faq/programming.rst:653 msgid "How can I find the methods or attributes of an object?" msgstr "" #: ../../faq/programming.rst:655 msgid "" "For an instance ``x`` of a user-defined class, :func:`dir(x) ` returns " "an alphabetized list of the names containing the instance attributes and " "methods and attributes defined by its class." msgstr "" #: ../../faq/programming.rst:661 msgid "How can my code discover the name of an object?" msgstr "" #: ../../faq/programming.rst:663 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:668 msgid "" ">>> class A:\n" "... pass\n" "...\n" ">>> B = A\n" ">>> a = B()\n" ">>> b = a\n" ">>> print(b)\n" "<__main__.A object at 0x16D07CC>\n" ">>> print(a)\n" "<__main__.A object at 0x16D07CC>" msgstr "" #: ../../faq/programming.rst:679 msgid "" "Arguably the class has a name: even though it is bound to two names and " "invoked through the name ``B`` the created instance is still reported as an " "instance of class ``A``. However, it is impossible to say whether the " "instance's name is ``a`` or ``b``, since both names are bound to the same " "value." msgstr "" #: ../../faq/programming.rst:684 msgid "" "Generally speaking it should not be necessary for your code to \"know the " "names\" of particular values. Unless you are deliberately writing " "introspective programs, this is usually an indication that a change of " "approach might be beneficial." msgstr "" #: ../../faq/programming.rst:689 msgid "" "In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer " "to this question:" msgstr "" #: ../../faq/programming.rst:692 msgid "" "The same way as you get the name of that cat you found on your porch: the " "cat (object) itself cannot tell you its name, and it doesn't really care -- " "so the only way to find out what it's called is to ask all your neighbours " "(namespaces) if it's their cat (object)..." msgstr "" #: ../../faq/programming.rst:697 msgid "" "....and don't be surprised if you'll find that it's known by many names, or " "no name at all!" msgstr "" #: ../../faq/programming.rst:702 msgid "What's up with the comma operator's precedence?" msgstr "" #: ../../faq/programming.rst:704 msgid "Comma is not an operator in Python. Consider this session::" msgstr "" #: ../../faq/programming.rst:706 msgid "" ">>> \"a\" in \"b\", \"a\"\n" "(False, 'a')" msgstr "" #: ../../faq/programming.rst:709 msgid "" "Since the comma is not an operator, but a separator between expressions the " "above is evaluated as if you had entered::" msgstr "" #: ../../faq/programming.rst:712 msgid "(\"a\" in \"b\"), \"a\"" msgstr "" #: ../../faq/programming.rst:714 msgid "not::" msgstr "" #: ../../faq/programming.rst:716 msgid "\"a\" in (\"b\", \"a\")" msgstr "" #: ../../faq/programming.rst:718 msgid "" "The same is true of the various assignment operators (``=``, ``+=``, and so " "on). They are not truly operators but syntactic delimiters in assignment " "statements." msgstr "" #: ../../faq/programming.rst:723 msgid "Is there an equivalent of C's \"?:\" ternary operator?" msgstr "" #: ../../faq/programming.rst:725 msgid "Yes, there is. The syntax is as follows::" msgstr "" #: ../../faq/programming.rst:727 msgid "" "[on_true] if [expression] else [on_false]\n" "\n" "x, y = 50, 25\n" "small = x if x < y else y" msgstr "" #: ../../faq/programming.rst:732 msgid "" "Before this syntax was introduced in Python 2.5, a common idiom was to use " "logical operators::" msgstr "" #: ../../faq/programming.rst:735 msgid "[expression] and [on_true] or [on_false]" msgstr "" #: ../../faq/programming.rst:737 msgid "" "However, this idiom is unsafe, as it can give wrong results when *on_true* " "has a false boolean value. Therefore, it is always better to use the ``... " "if ... else ...`` form." msgstr "" #: ../../faq/programming.rst:743 msgid "Is it possible to write obfuscated one-liners in Python?" msgstr "" #: ../../faq/programming.rst:745 msgid "" "Yes. Usually this is done by nesting :keyword:`lambda` within :keyword:`!" "lambda`. See the following three examples, slightly adapted from Ulf " "Bartelt::" msgstr "" #: ../../faq/programming.rst:748 msgid "" "from functools import reduce\n" "\n" "# Primes < 1000\n" "print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\n" "map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))\n" "\n" "# First 10 Fibonacci numbers\n" "print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:\n" "f(x,f), range(10))))\n" "\n" "# Mandelbrot set\n" "print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\\n'+y,map(lambda " "y,\n" "Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\n" "Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\n" "i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y\n" ">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(\n" "64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\n" "))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))\n" "# \\___ ___/ \\___ ___/ | | |__ lines on screen\n" "# V V | |______ columns on screen\n" "# | | |__________ maximum of \"iterations\"\n" "# | |_________________ range on y axis\n" "# |____________________________ range on x axis" msgstr "" #: ../../faq/programming.rst:772 msgid "Don't try this at home, kids!" msgstr "" #: ../../faq/programming.rst:778 msgid "What does the slash(/) in the parameter list of a function mean?" msgstr "" #: ../../faq/programming.rst:780 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:787 msgid "" ">>> help(divmod)\n" "Help on built-in function divmod in module builtins:\n" "\n" "divmod(x, y, /)\n" " Return the tuple (x//y, x%y). Invariant: div*y + mod == x." msgstr "" #: ../../faq/programming.rst:793 msgid "" "The slash at the end of the parameter list means that both parameters are " "positional-only. Thus, calling :func:`divmod` with keyword arguments would " "lead to an error::" msgstr "" #: ../../faq/programming.rst:797 msgid "" ">>> divmod(x=3, y=4)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: divmod() takes no keyword arguments" msgstr "" #: ../../faq/programming.rst:804 msgid "Numbers and strings" msgstr "" #: ../../faq/programming.rst:807 msgid "How do I specify hexadecimal and octal integers?" msgstr "" #: ../../faq/programming.rst:809 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:813 msgid "" ">>> a = 0o10\n" ">>> a\n" "8" msgstr "" #: ../../faq/programming.rst:817 msgid "" "Hexadecimal is just as easy. Simply precede the hexadecimal number with a " "zero, and then a lower or uppercase \"x\". Hexadecimal digits can be " "specified in lower or uppercase. For example, in the Python interpreter::" msgstr "" #: ../../faq/programming.rst:821 msgid "" ">>> a = 0xa5\n" ">>> a\n" "165\n" ">>> b = 0XB2\n" ">>> b\n" "178" msgstr "" #: ../../faq/programming.rst:830 msgid "Why does -22 // 10 return -3?" msgstr "" #: ../../faq/programming.rst:832 msgid "" "It's primarily driven by the desire that ``i % j`` have the same sign as " "``j``. If you want that, and also want::" msgstr "" #: ../../faq/programming.rst:835 msgid "i == (i // j) * j + (i % j)" msgstr "" #: ../../faq/programming.rst:837 msgid "" "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``." msgstr "" #: ../../faq/programming.rst:841 msgid "" "There are few real use cases for ``i % j`` when ``j`` is negative. When " "``j`` is positive, there are many, and in virtually all of them it's more " "useful for ``i % j`` to be ``>= 0``. If the clock says 10 now, what did it " "say 200 hours ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a " "bug waiting to bite." msgstr "" #: ../../faq/programming.rst:849 msgid "How do I get int literal attribute instead of SyntaxError?" msgstr "" #: ../../faq/programming.rst:851 msgid "" "Trying to lookup an ``int`` literal attribute in the normal manner gives a :" "exc:`SyntaxError` because the period is seen as a decimal point::" msgstr "" #: ../../faq/programming.rst:854 msgid "" ">>> 1.__class__\n" " File \"\", line 1\n" " 1.__class__\n" " ^\n" "SyntaxError: invalid decimal literal" msgstr "" #: ../../faq/programming.rst:860 msgid "" "The solution is to separate the literal from the period with either a space " "or parentheses." msgstr "" #: ../../faq/programming.rst:870 msgid "How do I convert a string to a number?" msgstr "" #: ../../faq/programming.rst:872 msgid "" "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``." msgstr "" #: ../../faq/programming.rst:876 msgid "" "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." msgstr "" #: ../../faq/programming.rst:883 msgid "" "Do not use the built-in function :func:`eval` if all you need is to convert " "strings to numbers. :func:`eval` will be significantly slower and it " "presents a security risk: someone could pass you a Python expression that " "might have unwanted side effects. For example, someone could pass " "``__import__('os').system(\"rm -rf $HOME\")`` which would erase your home " "directory." msgstr "" #: ../../faq/programming.rst:890 msgid "" ":func:`eval` also has the effect of interpreting numbers as Python " "expressions, so that, for example, ``eval('09')`` gives a syntax error " "because Python does not allow leading '0' in a decimal number (except '0')." msgstr "" #: ../../faq/programming.rst:896 msgid "How do I convert a number to a string?" msgstr "" #: ../../faq/programming.rst:898 msgid "" "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'``." msgstr "" #: ../../faq/programming.rst:907 msgid "How do I modify a string in place?" msgstr "" #: ../../faq/programming.rst:909 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:915 msgid "" ">>> import io\n" ">>> s = \"Hello, world\"\n" ">>> sio = io.StringIO(s)\n" ">>> sio.getvalue()\n" "'Hello, world'\n" ">>> sio.seek(7)\n" "7\n" ">>> sio.write(\"there!\")\n" "6\n" ">>> sio.getvalue()\n" "'Hello, there!'\n" "\n" ">>> import array\n" ">>> a = array.array('w', s)\n" ">>> print(a)\n" "array('w', 'Hello, world')\n" ">>> a[0] = 'y'\n" ">>> print(a)\n" "array('w', 'yello, world')\n" ">>> a.tounicode()\n" "'yello, world'" msgstr "" #: ../../faq/programming.rst:939 msgid "How do I use strings to call functions/methods?" msgstr "" #: ../../faq/programming.rst:941 msgid "There are various techniques." msgstr "" #: ../../faq/programming.rst:943 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:948 msgid "" "def a():\n" " pass\n" "\n" "def b():\n" " pass\n" "\n" "dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs\n" "\n" "dispatch[get_input()]() # Note trailing parens to call function" msgstr "" #: ../../faq/programming.rst:958 msgid "Use the built-in function :func:`getattr`::" msgstr "" #: ../../faq/programming.rst:960 msgid "" "import foo\n" "getattr(foo, 'bar')()" msgstr "" #: ../../faq/programming.rst:963 msgid "" "Note that :func:`getattr` works on any object, including classes, class " "instances, modules, and so on." msgstr "" #: ../../faq/programming.rst:966 msgid "This is used in several places in the standard library, like this::" msgstr "" #: ../../faq/programming.rst:968 msgid "" "class Foo:\n" " def do_foo(self):\n" " ...\n" "\n" " def do_bar(self):\n" " ...\n" "\n" "f = getattr(foo_instance, 'do_' + opname)\n" "f()" msgstr "" #: ../../faq/programming.rst:979 msgid "Use :func:`locals` to resolve the function name::" msgstr "" #: ../../faq/programming.rst:981 msgid "" "def myFunc():\n" " print(\"hello\")\n" "\n" "fname = \"myFunc\"\n" "\n" "f = locals()[fname]\n" "f()" msgstr "" #: ../../faq/programming.rst:991 msgid "" "Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines " "from strings?" msgstr "" #: ../../faq/programming.rst:993 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:999 msgid "" ">>> lines = (\"line 1 \\r\\n\"\n" "... \"\\r\\n\"\n" "... \"\\r\\n\")\n" ">>> lines.rstrip(\"\\n\\r\")\n" "'line 1 '" msgstr "" #: ../../faq/programming.rst:1005 msgid "" "Since this is typically only desired when reading text one line at a time, " "using ``S.rstrip()`` this way works well." msgstr "" #: ../../faq/programming.rst:1010 msgid "Is there a ``scanf()`` or ``sscanf()`` equivalent?" msgstr "" #: ../../faq/programming.rst:1012 msgid "Not as such." msgstr "" #: ../../faq/programming.rst:1014 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1020 msgid "" "For more complicated input parsing, regular expressions are more powerful " "than C's ``sscanf`` and better suited for the task." msgstr "" #: ../../faq/programming.rst:1025 msgid "What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?" msgstr "" #: ../../faq/programming.rst:1027 msgid "See the :ref:`unicode-howto`." msgstr "" #: ../../faq/programming.rst:1033 msgid "Can I end a raw string with an odd number of backslashes?" msgstr "" #: ../../faq/programming.rst:1035 msgid "" "A raw string ending with an odd number of backslashes will escape the " "string's quote::" msgstr "" #: ../../faq/programming.rst:1037 msgid "" ">>> r'C:\\this\\will\\not\\work\\'\n" " File \"\", line 1\n" " r'C:\\this\\will\\not\\work\\'\n" " ^\n" "SyntaxError: unterminated string literal (detected at line 1)" msgstr "" #: ../../faq/programming.rst:1043 msgid "" "There are several workarounds for this. One is to use regular strings and " "double the backslashes::" msgstr "" #: ../../faq/programming.rst:1046 msgid "" ">>> 'C:\\\\this\\\\will\\\\work\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" #: ../../faq/programming.rst:1049 msgid "" "Another is to concatenate a regular string containing an escaped backslash " "to the raw string::" msgstr "" #: ../../faq/programming.rst:1052 msgid "" ">>> r'C:\\this\\will\\work' '\\\\'\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" #: ../../faq/programming.rst:1055 msgid "" "It is also possible to use :func:`os.path.join` to append a backslash on " "Windows::" msgstr "" #: ../../faq/programming.rst:1057 msgid "" ">>> os.path.join(r'C:\\this\\will\\work', '')\n" "'C:\\\\this\\\\will\\\\work\\\\'" msgstr "" #: ../../faq/programming.rst:1060 msgid "" "Note that while a backslash will \"escape\" a quote for the purposes of " "determining where the raw string ends, no escaping occurs when interpreting " "the value of the raw string. That is, the backslash remains present in the " "value of the raw string::" msgstr "" #: ../../faq/programming.rst:1065 msgid "" ">>> r'backslash\\'preserved'\n" "\"backslash\\\\'preserved\"" msgstr "" #: ../../faq/programming.rst:1068 msgid "Also see the specification in the :ref:`language reference `." msgstr "" #: ../../faq/programming.rst:1072 msgid "Performance" msgstr "" #: ../../faq/programming.rst:1075 msgid "My program is too slow. How do I speed it up?" msgstr "" #: ../../faq/programming.rst:1077 msgid "" "That's a tough one, in general. First, here is a list of things to remember " "before diving further:" msgstr "" #: ../../faq/programming.rst:1080 msgid "" "Performance characteristics vary across Python implementations. This FAQ " "focuses on :term:`CPython`." msgstr "" #: ../../faq/programming.rst:1082 msgid "" "Behaviour can vary across operating systems, especially when talking about I/" "O or multi-threading." msgstr "" #: ../../faq/programming.rst:1084 msgid "" "You should always find the hot spots in your program *before* attempting to " "optimize any code (see the :mod:`profile` module)." msgstr "" #: ../../faq/programming.rst:1086 msgid "" "Writing benchmark scripts will allow you to iterate quickly when searching " "for improvements (see the :mod:`timeit` module)." msgstr "" #: ../../faq/programming.rst:1088 msgid "" "It is highly recommended to have good code coverage (through unit testing or " "any other technique) before potentially introducing regressions hidden in " "sophisticated optimizations." msgstr "" #: ../../faq/programming.rst:1092 msgid "" "That being said, there are many tricks to speed up Python code. Here are " "some general principles which go a long way towards reaching acceptable " "performance levels:" msgstr "" #: ../../faq/programming.rst:1096 msgid "" "Making your algorithms faster (or changing to faster ones) can yield much " "larger benefits than trying to sprinkle micro-optimization tricks all over " "your code." msgstr "" #: ../../faq/programming.rst:1100 msgid "" "Use the right data structures. Study documentation for the :ref:`bltin-" "types` and the :mod:`collections` module." msgstr "" #: ../../faq/programming.rst:1103 msgid "" "When the standard library provides a primitive for doing something, it is " "likely (although not guaranteed) to be faster than any alternative you may " "come up with. This is doubly true for primitives written in C, such as " "builtins and some extension types. For example, be sure to use either the :" "meth:`list.sort` built-in method or the related :func:`sorted` function to " "do sorting (and see the :ref:`sortinghowto` for examples of moderately " "advanced usage)." msgstr "" #: ../../faq/programming.rst:1111 msgid "" "Abstractions tend to create indirections and force the interpreter to work " "more. If the levels of indirection outweigh the amount of useful work done, " "your program will be slower. You should avoid excessive abstraction, " "especially under the form of tiny functions or methods (which are also often " "detrimental to readability)." msgstr "" #: ../../faq/programming.rst:1117 msgid "" "If you have reached the limit of what pure Python can allow, there are tools " "to take you further away. For example, `Cython `_ can " "compile a slightly modified version of Python code into a C extension, and " "can be used on many different platforms. Cython can take advantage of " "compilation (and optional type annotations) to make your code significantly " "faster than when interpreted. If you are confident in your C programming " "skills, you can also :ref:`write a C extension module ` " "yourself." msgstr "" #: ../../faq/programming.rst:1127 msgid "" "The wiki page devoted to `performance tips `_." msgstr "" #: ../../faq/programming.rst:1134 msgid "What is the most efficient way to concatenate many strings together?" msgstr "" #: ../../faq/programming.rst:1136 msgid "" ":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." msgstr "" #: ../../faq/programming.rst:1141 msgid "" "To accumulate many :class:`str` objects, the recommended idiom is to place " "them into a list and call :meth:`str.join` at the end::" msgstr "" #: ../../faq/programming.rst:1144 msgid "" "chunks = []\n" "for s in my_strings:\n" " chunks.append(s)\n" "result = ''.join(chunks)" msgstr "" #: ../../faq/programming.rst:1149 msgid "(Another reasonably efficient idiom is to use :class:`io.StringIO`.)" msgstr "" #: ../../faq/programming.rst:1151 msgid "" "To accumulate many :class:`bytes` objects, the recommended idiom is to " "extend a :class:`bytearray` object using in-place concatenation (the ``+=`` " "operator)::" msgstr "" #: ../../faq/programming.rst:1154 msgid "" "result = bytearray()\n" "for b in my_bytes_objects:\n" " result += b" msgstr "" #: ../../faq/programming.rst:1160 msgid "Sequences (tuples/lists)" msgstr "" #: ../../faq/programming.rst:1163 msgid "How do I convert between tuples and lists?" msgstr "" #: ../../faq/programming.rst:1165 msgid "" "The type constructor ``tuple(seq)`` converts any sequence (actually, any " "iterable) into a tuple with the same items in the same order." msgstr "" #: ../../faq/programming.rst:1168 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1173 msgid "" "The type constructor ``list(seq)`` converts any sequence or iterable into a " "list with the same items in the same order. For example, ``list((1, 2, " "3))`` yields ``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. " "If the argument is a list, it makes a copy just like ``seq[:]`` would." msgstr "" #: ../../faq/programming.rst:1180 msgid "What's a negative index?" msgstr "" #: ../../faq/programming.rst:1182 msgid "" "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]``." msgstr "" #: ../../faq/programming.rst:1187 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1193 msgid "How do I iterate over a sequence in reverse order?" msgstr "" #: ../../faq/programming.rst:1195 msgid "Use the :func:`reversed` built-in function::" msgstr "" #: ../../faq/programming.rst:1197 msgid "" "for x in reversed(sequence):\n" " ... # do something with x ..." msgstr "" #: ../../faq/programming.rst:1200 msgid "" "This won't touch your original sequence, but build a new copy with reversed " "order to iterate over." msgstr "" #: ../../faq/programming.rst:1205 msgid "How do you remove duplicates from a list?" msgstr "" #: ../../faq/programming.rst:1207 msgid "See the Python Cookbook for a long discussion of many ways to do this:" msgstr "" #: ../../faq/programming.rst:1209 msgid "https://code.activestate.com/recipes/52560/" msgstr "" #: ../../faq/programming.rst:1211 msgid "" "If you don't mind reordering the list, sort it and then scan from the end of " "the list, deleting duplicates as you go::" msgstr "" #: ../../faq/programming.rst:1214 msgid "" "if mylist:\n" " mylist.sort()\n" " last = mylist[-1]\n" " for i in range(len(mylist)-2, -1, -1):\n" " if last == mylist[i]:\n" " del mylist[i]\n" " else:\n" " last = mylist[i]" msgstr "" #: ../../faq/programming.rst:1223 msgid "" "If all elements of the list may be used as set keys (that is, they are all :" "term:`hashable`) this is often faster::" msgstr "" #: ../../faq/programming.rst:1226 msgid "mylist = list(set(mylist))" msgstr "" #: ../../faq/programming.rst:1228 msgid "" "This converts the list into a set, thereby removing duplicates, and then " "back into a list." msgstr "" #: ../../faq/programming.rst:1233 msgid "How do you remove multiple items from a list?" msgstr "" #: ../../faq/programming.rst:1235 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1240 msgid "" "mylist[:] = filter(keep_function, mylist)\n" "mylist[:] = (x for x in mylist if keep_condition)\n" "mylist[:] = [x for x in mylist if keep_condition]" msgstr "" #: ../../faq/programming.rst:1244 msgid "The list comprehension may be fastest." msgstr "" #: ../../faq/programming.rst:1248 msgid "How do you make an array in Python?" msgstr "" #: ../../faq/programming.rst:1250 msgid "Use a list::" msgstr "" #: ../../faq/programming.rst:1252 msgid "[\"this\", 1, \"is\", \"an\", \"array\"]" msgstr "" #: ../../faq/programming.rst:1254 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1257 msgid "" "The ``array`` module also provides methods for creating arrays of fixed " "types with compact representations, but they are slower to index than " "lists. Also note that `NumPy `_ and other third-party " "packages define array-like structures with various characteristics as well." msgstr "" #: ../../faq/programming.rst:1263 msgid "" "To get Lisp-style linked lists, you can emulate *cons cells* using tuples::" msgstr "" #: ../../faq/programming.rst:1265 msgid "lisp_list = (\"like\", (\"this\", (\"example\", None) ) )" msgstr "" #: ../../faq/programming.rst:1267 msgid "" "If mutability is desired, you could use lists instead of tuples. Here the " "analogue of a Lisp *car* is ``lisp_list[0]`` and the analogue of *cdr* is " "``lisp_list[1]``. Only do this if you're sure you really need to, because " "it's usually a lot slower than using Python lists." msgstr "" #: ../../faq/programming.rst:1276 msgid "How do I create a multidimensional list?" msgstr "" #: ../../faq/programming.rst:1278 msgid "You probably tried to make a multidimensional array like this::" msgstr "" #: ../../faq/programming.rst:1280 msgid ">>> A = [[None] * 2] * 3" msgstr "" #: ../../faq/programming.rst:1282 msgid "This looks correct if you print it:" msgstr "" #: ../../faq/programming.rst:1288 msgid "" ">>> A\n" "[[None, None], [None, None], [None, None]]" msgstr "" #: ../../faq/programming.rst:1293 msgid "But when you assign a value, it shows up in multiple places:" msgstr "" #: ../../faq/programming.rst:1299 msgid "" ">>> A[0][0] = 5\n" ">>> A\n" "[[5, None], [5, None], [5, None]]" msgstr "" #: ../../faq/programming.rst:1305 msgid "" "The reason is that replicating a list with ``*`` doesn't create copies, it " "only creates references to the existing objects. The ``*3`` creates a list " "containing 3 references to the same list of length two. Changes to one row " "will show in all rows, which is almost certainly not what you want." msgstr "" #: ../../faq/programming.rst:1310 msgid "" "The suggested approach is to create a list of the desired length first and " "then fill in each element with a newly created list::" msgstr "" #: ../../faq/programming.rst:1313 msgid "" "A = [None] * 3\n" "for i in range(3):\n" " A[i] = [None] * 2" msgstr "" #: ../../faq/programming.rst:1317 msgid "" "This generates a list containing 3 different lists of length two. You can " "also use a list comprehension::" msgstr "" #: ../../faq/programming.rst:1320 msgid "" "w, h = 2, 3\n" "A = [[None] * w for i in range(h)]" msgstr "" #: ../../faq/programming.rst:1323 msgid "" "Or, you can use an extension that provides a matrix datatype; `NumPy " "`_ is the best known." msgstr "" #: ../../faq/programming.rst:1328 msgid "How do I apply a method or function to a sequence of objects?" msgstr "" #: ../../faq/programming.rst:1330 msgid "" "To call a method or function and accumulate the return values in a list, a :" "term:`list comprehension` is an elegant solution::" msgstr "" #: ../../faq/programming.rst:1333 msgid "" "result = [obj.method() for obj in mylist]\n" "\n" "result = [function(obj) for obj in mylist]" msgstr "" #: ../../faq/programming.rst:1337 msgid "" "To just run the method or function without saving the return values, a " "plain :keyword:`for` loop will suffice::" msgstr "" #: ../../faq/programming.rst:1340 msgid "" "for obj in mylist:\n" " obj.method()\n" "\n" "for obj in mylist:\n" " function(obj)" msgstr "" #: ../../faq/programming.rst:1350 msgid "" "Why does a_tuple[i] += ['item'] raise an exception when the addition works?" msgstr "" #: ../../faq/programming.rst:1352 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1356 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1360 msgid "If you wrote::" msgstr "" #: ../../faq/programming.rst:1362 msgid "" ">>> a_tuple = (1, 2)\n" ">>> a_tuple[0] += 1\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1368 msgid "" "The reason for the exception should be immediately clear: ``1`` is added to " "the object ``a_tuple[0]`` points to (``1``), producing the result object, " "``2``, but when we attempt to assign the result of the computation, ``2``, " "to element ``0`` of the tuple, we get an error because we can't change what " "an element of a tuple points to." msgstr "" #: ../../faq/programming.rst:1374 msgid "" "Under the covers, what this augmented assignment statement is doing is " "approximately this::" msgstr "" #: ../../faq/programming.rst:1377 msgid "" ">>> result = a_tuple[0] + 1\n" ">>> a_tuple[0] = result\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1383 msgid "" "It is the assignment part of the operation that produces the error, since a " "tuple is immutable." msgstr "" #: ../../faq/programming.rst:1386 msgid "When you write something like::" msgstr "" #: ../../faq/programming.rst:1388 msgid "" ">>> a_tuple = (['foo'], 'bar')\n" ">>> a_tuple[0] += ['item']\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1394 msgid "" "The exception is a bit more surprising, and even more surprising is the fact " "that even though there was an error, the append worked::" msgstr "" #: ../../faq/programming.rst:1397 msgid "" ">>> a_tuple[0]\n" "['foo', 'item']" msgstr "" #: ../../faq/programming.rst:1400 msgid "" "To see why this happens, you need to know that (a) if an object implements " "an :meth:`~object.__iadd__` magic method, it gets called when the ``+=`` " "augmented assignment is executed, and its return value is what gets used in " "the assignment statement; and (b) for lists, :meth:`!__iadd__` is equivalent " "to calling :meth:`~sequence.extend` on the list and returning the list. " "That's why we say that for lists, ``+=`` is a \"shorthand\" for :meth:`list." "extend`::" msgstr "" #: ../../faq/programming.rst:1408 msgid "" ">>> a_list = []\n" ">>> a_list += [1]\n" ">>> a_list\n" "[1]" msgstr "" #: ../../faq/programming.rst:1413 msgid "This is equivalent to::" msgstr "" #: ../../faq/programming.rst:1415 msgid "" ">>> result = a_list.__iadd__([1])\n" ">>> a_list = result" msgstr "" #: ../../faq/programming.rst:1418 msgid "" "The object pointed to by a_list has been mutated, and the pointer to the " "mutated object is assigned back to ``a_list``. The end result of the " "assignment is a no-op, since it is a pointer to the same object that " "``a_list`` was previously pointing to, but the assignment still happens." msgstr "" #: ../../faq/programming.rst:1423 msgid "Thus, in our tuple example what is happening is equivalent to::" msgstr "" #: ../../faq/programming.rst:1425 msgid "" ">>> result = a_tuple[0].__iadd__(['item'])\n" ">>> a_tuple[0] = result\n" "Traceback (most recent call last):\n" " ...\n" "TypeError: 'tuple' object does not support item assignment" msgstr "" #: ../../faq/programming.rst:1431 msgid "" "The :meth:`!__iadd__` succeeds, and thus the list is extended, but even " "though ``result`` points to the same object that ``a_tuple[0]`` already " "points to, that final assignment still results in an error, because tuples " "are immutable." msgstr "" #: ../../faq/programming.rst:1437 msgid "" "I want to do a complicated sort: can you do a Schwartzian Transform in " "Python?" msgstr "" #: ../../faq/programming.rst:1439 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1443 msgid "" "Isorted = L[:]\n" "Isorted.sort(key=lambda s: int(s[10:15]))" msgstr "" #: ../../faq/programming.rst:1448 msgid "How can I sort one list by values from another list?" msgstr "" #: ../../faq/programming.rst:1450 msgid "" "Merge them into an iterator of tuples, sort the resulting list, and then " "pick out the element you want." msgstr "" #: ../../faq/programming.rst:1465 msgid "Objects" msgstr "" #: ../../faq/programming.rst:1468 msgid "What is a class?" msgstr "" #: ../../faq/programming.rst:1470 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1474 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1483 msgid "What is a method?" msgstr "" #: ../../faq/programming.rst:1485 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1489 msgid "" "class C:\n" " def meth(self, arg):\n" " return arg * 2 + self.attribute" msgstr "" #: ../../faq/programming.rst:1495 msgid "What is self?" msgstr "" #: ../../faq/programming.rst:1497 msgid "" "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)``." msgstr "" #: ../../faq/programming.rst:1502 msgid "See also :ref:`why-self`." msgstr "" #: ../../faq/programming.rst:1506 msgid "" "How do I check if an object is an instance of a given class or of a subclass " "of it?" msgstr "" #: ../../faq/programming.rst:1508 msgid "" "Use the built-in function :func:`isinstance(obj, cls) `. You " "can check if an object is an instance of any of a number of classes by " "providing a tuple instead of a single class, 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))``." msgstr "" #: ../../faq/programming.rst:1515 msgid "" "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 test for \"true inheritance\", scan the :term:`method resolution order` " "(MRO) of the class:" msgstr "" #: ../../faq/programming.rst:1521 msgid "" "from collections.abc import Mapping\n" "\n" "class P:\n" " pass\n" "\n" "class C(P):\n" " pass\n" "\n" "Mapping.register(P)" msgstr "" #: ../../faq/programming.rst:1533 msgid "" ">>> c = C()\n" ">>> isinstance(c, C) # direct\n" "True\n" ">>> isinstance(c, P) # indirect\n" "True\n" ">>> isinstance(c, Mapping) # virtual\n" "True\n" "\n" "# Actual inheritance chain\n" ">>> type(c).__mro__\n" "(, , )\n" "\n" "# Test for \"true inheritance\"\n" ">>> Mapping in type(c).__mro__\n" "False" msgstr "" #: ../../faq/programming.rst:1551 msgid "" "Note that most programs do not use :func:`isinstance` on user-defined " "classes very often. If you are developing the classes yourself, a more " "proper object-oriented style is to define methods on the classes that " "encapsulate a particular behaviour, instead of checking the object's class " "and doing a different thing based on what class it is. For example, if you " "have a function that does something::" msgstr "" #: ../../faq/programming.rst:1558 msgid "" "def search(obj):\n" " if isinstance(obj, Mailbox):\n" " ... # code to search a mailbox\n" " elif isinstance(obj, Document):\n" " ... # code to search a document\n" " elif ..." msgstr "" #: ../../faq/programming.rst:1565 msgid "" "A better approach is to define a ``search()`` method on all the classes and " "just call it::" msgstr "" #: ../../faq/programming.rst:1568 msgid "" "class Mailbox:\n" " def search(self):\n" " ... # code to search a mailbox\n" "\n" "class Document:\n" " def search(self):\n" " ... # code to search a document\n" "\n" "obj.search()" msgstr "" #: ../../faq/programming.rst:1580 msgid "What is delegation?" msgstr "" #: ../../faq/programming.rst:1582 msgid "" "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``." msgstr "" #: ../../faq/programming.rst:1588 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1592 msgid "" "class UpperOut:\n" "\n" " def __init__(self, outfile):\n" " self._outfile = outfile\n" "\n" " def write(self, s):\n" " self._outfile.write(s.upper())\n" "\n" " def __getattr__(self, name):\n" " return getattr(self._outfile, name)" msgstr "" #: ../../faq/programming.rst:1603 msgid "" "Here the ``UpperOut`` class redefines the ``write()`` method to convert the " "argument string to uppercase before calling the underlying ``self._outfile." "write()`` method. All other methods are delegated to the underlying ``self." "_outfile`` object. The delegation is accomplished via the :meth:`~object." "__getattr__` method; consult :ref:`the language reference ` for more information about controlling attribute access." msgstr "" #: ../../faq/programming.rst:1610 msgid "" "Note that for more general cases delegation can get trickier. When " "attributes must be set as well as retrieved, the class must define a :meth:" "`~object.__setattr__` method too, and it must do so carefully. The basic " "implementation of :meth:`!__setattr__` is roughly equivalent to the " "following::" msgstr "" #: ../../faq/programming.rst:1615 msgid "" "class X:\n" " ...\n" " def __setattr__(self, name, value):\n" " self.__dict__[name] = value\n" " ..." msgstr "" #: ../../faq/programming.rst:1621 msgid "" "Many :meth:`~object.__setattr__` implementations call :meth:`!object." "__setattr__` to set an attribute on self without causing infinite recursion::" msgstr "" #: ../../faq/programming.rst:1624 msgid "" "class X:\n" " def __setattr__(self, name, value):\n" " # Custom logic here...\n" " object.__setattr__(self, name, value)" msgstr "" #: ../../faq/programming.rst:1629 msgid "" "Alternatively, it is possible to set attributes by inserting entries into :" "attr:`self.__dict__ ` directly." msgstr "" #: ../../faq/programming.rst:1634 msgid "" "How do I call a method defined in a base class from a derived class that " "extends it?" msgstr "" #: ../../faq/programming.rst:1636 msgid "Use the built-in :func:`super` function::" msgstr "" #: ../../faq/programming.rst:1638 msgid "" "class Derived(Base):\n" " def meth(self):\n" " super().meth() # calls Base.meth" msgstr "" #: ../../faq/programming.rst:1642 msgid "" "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 the next in " "line after ``Derived`` in the MRO: ``Base``." msgstr "" #: ../../faq/programming.rst:1649 msgid "How can I organize my code to make it easier to change the base class?" msgstr "" #: ../../faq/programming.rst:1651 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1656 msgid "" "class Base:\n" " ...\n" "\n" "BaseAlias = Base\n" "\n" "class Derived(BaseAlias):\n" " ..." msgstr "" #: ../../faq/programming.rst:1666 msgid "How do I create static class data and static class methods?" msgstr "" #: ../../faq/programming.rst:1668 msgid "" "Both static data and static methods (in the sense of C++ or Java) are " "supported in Python." msgstr "" #: ../../faq/programming.rst:1671 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:1674 msgid "" "class C:\n" " count = 0 # number of times C.__init__ called\n" "\n" " def __init__(self):\n" " C.count = C.count + 1\n" "\n" " def getcount(self):\n" " return C.count # or return self.count" msgstr "" #: ../../faq/programming.rst:1683 msgid "" "``c.count`` also refers to ``C.count`` for any ``c`` such that " "``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some " "class on the base-class search path from ``c.__class__`` back to ``C``." msgstr "" #: ../../faq/programming.rst:1687 msgid "" "Caution: within a method of C, an assignment like ``self.count = 42`` " "creates a new and unrelated instance named \"count\" in ``self``'s own " "dict. Rebinding of a class-static data name must always specify the class " "whether inside a method or not::" msgstr "" #: ../../faq/programming.rst:1692 msgid "C.count = 314" msgstr "" #: ../../faq/programming.rst:1694 msgid "Static methods are possible::" msgstr "" #: ../../faq/programming.rst:1696 msgid "" "class C:\n" " @staticmethod\n" " def static(arg1, arg2, arg3):\n" " # No 'self' parameter!\n" " ..." msgstr "" #: ../../faq/programming.rst:1702 msgid "" "However, a far more straightforward way to get the effect of a static method " "is via a simple module-level function::" msgstr "" #: ../../faq/programming.rst:1705 msgid "" "def getcount():\n" " return C.count" msgstr "" #: ../../faq/programming.rst:1708 msgid "" "If your code is structured so as to define one class (or tightly related " "class hierarchy) per module, this supplies the desired encapsulation." msgstr "" #: ../../faq/programming.rst:1713 msgid "How can I overload constructors (or methods) in Python?" msgstr "" #: ../../faq/programming.rst:1715 msgid "" "This answer actually applies to all methods, but the question usually comes " "up first in the context of constructors." msgstr "" #: ../../faq/programming.rst:1718 msgid "In C++ you'd write:" msgstr "" #: ../../faq/programming.rst:1720 msgid "" "class C {\n" " C() { cout << \"No arguments\\n\"; }\n" " C(int i) { cout << \"Argument is \" << i << \"\\n\"; }\n" "}" msgstr "" #: ../../faq/programming.rst:1727 msgid "" "In Python you have to write a single constructor that catches all cases " "using default arguments. For example::" msgstr "" #: ../../faq/programming.rst:1730 msgid "" "class C:\n" " def __init__(self, i=None):\n" " if i is None:\n" " print(\"No arguments\")\n" " else:\n" " print(\"Argument is\", i)" msgstr "" #: ../../faq/programming.rst:1737 msgid "This is not entirely equivalent, but close enough in practice." msgstr "" #: ../../faq/programming.rst:1739 msgid "You could also try a variable-length argument list, for example::" msgstr "" #: ../../faq/programming.rst:1741 msgid "" "def __init__(self, *args):\n" " ..." msgstr "" #: ../../faq/programming.rst:1744 msgid "The same approach works for all method definitions." msgstr "" #: ../../faq/programming.rst:1748 msgid "I try to use __spam and I get an error about _SomeClassName__spam." msgstr "" #: ../../faq/programming.rst:1750 msgid "" "Variable names with double leading underscores are \"mangled\" to provide a " "simple but effective way to define class private variables. Any identifier " "of the form ``__spam`` (at least two leading underscores, at most one " "trailing underscore) is textually replaced with ``_classname__spam``, where " "``classname`` is the current class name with any leading underscores " "stripped." msgstr "" #: ../../faq/programming.rst:1756 msgid "" "The identifier can be used unchanged within the class, but to access it " "outside the class, the mangled name must be used:" msgstr "" #: ../../faq/programming.rst:1759 msgid "" "class A:\n" " def __one(self):\n" " return 1\n" " def two(self):\n" " return 2 * self.__one()\n" "\n" "class B(A):\n" " def three(self):\n" " return 3 * self._A__one()\n" "\n" "four = 4 * A()._A__one()" msgstr "" #: ../../faq/programming.rst:1773 msgid "" "In particular, this does not guarantee privacy since an outside user can " "still deliberately access the private attribute; many Python programmers " "never bother to use private variable names at all." msgstr "" #: ../../faq/programming.rst:1779 msgid "" "The :ref:`private name mangling specifications ` for " "details and special cases." msgstr "" #: ../../faq/programming.rst:1784 msgid "My class defines __del__ but it is not called when I delete the object." msgstr "" #: ../../faq/programming.rst:1786 msgid "There are several possible reasons for this." msgstr "" #: ../../faq/programming.rst:1788 msgid "" "The :keyword:`del` statement does not necessarily call :meth:`~object." "__del__` -- it simply decrements the object's reference count, and if this " "reaches zero :meth:`!__del__` is called." msgstr "" #: ../../faq/programming.rst:1792 msgid "" "If your data structures contain circular links (for example, a tree where " "each child has a parent reference and each parent has a list of children) " "the reference counts will never go back to zero. Once in a while Python " "runs an algorithm to detect such cycles, but the garbage collector might run " "some time after the last reference to your data structure vanishes, so your :" "meth:`!__del__` method may be called at an inconvenient and random time. " "This is inconvenient if you're trying to reproduce a problem. Worse, the " "order in which object's :meth:`!__del__` methods are executed is arbitrary. " "You can run :func:`gc.collect` to force a collection, but there *are* " "pathological cases where objects will never be collected." msgstr "" #: ../../faq/programming.rst:1803 msgid "" "Despite the cycle collector, it's still a good idea to define an explicit " "``close()`` method on objects to be called whenever you're done with them. " "The ``close()`` method can then remove attributes that refer to subobjects. " "Don't call :meth:`!__del__` directly -- :meth:`!__del__` should call " "``close()`` and ``close()`` should make sure that it can be called more than " "once for the same object." msgstr "" #: ../../faq/programming.rst:1810 msgid "" "Another way to avoid cyclical references is to use the :mod:`weakref` " "module, which allows you to point to objects without incrementing their " "reference count. Tree data structures, for instance, should use weak " "references for their parent and sibling references (if they need them!)." msgstr "" #: ../../faq/programming.rst:1823 msgid "" "Finally, if your :meth:`!__del__` method raises an exception, a warning " "message is printed to :data:`sys.stderr`." msgstr "" #: ../../faq/programming.rst:1828 msgid "How do I get a list of all instances of a given class?" msgstr "" #: ../../faq/programming.rst:1830 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1836 msgid "Why does the result of ``id()`` appear to be not unique?" msgstr "" #: ../../faq/programming.rst:1838 msgid "" "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:" msgstr "" #: ../../faq/programming.rst:1849 msgid "" "The two ids belong to different integer objects that are created before, and " "deleted immediately after execution of the ``id()`` call. To be sure that " "objects whose id you want to examine are still alive, create another " "reference to the object:" msgstr "" #: ../../faq/programming.rst:1864 msgid "When can I rely on identity tests with the *is* operator?" msgstr "" #: ../../faq/programming.rst:1866 msgid "" "The ``is`` operator tests for object identity. The test ``a is b`` is " "equivalent to ``id(a) == id(b)``." msgstr "" #: ../../faq/programming.rst:1869 msgid "" "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``." msgstr "" #: ../../faq/programming.rst:1874 msgid "" "However, identity tests can *only* be substituted for equality tests when " "object identity is assured. Generally, there are three circumstances where " "identity is guaranteed:" msgstr "" #: ../../faq/programming.rst:1878 msgid "" "Assignments create new names but do not change object identity. After the " "assignment ``new = old``, it is guaranteed that ``new is old``." msgstr "" #: ../../faq/programming.rst:1881 msgid "" "Putting an object in a container that stores object references does not " "change object identity. After the list assignment ``s[0] = x``, it is " "guaranteed that ``s[0] is x``." msgstr "" #: ../../faq/programming.rst:1885 msgid "" "If an object is a singleton, it means that only one instance of that object " "can exist. After the assignments ``a = None`` and ``b = None``, it is " "guaranteed that ``a is b`` because ``None`` is a singleton." msgstr "" #: ../../faq/programming.rst:1889 msgid "" "In most other circumstances, identity tests are inadvisable and equality " "tests are preferred. In particular, identity tests should not be used to " "check constants such as :class:`int` and :class:`str` which aren't " "guaranteed to be singletons::" msgstr "" #: ../../faq/programming.rst:1894 msgid "" ">>> a = 10_000_000\n" ">>> b = 5_000_000\n" ">>> c = b + 5_000_000\n" ">>> a is c\n" "False\n" "\n" ">>> a = 'Python'\n" ">>> b = 'Py'\n" ">>> c = b + 'thon'\n" ">>> a is c\n" "False" msgstr "" #: ../../faq/programming.rst:1906 msgid "Likewise, new instances of mutable containers are never identical::" msgstr "" #: ../../faq/programming.rst:1908 msgid "" ">>> a = []\n" ">>> b = []\n" ">>> a is b\n" "False" msgstr "" #: ../../faq/programming.rst:1913 msgid "" "In the standard library code, you will see several common patterns for " "correctly using identity tests:" msgstr "" #: ../../faq/programming.rst:1916 msgid "" "As recommended by :pep:`8`, an identity test is the preferred way to check " "for ``None``. This reads like plain English in code and avoids confusion " "with other objects that may have boolean values that evaluate to false." msgstr "" #: ../../faq/programming.rst:1920 msgid "" "Detecting optional arguments can be tricky when ``None`` is a valid input " "value. In those situations, you can create a singleton sentinel object " "guaranteed to be distinct from other objects. For example, here is how to " "implement a method that behaves like :meth:`dict.pop`:" msgstr "" #: ../../faq/programming.rst:1925 msgid "" "_sentinel = sentinel('_sentinel')\n" "\n" "def pop(self, key, default=_sentinel):\n" " if key in self:\n" " value = self[key]\n" " del self[key]\n" " return value\n" " if default is _sentinel:\n" " raise KeyError(key)\n" " return default" msgstr "" #: ../../faq/programming.rst:1938 msgid "" "Container implementations sometimes need to augment equality tests with " "identity tests. This prevents the code from being confused by objects such " "as ``float('NaN')`` that are not equal to themselves." msgstr "" #: ../../faq/programming.rst:1942 msgid "" "For example, here is the implementation of :meth:`!collections.abc.Sequence." "__contains__`::" msgstr "" #: ../../faq/programming.rst:1945 msgid "" "def __contains__(self, value):\n" " for v in self:\n" " if v is value or v == value:\n" " return True\n" " return False" msgstr "" #: ../../faq/programming.rst:1953 msgid "" "How can a subclass control what data is stored in an immutable instance?" msgstr "" #: ../../faq/programming.rst:1955 msgid "" "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." msgstr "" #: ../../faq/programming.rst:1960 msgid "" "All of these immutable classes have a different signature than their parent " "class:" msgstr "" #: ../../faq/programming.rst:1963 msgid "" "import datetime as dt\n" "\n" "class FirstOfMonthDate(dt.date):\n" " \"Always choose the first day of the month\"\n" " def __new__(cls, year, month, day):\n" " return super().__new__(cls, year, month, 1)\n" "\n" "class NamedInt(int):\n" " \"Allow text names for some numbers\"\n" " xlat = {'zero': 0, 'one': 1, 'ten': 10}\n" " def __new__(cls, value):\n" " value = cls.xlat.get(value, value)\n" " return super().__new__(cls, value)\n" "\n" "class TitleStr(str):\n" " \"Convert str to name suitable for a URL path\"\n" " def __new__(cls, s):\n" " s = s.lower().replace(' ', '-')\n" " s = ''.join([c for c in s if c.isalnum() or c == '-'])\n" " return super().__new__(cls, s)" msgstr "" #: ../../faq/programming.rst:1986 msgid "The classes can be used like this:" msgstr "" #: ../../faq/programming.rst:1988 msgid "" ">>> FirstOfMonthDate(2012, 2, 14)\n" "FirstOfMonthDate(2012, 2, 1)\n" ">>> NamedInt('ten')\n" "10\n" ">>> NamedInt(20)\n" "20\n" ">>> TitleStr('Blog: Why Python Rocks')\n" "'blog-why-python-rocks'" msgstr "" #: ../../faq/programming.rst:2003 msgid "How do I cache method calls?" msgstr "" #: ../../faq/programming.rst:2005 msgid "" "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." msgstr "" #: ../../faq/programming.rst:2010 msgid "" "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." msgstr "" #: ../../faq/programming.rst:2014 msgid "" "The advantage is that when an instance is no longer used, the cached method " "result will be released right away. The disadvantage is that if instances " "accumulate, so too will the accumulated method results. They can grow " "without bound." msgstr "" #: ../../faq/programming.rst:2019 msgid "" "The ``lru_cache`` approach works with methods that have :term:`hashable` " "arguments. It creates a reference to the instance unless special efforts " "are made to pass in weak references." msgstr "" #: ../../faq/programming.rst:2023 msgid "" "The advantage of the least recently used algorithm is that the cache is " "bounded by the specified *maxsize*. The disadvantage is that instances are " "kept alive until they age out of the cache or until the cache is cleared." msgstr "" #: ../../faq/programming.rst:2028 msgid "This example shows the various techniques::" msgstr "" #: ../../faq/programming.rst:2030 msgid "" "class Weather:\n" " \"Lookup weather information on a government website\"\n" "\n" " def __init__(self, station_id):\n" " self._station_id = station_id\n" " # The _station_id is private and immutable\n" "\n" " def current_temperature(self):\n" " \"Latest hourly observation\"\n" " # Do not cache this because old results\n" " # can be out of date.\n" "\n" " @cached_property\n" " def location(self):\n" " \"Return the longitude/latitude coordinates of the station\"\n" " # Result only depends on the station_id\n" "\n" " @lru_cache(maxsize=20)\n" " def historic_rainfall(self, date, units='mm'):\n" " \"Rainfall on a given date\"\n" " # Depends on the station_id, date, and units." msgstr "" #: ../../faq/programming.rst:2052 msgid "" "The above example assumes that the *station_id* never changes. If the " "relevant instance attributes are mutable, the ``cached_property`` approach " "can't be made to work because it cannot detect changes to the attributes." msgstr "" #: ../../faq/programming.rst:2057 msgid "" "To make the ``lru_cache`` approach work when the *station_id* is mutable, " "the class needs to define the :meth:`~object.__eq__` and :meth:`~object." "__hash__` methods so that the cache can detect relevant attribute updates::" msgstr "" #: ../../faq/programming.rst:2061 msgid "" "class Weather:\n" " \"Example with a mutable station identifier\"\n" "\n" " def __init__(self, station_id):\n" " self.station_id = station_id\n" "\n" " def change_station(self, station_id):\n" " self.station_id = station_id\n" "\n" " def __eq__(self, other):\n" " return self.station_id == other.station_id\n" "\n" " def __hash__(self):\n" " return hash(self.station_id)\n" "\n" " @lru_cache(maxsize=20)\n" " def historic_rainfall(self, date, units='cm'):\n" " 'Rainfall on a given date'\n" " # Depends on the station_id, date, and units." msgstr "" #: ../../faq/programming.rst:2083 msgid "Modules" msgstr "" #: ../../faq/programming.rst:2086 msgid "How do I create a .pyc file?" msgstr "" #: ../../faq/programming.rst:2088 msgid "" "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.)" msgstr "" #: ../../faq/programming.rst:2096 msgid "" "One reason that a ``.pyc`` file may not be created is a permissions problem " "with the directory containing the source file, meaning that the " "``__pycache__`` subdirectory cannot be created. This can happen, for " "example, if you develop as one user but run as another, such as if you are " "testing with a web server." msgstr "" #: ../../faq/programming.rst:2101 msgid "" "Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, " "creation of a .pyc file is automatic if you're importing a module and Python " "has the ability (permissions, free space, and so on) to create a " "``__pycache__`` subdirectory and write the compiled module to that " "subdirectory." msgstr "" #: ../../faq/programming.rst:2106 msgid "" "Running Python on a top-level script is not considered an import and no ``." "pyc`` will be created. For example, if you have a top-level module ``foo." "py`` that imports another module ``xyz.py``, when you run ``foo`` (by typing " "``python foo.py`` as a shell command), a ``.pyc`` will be created for " "``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created " "for ``foo`` since ``foo.py`` isn't being imported." msgstr "" #: ../../faq/programming.rst:2113 msgid "" "If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a ``." "pyc`` file for a module that is not imported -- you can, using the :mod:" "`py_compile` and :mod:`compileall` modules." msgstr "" #: ../../faq/programming.rst:2117 msgid "" "The :mod:`py_compile` module can manually compile any module. One way is to " "use the ``compile()`` function in that module interactively::" msgstr "" #: ../../faq/programming.rst:2120 msgid "" ">>> import py_compile\n" ">>> py_compile.compile('foo.py')" msgstr "" #: ../../faq/programming.rst:2123 msgid "" "This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same " "location as ``foo.py`` (or you can override that with the optional parameter " "*cfile*)." msgstr "" #: ../../faq/programming.rst:2127 msgid "" "You can also automatically compile all files in a directory or directories " "using the :mod:`compileall` module. You can do it from the shell prompt by " "running ``compileall.py`` and providing the path of a directory containing " "Python files to compile::" msgstr "" #: ../../faq/programming.rst:2132 msgid "python -m compileall ." msgstr "" #: ../../faq/programming.rst:2136 msgid "How do I find the current module name?" msgstr "" #: ../../faq/programming.rst:2138 msgid "" "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__``::" msgstr "" #: ../../faq/programming.rst:2144 msgid "" "def main():\n" " print('Running test...')\n" " ...\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../faq/programming.rst:2153 msgid "How can I have modules that mutually import each other?" msgstr "" #: ../../faq/programming.rst:2155 msgid "Suppose you have the following modules:" msgstr "" #: ../../faq/programming.rst:2157 msgid ":file:`foo.py`::" msgstr "" #: ../../faq/programming.rst:2159 msgid "" "from bar import bar_var\n" "foo_var = 1" msgstr "" #: ../../faq/programming.rst:2162 msgid ":file:`bar.py`::" msgstr "" #: ../../faq/programming.rst:2164 msgid "" "from foo import foo_var\n" "bar_var = 2" msgstr "" #: ../../faq/programming.rst:2167 msgid "The problem is that the interpreter will perform the following steps:" msgstr "" #: ../../faq/programming.rst:2169 msgid "main imports ``foo``" msgstr "" #: ../../faq/programming.rst:2170 msgid "Empty globals for ``foo`` are created" msgstr "" #: ../../faq/programming.rst:2171 msgid "``foo`` is compiled and starts executing" msgstr "" #: ../../faq/programming.rst:2172 msgid "``foo`` imports ``bar``" msgstr "" #: ../../faq/programming.rst:2173 msgid "Empty globals for ``bar`` are created" msgstr "" #: ../../faq/programming.rst:2174 msgid "``bar`` is compiled and starts executing" msgstr "" #: ../../faq/programming.rst:2175 msgid "" "``bar`` imports ``foo`` (which is a no-op since there already is a module " "named ``foo``)" msgstr "" #: ../../faq/programming.rst:2176 msgid "" "The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set " "``bar.foo_var = foo.foo_var``" msgstr "" #: ../../faq/programming.rst:2178 msgid "" "The last step fails, because Python isn't done with interpreting ``foo`` yet " "and the global symbol dictionary for ``foo`` is still empty." msgstr "" #: ../../faq/programming.rst:2181 msgid "" "The same thing happens when you use ``import foo``, and then try to access " "``foo.foo_var`` in global code." msgstr "" #: ../../faq/programming.rst:2184 msgid "There are (at least) three possible workarounds for this problem." msgstr "" #: ../../faq/programming.rst:2186 msgid "" "Guido van Rossum recommends avoiding all uses of ``from import ..." "``, and placing all code inside functions. Initializations of global " "variables and class variables should use constants or built-in functions " "only. This means everything from an imported module is referenced as " "``.``." msgstr "" #: ../../faq/programming.rst:2191 msgid "" "Jim Roskind suggests performing steps in the following order in each module:" msgstr "" #: ../../faq/programming.rst:2193 msgid "" "exports (globals, functions, and classes that don't need imported base " "classes)" msgstr "" #: ../../faq/programming.rst:2195 msgid "``import`` statements" msgstr "" #: ../../faq/programming.rst:2196 msgid "" "active code (including globals that are initialized from imported values)." msgstr "" #: ../../faq/programming.rst:2198 msgid "" "Van Rossum doesn't like this approach much because the imports appear in a " "strange place, but it does work." msgstr "" #: ../../faq/programming.rst:2201 msgid "" "Matthias Urlichs recommends restructuring your code so that the recursive " "import is not necessary in the first place." msgstr "" #: ../../faq/programming.rst:2204 msgid "These solutions are not mutually exclusive." msgstr "" #: ../../faq/programming.rst:2208 msgid "__import__('x.y.z') returns ; how do I get z?" msgstr "" #: ../../faq/programming.rst:2210 msgid "" "Consider using the convenience function :func:`~importlib.import_module` " "from :mod:`importlib` instead::" msgstr "" #: ../../faq/programming.rst:2213 msgid "z = importlib.import_module('x.y.z')" msgstr "" #: ../../faq/programming.rst:2217 msgid "" "When I edit an imported module and reimport it, the changes don't show up. " "Why does this happen?" msgstr "" #: ../../faq/programming.rst:2219 msgid "" "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::" msgstr "" #: ../../faq/programming.rst:2225 msgid "" "import importlib\n" "import modname\n" "importlib.reload(modname)" msgstr "" #: ../../faq/programming.rst:2229 msgid "" "Warning: this technique is not 100% fool-proof. In particular, modules " "containing statements like::" msgstr "" #: ../../faq/programming.rst:2232 msgid "from modname import some_objects" msgstr "" #: ../../faq/programming.rst:2234 msgid "" "will continue to work with the old version of the imported objects. If the " "module contains class definitions, existing class instances will *not* be " "updated to use the new class definition. This can result in the following " "paradoxical behaviour::" msgstr "" #: ../../faq/programming.rst:2239 msgid "" ">>> import importlib\n" ">>> import cls\n" ">>> c = cls.C() # Create an instance of C\n" ">>> importlib.reload(cls)\n" "\n" ">>> isinstance(c, cls.C) # isinstance is false?!?\n" "False" msgstr "" #: ../../faq/programming.rst:2247 msgid "" "The nature of the problem is made clear if you print out the \"identity\" of " "the class objects::" msgstr "" #: ../../faq/programming.rst:2250 msgid "" ">>> hex(id(c.__class__))\n" "'0x7352a0'\n" ">>> hex(id(cls.C))\n" "'0x4198d0'" msgstr "" #: ../../faq/programming.rst:409 msgid "argument" msgstr "" #: ../../faq/programming.rst:409 msgid "difference from parameter" msgstr "" #: ../../faq/programming.rst:409 msgid "parameter" msgstr "" #: ../../faq/programming.rst:409 msgid "difference from argument" msgstr ""