Teks sumber — English
Terjemahan — Bahasa Indonesia
:func:`callable`
:func:`callable`
Return an :term:`asynchronous iterator` for an :term:`asynchronous iterable`. Equivalent to calling ``x.__aiter__()``.
This calls the :meth:`~object.__anext__` method of *async_iterator*, returning an :term:`awaitable`. Awaiting this returns the next value of the iterator. If *default* is given, it is returned if the iterator is exhausted, otherwise :exc:`StopAsyncIteration` is raised.
This function drops you into the debugger at the call site. Specifically, it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight through. By default, ``sys.breakpointhook()`` calls :func:`pdb.set_trace` expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly import :mod:`pdb` or type as much code to enter the debugger. However, :func:`sys.breakpointhook` can be set to some other function and :func:`breakpoint` will automatically call that, allowing you to drop into the debugger of choice. If :func:`sys.breakpointhook` is not accessible, this function will raise :exc:`RuntimeError`.
Return :const:`True` if the *object* argument appears callable, :const:`False` if not. If this returns ``True``, it is still possible that a call fails, but if it is ``False``, calling *object* will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a :meth:`~object.__call__` method.
A class method can be called either on the class (such as ``C.f()``) or on an instance (such as ``C().f()``). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Metode kelas dapat dipanggil baik pada kelas (seperti ``C.f()``) atau pada *instance* (seperti ``C().f()``). Instance diabaikan kecuali untuk kelasnya. Jika metode kelas dipanggil untuk kelas turunan, objek kelas turunan dilewatkan sebagai argumen pertama yang tersirat.
The optional arguments *flags* and *dont_inherit* control which :ref:`compiler options <ast-compiler-flags>` should be activated and which :ref:`future features <future>` should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling :func:`compile`. If the *flags* argument is given and *dont_inherit* is not (or is zero) then the compiler options and the future statements specified by the *flags* argument are used in addition to those that would be used anyway. If *dont_inherit* is a non-zero integer then the *flags* argument is it -- the flags (future features and compiler options) in the surrounding code are ignored.
If the object has a method named :meth:`~object.__dir__`, this method will be called and must return the list of attributes. This allows objects that implement a custom :func:`~object.__getattr__` or :func:`~object.__getattribute__` function to customize the way :func:`dir` reports their attributes.
The resulting list is sorted alphabetically. For example:
Daftar yang dihasilkan diurutkan berdasarkan abjad. Sebagai contoh:
This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.
The *source* argument is parsed and evaluated as a Python expression (technically speaking, an :ref:`expression list <exprlists>`) using the *globals* and *locals* mappings as global and local namespace. If the *globals* dictionary is present and does not contain a value for the key ``__builtins__``, a reference to the dictionary of the built-in module :mod:`builtins` is inserted under that key before *source* is parsed. Overriding ``__builtins__`` can be used to restrict or change the available names, but this is **not** a security mechanism: the executed code can still access all builtins. If the *locals* mapping is omitted it defaults to the *globals* dictionary. If both mappings are omitted, the source is executed with the *globals* and *locals* in the environment where :func:`eval` is called. Note, *eval()* will only have access to the :term:`nested scopes <nested scope>` (non-locals) in the enclosing environment if they are already referenced in the scope that is calling :func:`eval` (e.g. via a :keyword:`nonlocal` statement).
The default *format_spec* is an empty string which usually gives the same effect as calling :func:`str(value) <str>`.
Default *format_spec* adalah string kosong yang biasanya memberikan efek yang sama dengan memanggil :func:`str(value) <str>`.
A call to ``format(value, format_spec)`` is translated to ``type(value).__format__(value, format_spec)`` which bypasses the instance dictionary when searching for the value's :meth:`~object.__format__` method. A :exc:`TypeError` exception is raised if the method search reaches :mod:`object` and the *format_spec* is non-empty, or if either the *format_spec* or the return value are not strings.
Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.
The arguments are an object and a string. The result is ``True`` if the string is the name of one of the object's attributes, ``False`` if not. (This is implemented by calling ``getattr(object, name)`` and seeing whether it raises an :exc:`AttributeError` or not.)
Argumen adalah objek dan string. Hasilnya adalah ``True`` jika string adalah nama salah satu atribut objek, ``False`` jika tidak. (Ini diimplementasikan dengan memanggil ``getattr(object, name)`` dan melihat apakah itu memunculkan :exc:`AttributeError` atau tidak.)
Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported signatures for callables are now more comprehensive and consistent.
Perubahan ke :mod:`pydoc` dan :mod:`inspect` berarti bahwa tanda tangan *signatures* yang dilaporkan untuk *callables* sekarang lebih komprehensif dan konsisten.
If *base* is not an instance of :class:`int` and the *base* object has a :meth:`base.__index__ <object.__index__>` method, that method is called to obtain an integer for the base. Previous versions used :meth:`base.__int__ <object.__int__>` instead of :meth:`base.__index__ <object.__index__>`.
Jika *base* bukan turunan dari :class:`int` dan objek *base* memiliki metode :meth:`base.__index__ <object.__index__>`, metode itu dipanggil untuk mendapatkan integer untuk basis. Versi sebelumnya menggunakan <object.__int__>` alih-alih :meth: `base.__index__ <object.__index__>`.
Return an :term:`iterator` object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, the single argument must be a collection object which supports the :term:`iterable` protocol (the :meth:`~object.__iter__` method), or it must support the sequence protocol (the :meth:`~object.__getitem__` method with integer arguments starting at ``0``). If it does not support either of those protocols, :exc:`TypeError` is raised. If the second argument, *sentinel*, is given, then the first argument must be a callable object. The iterator created in this case will call *callable* with no arguments for each call to its :meth:`~iterator.__next__` method; if the value returned is equal to *sentinel*, :exc:`StopIteration` will be raised, otherwise the value will be returned.
When using ``exec()`` or ``eval()`` with separate local and global arguments, it returns the local namespace passed in to the function call.
In all of the above cases, each call to ``locals()`` in a given frame of execution will return the *same* mapping object. Changes made through the mapping object returned from ``locals()`` will be visible as assigned, reassigned, or deleted local variables, and assigning, reassigning, or deleting local variables will immediately affect the contents of the returned mapping object.
In an :term:`optimized scope` (including functions, generators, and coroutines), each call to ``locals()`` instead returns a fresh dictionary containing the current bindings of the function's local variables and any nonlocal cell references. In this case, name binding changes made via the returned dict are *not* written back to the corresponding local variables or nonlocal cell references, and assigning, reassigning, or deleting local variables and nonlocal cell references does *not* affect the contents of previously returned dictionaries.
Calling ``locals()`` as part of a comprehension in a function, generator, or coroutine is equivalent to calling it in the containing scope, except that the comprehension's initialised iteration variables will be included. In other scopes, it behaves as if the comprehension were running as a nested function.
Calling ``locals()`` as part of a generator expression is equivalent to calling it in a nested generator function.
Retrieve the next item from the :term:`iterator` by calling its :meth:`~iterator.__next__` method. If *default* is given, it is returned if the iterator is :term:`exhausted`, otherwise :exc:`StopIteration` is raised.
This is the ultimate base class of all other classes. It has methods that are common to all instances of Python classes. When the constructor is called, it returns a new featureless object. The constructor does not accept any arguments.
*mode* is an optional string that specifies the mode in which the file is opened. It defaults to ``'r'`` which means open for reading in text mode. Other common values are ``'w'`` for writing (truncating the file if it already exists), ``'x'`` for exclusive creation, and ``'a'`` for appending (which on *some* Unix systems, means that *all* writes append to the end of the file regardless of the current seek position). In text mode, if *encoding* is not specified, UTF-8 is used by default; if :ref:`Python UTF-8 Mode <utf8-mode>` is disabled, :func:`locale.getencoding` is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave *encoding* unspecified.) The available modes are:
Binary files are buffered in fixed-size chunks; the size of the buffer is ``max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE)`` when the device block size is available. On most systems, the buffer will typically be 128 kilobytes long.
When reading input from the stream, if *newline* is ``None``, universal newlines mode is enabled. Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these are translated into ``'\n'`` before being returned to the caller. If it is ``''``, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
Saat membaca masukan dari aliran *stream*, jika *newline* adalah ``None``, mode universal baris baru diaktifkan. Baris dalam masukan dapat diakhiri dengan ``'\n'``, ``'\r'``, atau ``'\r\n'``, dan ini diterjemahkan ke dalam ``'\n'`` sebelum dikembalikan ke pemanggil. Jika ``''``, mode baris baru universal diaktifkan, tetapi akhir baris dikembalikan ke pemanggil yang tidak diterjemahkan. Jika memiliki salah satu nilai legal lainnya, jalur masukan hanya diakhiri oleh string yang diberikan, dan akhir baris dikembalikan ke pemanggil yang tidak diterjemahkan.
A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing :mod:`os.open` as *opener* results in functionality similar to passing ``None``).
Pembuka khusus dapat digunakan dengan melewatkan *callable* sebagai *opener*. Deskriptor berkas yang mendasari untuk objek berkas kemudian diperoleh dengan memanggil *opener* dengan (*file*, *flags*). *opener* harus mengembalikan deskriptor berkas terbuka (lewat :mod:`os.open` sebagai *opener* menghasilkan fungsionalitas yang mirip dengan melewatkan ``None``).
The type of :term:`file object` returned by the :func:`open` function depends on the mode. When :func:`open` is used to open a file in a text mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of :class:`io.TextIOBase` (specifically :class:`io.TextIOWrapper`). When used to open a file in a binary mode with buffering, the returned class is a subclass of :class:`io.BufferedIOBase`. The exact class varies: in read binary mode, it returns an :class:`io.BufferedReader`; in write binary and append binary modes, it returns an :class:`io.BufferedWriter`, and in read/write mode, it returns an :class:`io.BufferedRandom`. When buffering is disabled, the raw stream, a subclass of :class:`io.RawIOBase`, :class:`io.FileIO`, is returned.
Tipe :term:`file object` yang dikembalikan oleh fungsi :func:`open` tergantung pada mode. Ketika :func:`open` digunakan untuk membuka berkas dalam mode teks (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, dll.), ia mengembalikan subkelas dari :class:`io.TextIOBase` (khusus :class:`io.TextIOWrapper`). Ketika digunakan untuk membuka file dalam mode biner dengan *buffering*, kelas yang dikembalikan adalah subkelas dari :class:`io.BufferedIOBase`. Kelas yang tepat bervariasi: dalam mode baca biner, ia mengembalikan :class:`io.BufferedReader`; dalam mode tulis biner dan *append* biner, ia mengembalikan sebuah :class:`io.BufferedWriter`, dan dalam mode baca/tulis, ia mengembalikan sebuah :class:`io.BufferedRandom`. Ketika *buffering* dinonaktifkan, aliran tak diproses *raw stream*, subkelas dari :class:`io.RawIOBase`, :class:`io.FileIO`, dikembalikan.
The ``mode`` and ``flags`` arguments may have been modified or inferred from the original call.
Argumen ``mode`` dan ``flags`` mungkin telah dimodifikasi atau disimpulkan dari pemanggilan asli.
If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
Jika panggilan sistem terganggu dan penangan sinyal tidak menimbulkan pengecualian, fungsi sekarang mencoba ulang panggilan sistem alih-alih menimbulkan pengecualian :exc:`InterruptedError` (lihat :pep:`475` untuk penjelasannya).
The sort algorithm uses only ``<`` comparisons between items. While defining an :meth:`~object.__lt__` method will suffice for sorting, :PEP:`8` recommends that all six :ref:`rich comparisons <comparisons>` be implemented. This will help avoid bugs when using the same data with other ordering tools such as :func:`max` that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call the reflected :meth:`~object.__gt__` method.
A static method can be called either on the class (such as ``C.f()``) or on an instance (such as ``C().f()``). Moreover, the static method :term:`descriptor` is also callable, so it can be used in the class definition (such as ``f()``).
Like all decorators, it is also possible to call ``staticmethod`` as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom::
Seperti semua dekorator, dimungkinkan juga untuk memanggil ``staticmethod`` sebagai fungsi biasa dan melakukan sesuatu dengan hasilnya. Ini diperlukan dalam beberapa kasus di mana Anda memerlukan referensi ke fungsi dari badan kelas dan Anda ingin menghindari transformasi otomatis ke metode *instance*. Untuk kasus ini, gunakan idiom ini::
Static methods now inherit the method attributes (:attr:`~function.__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :attr:`~function.__doc__` and :attr:`~function.__annotations__`), have a new ``__wrapped__`` attribute, and are now callable as regular functions.
For some use cases, there are good alternatives to :func:`sum`. The preferred, fast way to concatenate a sequence of strings is by calling ``''.join(sequence)``. To add floating-point values with extended precision, see :func:`math.fsum`\. To concatenate a series of iterables, consider using :func:`itertools.chain`.
Return a proxy object that delegates method calls to a parent or sibling class of *type*. This is useful for accessing inherited methods that have been overridden in a class.
Kembalikan objek proxy yang mendelegasikan panggilan metode ke kelas orang tua atau saudara dari *type*. Ini berguna untuk mengakses metode yang diwariskan yang telah ditimpa di suatu kelas.
When called directly within an ordinary method of a class, both arguments may be omitted ("zero-argument :func:`!super`"). In this case, *type* will be the enclosing class, and *object_or_type* will be the first argument of the immediately enclosing function (typically ``self``). Zero-argument :func:`!super` will not work as expected within nested functions, including generator expressions, which implicitly create nested functions.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).
For both use cases, a typical superclass call looks like this::
Untuk kedua kasus penggunaan, pemanggilan *superclass* yang khas terlihat seperti ini::
In addition to method lookups, :func:`super` also works for attribute lookups. One possible use case for this is calling :term:`descriptors <descriptor>` in a parent or sibling class.
Selain pencarian metode, :func:`super` juga berfungsi untuk pencarian atribut. Salah satu kemungkinan kasus penggunaan ini adalah pemanggilan :term:`descriptors <descriptor>` di kelas induk atau saudara kandung.
Unlike a :keyword:`class` statement, the three argument form does not call the metaclass ``__prepare__`` method (see :ref:`prepare`). Use :func:`types.new_class` to dynamically create a class using the appropriate metaclass.
The result of calling this function without an argument has been updated as described for the :func:`locals` builtin.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using ``zip(*[iter(s)]*n, strict=True)``. This repeats the *same* iterator ``n`` times so that each output tuple has the result of ``n`` calls to the iterator. This has the effect of dividing the input into n-length chunks.
The statement ``import spam.ham`` results in this call::
Pernyataan ``import spam.ham`` menghasilkan panggilan ini::