Home Blog
en|ru

Шпаргалка по python

Шпаргалка по Python

Встроенные функции

  • abs(x, /)
  • aiter(async_iterable, /) Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().
  • all(iterable, /) Return True if all elements of the iterable are true (or if the iterable is empty).
  • awaitable anext(async_iterator, /)
  • awaitable anext(async_iterator, default, /) When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted. This is the async variant of the next() builtin, and behaves similarly.
  • any(iterable, /) Return True if any element of the iterable is true. If the iterable is empty, return False.
  • ascii(object, /) As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that returned by repr() in Python 2.
  • bin(x, /) Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:
      bin(3)
      '0b11'
    
  • class bool(x=False, /)
  • breakpoint(*args, **kws) This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice. If sys.breakpointhook() is not accessible, this function will raise RuntimeError.
  • class bytearray(source=b’’)
  • class bytearray(source, encoding)
  • class bytearray(source, encoding, errors) Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.
  • class bytes(source=b’’)
  • class bytes(source, encoding)
  • class bytes(source, encoding, errors) Return a new “bytes” object which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
  • callable(object, /) Return True if the object argument appears callable, 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 __call__() method.
  • chr(i, /) Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string ‘a’, while chr(8364) returns the string ‘€’. This is the inverse of ord().
  • @classmethod Transform a method into a class method.
  • compile(source, filename, mode, flags=0, dont_inherit=False, optimize=- 1) Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.
  • class complex(real=0, imag=0)
  • class complex(string, /) Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.
  • delattr(object, name, /) This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, ‘foobar’) is equivalent to del x.foobar. name need not be a Python identifier (see setattr()).
  • class dict(**kwarg)
  • class dict(mapping, /, **kwarg)
  • class dict(iterable, /, **kwarg) Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.
  • dir()
  • dir(object, /) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
  • eval(expression, /, globals=None, locals=None) The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
  • filter(function, iterable, /) Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
  • class float(x=0.0, /) Return a floating point number constructed from a number or string x.
  • format(value, format_spec=’’, /) Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.
  • class frozenset(iterable=set(), /) Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.
  • getattr(object, name, /)
  • getattr(object, name, default, /) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. name need not be a Python identifier (see setattr()).
  • globals() 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.
  • hasattr(object, name, /) 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 AttributeError or not.)
  • hash(object, /) Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
  • help()
  • help(request) Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
  • hex(x, /) Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:
  • id(object, /) Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
  • input()
  • input(prompt, /) If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:
  • class int(x=0, /)
  • class int(x, /, base=10) Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.
  • isinstance(object, classinfo, /) Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised. TypeError may not be raised for an invalid type if an earlier check succeeds.
  • issubclass(class, classinfo, /) Return True if class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Union Type, in which case return True if class is a subclass of any entry in classinfo. In any other case, a TypeError exception is raised.
  • iter(object, /)
  • iter(object, sentinel, /) Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
  • len(s, /) Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
  • class list
  • class list(iterable, /) Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.
  • locals() Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.
  • map(function, iterable, /, *iterables) Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().
  • max(iterable, /, *, key=None)
  • max(iterable, /, *, default, key=None)
  • max(arg1, arg2, /, *args, key=None) Return the largest item in an iterable or the largest of two or more arguments.
  • class memoryview(object) Return a “memory view” object created from the given argument. See Memory Views for more information.
  • min(iterable, /, *, key=None)
  • min(iterable, /, *, default, key=None)
  • min(arg1, arg2, /, *args, key=None) Return the smallest item in an iterable or the smallest of two or more arguments.
  • next(iterator, /)
  • next(iterator, default, /) Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
  • class object Return a new featureless object. object is a base for all classes. It has methods that are common to all instances of Python classes. This function does not accept any arguments.
  • oct(x, /) Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:
  • open(file, mode=’r’, buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function. The available modes are: ‘r’, ‘w’, ‘x’ (exclusive, fail if exists), ‘a’, ‘b’ (binary), ‘t’ (text), ‘+’ (rw)
  • ord(c, /) Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord(‘a’) returns the integer 97 and ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr().
  • pow(base, exp, mod=None)
  • print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
  • class property(fget=None, fset=None, fdel=None, doc=None) Return a property attribute.
    class C:
        def \_\_init\_\_(self):
            self._x = None

        def getx(self):
            return self.\_x

        def setx(self, value):
            self.\_x = value

        def delx(self):
            del self._x
        x = property(getx, setx, delx, "I'm the 'x' property.")
  • class range(stop, /)
  • class range(start, stop, step=1, /) Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.
  • repr(object, /) Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(); otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. If sys.displayhook() is not accessible, this function will raise RuntimeError.
  • reversed(seq, /) Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
  • round(number, ndigits=None)
  • class set
  • class set(iterable, /) Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.
  • setattr(object, name, value, /) This is the counterpart of getattr(). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123.
  • class slice(stop, /)
  • class slice(start, stop, step=1, /) Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
  • sorted(iterable, /, *, key=None, reverse=False) Return a new sorted list from the items in iterable. Has two optional arguments which must be specified as keyword arguments.
  • @staticmethod Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom:
    class C:
        @staticmethod
        def f(arg1, arg2, ...): ...
  • class str(object=’’)
  • class str(object=b’’, encoding=’utf-8’, errors=’strict’) Return a str version of object. See str() for details. str is the built-in string class. For general information about strings, see Text Sequence Type — str.
  • sum(iterable, /, start=0) Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.
  • class super
  • class super(type, object_or_type=None, /) 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.
  • class tuple
  • class tuple(iterable, /) Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.
  • class type(object, /)
  • class type(name, bases, dict, /, **kwds) With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
  • vars()
  • vars(object, /) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
  • zip(*iterables, strict=False) Iterate over several iterables in parallel, producing tuples with an item from each one.
    for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
        print(item)
    (1, 'sugar')
    (2, 'spice')
    (3, 'everything nice')
en|ru
Home Blog
Nickname sergzhum is registered!