Glossário¶
>>>
O prompt Python padrão do shell interativo. Muitas vezes visto em exemplos de código que podem ser executados de forma interativa no interpretador.
...
O prompt padrão do shell interativo do Python ao se digitar código em um bloco indentado ou dentro de um par de delimitadores direita-esquerda .. XXX: concordam com “delimitadores direita-esquerda”? (como parênteses, colchetes ou chaves).
- 2to3
Uma ferramenta que tenta converter o código Python 2.x para o código Python 3.x, manipulando a maioria das incompatibilidades que podem ser detectadas analisando a origem e percorrendo toda a árvore de análise.
2to3 is available in the standard library as
lib2to3
; a standalone entry point is provided asTools/scripts/2to3
. See 2to3 - Tradução Automatizada de Código Python 2 para 3.- Classe Base Abstrata
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques like
hasattr()
would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized byisinstance()
andissubclass()
; see theabc
module documentation. Python comes with many built-in ABCs for data structures (in thecollections
module), numbers (in thenumbers
module), and streams (in theio
module). You can create your own ABCs with theabc
module.- Argumento
A value passed to a function (or method) when calling the function. There are two types of arguments:
argumento nomeado: um argumento precedido por um identificador (por exemplo,
nome=
) na chamada de uma função ou passada como um valor em um dicionário precedido por**
. Por exemplo,3
e5
são ambos argumentos nomeados na chamada da funçãocomplex()
a seguir:complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5})
argumento posicional: um argumento que não é um argumento nomeado. Argumentos posicionais podem aparecer no início da lista de argumentos e/ou podem ser passados com elementos de um iterável precedido por
*
. Por exemplo,3
e5
são ambos argumentos posicionais nas chamadas a seguir:complex(3, 5) complex(*(3, 5))
Argumentos são atribuídos às variáveis locais nomeadas no corpo da função. Veja Calls para as regras de atribuição. Sintaticamente, qualquer expressão pode ser usada para representar um argumento; avaliada a expressão, o valor é atribuído à variável local.
See also the parameter glossary entry and the FAQ question on the difference between arguments and parameters.
- Atributo
Um valor associado a um objeto que é referenciado pelo nome separado por um ponto. Por exemplo, se um objeto o tem um atributo a esse seria referenciado como o.a.
- BDFL
Benevolent Dictator For Life, a.k.a. Guido van Rossum, Python’s creator.
- objeto byte ou similar
An object that supports the buffer protocol, like
str
,bytearray
ormemoryview
. Bytes-like objects can be used for various operations that expect binary data, such as compression, saving to a binary file or sending over a socket. Some operations need the binary data to be mutable, in which case not all bytes-like objects can apply.- bytecode
Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in
.pyc
and.pyo
files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases.A list of bytecode instructions can be found in the documentation for the dis module.
- Classe
A template for creating user-defined objects. Class definitions normally contain method definitions which operate on instances of the class.
- classic class
Any class which does not inherit from
object
. See new-style class. Classic classes have been removed in Python 3.- Coerção
The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example,
int(3.15)
converts the floating point number to the integer3
, but in3+4.5
, each argument is of a different type (one int, one float), and both must be converted to the same type before they can be added or it will raise aTypeError
. Coercion between two operands can be performed with thecoerce
built-in function; thus,3+4.5
is equivalent to callingoperator.add(*coerce(3, 4.5))
and results inoperator.add(3.0, 4.5)
. Without coercion, all arguments of even compatible types would have to be normalized to the same value by the programmer, e.g.,float(3)+4.5
rather than just3+4.5
.- Número Complexo
An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary numbers are real multiples of the imaginary unit (the square root of
-1
), often writteni
in mathematics orj
in engineering. Python has built-in support for complex numbers, which are written with this latter notation; the imaginary part is written with aj
suffix, e.g.,3+1j
. To get access to complex equivalents of themath
module, usecmath
. Use of complex numbers is a fairly advanced mathematical feature. If you’re not aware of a need for them, it’s almost certain you can safely ignore them.- Gerenciador de Contexto
An object which controls the environment seen in a
with
statement by defining__enter__()
and__exit__()
methods. See PEP 343.- CPython
The canonical implementation of the Python programming language, as distributed on python.org. The term “CPython” is used when necessary to distinguish this implementation from others such as Jython or IronPython.
- decorator
Uma função que retorna outra função, geralmente aplicada como uma transformação de função usando a sintaxe
@wrapper
. Exemplos comuns para decoradores sãoclassmethod()
estaticmethod()
.A sintaxe do decorador é meramente um açucar-sintático, as duas definições de funções seguintes são semanticamente equivalentes:
def f(...): ... f = staticmethod(f) @staticmethod def f(...): ...
O mesmo conceito existe para as classes, mas não é comumente utilizado. Veja a documentação de function definitions e class definitions para obter mais informações sobre decoradores.
- Descriptor
Any new-style object which defines the methods
__get__()
,__set__()
, or__delete__()
. When a class attribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to get, set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor, the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of Python because they are the basis for many features including functions, methods, properties, class methods, static methods, and reference to super classes.Para obter mais informações sobre os métodos dos descritores, veja: Implementing Descriptors.
- dicionário
An associative array, where arbitrary keys are mapped to values. The keys can be any object with
__hash__()
and__eq__()
methods. Called a hash in Perl.- visualização de dicionário
The objects returned from
dict.viewkeys()
,dict.viewvalues()
, anddict.viewitems()
are called dictionary views. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. To force the dictionary view to become a full list uselist(dictview)
. See Objetos de visão de dicionário.- docstring
Uma String literal que aparece como a primeira expressão em uma classe, função ou módulo. Embora ignorado quando o pacote é executado, o mesmo é reconhecido pelo compilador e colocado no atributo
__doc__
da classe, função ou módulo que a envolve. Uma vez que está disponível através da introspecção, é o lugar canônico para a documentação do objeto.- duck-typing
A programming style which does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using
type()
orisinstance()
. (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employshasattr()
tests or EAFP programming.- EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many
try
andexcept
statements. The technique contrasts with the LBYL style common to many other languages such as C.- Expressão
A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also statements which cannot be used as expressions, such as
print
orif
. Assignments are also statements, not expressions.- extension module (módulo de extensão)
Um módulo escrito em C ou C ++, usando a API C do Python para interagir com o núcleo e com o código do usuário.
- file object (arquivo objeto)
Um objeto que expõe uma API orientada a arquivos (com métodos como
read ()
ouwrite ()
) para um recurso subjacente. Dependendo da maneira como for criado, um file object pode mediar o acesso a um arquivo real no disco ou a outro tipo de dispositivo de armazenamento ou com alguma comunicação (por exemplo, entrada/saída padrão, buffers na memória, soquetes, pipes e etc.) . Os objetos de arquivo também são chamados file-like objects ou streams.There are actually three categories of file objects: raw binary files, buffered binary files and text files. Their interfaces are defined in the
io
module. The canonical way to create a file object is by using theopen()
function.- file-like object (objeto como a um arquivo)
Um sinônimo do termo file object.
- finder
An object that tries to find the loader for a module. It must implement a method named
find_module()
. See PEP 302 for details.- floor division
Mathematical division that rounds down to nearest integer. The floor division operator is
//
. For example, the expression11 // 4
evaluates to2
in contrast to the2.75
returned by float true division. Note that(-11) // 4
is-3
because that is-2.75
rounded downward. See PEP 238.- function (função)
A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. See also parameter, method, and the Function definitions section.
- __future__
A pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. For example, the expression
11/4
currently evaluates to2
. If the module in which it is executed had enabled true division by executing:from __future__ import division
the expression
11/4
would evaluate to2.75
. By importing the__future__
module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default:>>> import __future__ >>> __future__.division _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
- garbage collection (coletor de lixo)
The process of freeing memory when it is not used anymore. Python performs garbage collection via reference counting and a cyclic garbage collector that is able to detect and break reference cycles.
- generator
A function which returns an iterator. It looks like a normal function except that it contains
yield
statements for producing a series of values usable in a for-loop or that can be retrieved one at a time with thenext()
function. Eachyield
temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation).- generator expression
An expression that returns an iterator. It looks like a normal expression followed by a
for
expression defining a loop variable, range, and an optionalif
expression. The combined expression generates values for an enclosing function:>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 285
- GIL
Veja global interpreter lock.
- global interpreter lock (bloqueio global do intérprete)
The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as
dict
) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.
Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain.
- hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()
method), and can be compared to other objects (it needs an__eq__()
or__cmp__()
method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their
id()
.- IDLE
Um Ambiente de Desenvolvimento Integrado nativo do Python. IDLE é um editor básico e um ambiente que acompanha um intérprete e é disponibilizado junto com a distribuição padrão do Python.
- immutable (imutável)
An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
- integer division
Mathematical division discarding any remainder. For example, the expression
11/4
currently evaluates to2
in contrast to the2.75
returned by float division. Also called floor division. When dividing two integers the outcome will always be another integer (having the floor function applied to it). However, if one of the operands is another numeric type (such as afloat
), the result will be coerced (see coercion) to a common type. For example, an integer divided by a float will result in a float value, possibly with a decimal fraction. Integer division can be forced by using the//
operator instead of the/
operator. See also __future__.- importing (importando)
O processo pelo qual o código Python em um módulo é disponibilizado para o código Python em outro módulo.
- importer
Um objeto que localiza e carrega um módulo; Tanto um finder e o objeto loader.
- interactive
Python has an interactive interpreter which means you can enter statements and expressions at the interpreter prompt, immediately execute them and see their results. Just launch
python
with no arguments (possibly by selecting it from your computer’s main menu). It is a very powerful way to test out new ideas or inspect modules and packages (rememberhelp(x)
).- interpreted
Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. This means that source files can be run directly without explicitly creating an executable which is then run. Interpreted languages typically have a shorter development/debug cycle than compiled ones, though their programs generally also run more slowly. See also interactive.
- iterable (Iterável)
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as
list
,str
, andtuple
) and some non-sequence types likedict
andfile
and objects of any classes you define with an__iter__()
or__getitem__()
method. Iterables can be used in afor
loop and in many other places where a sequence is needed (zip()
,map()
, …). When an iterable object is passed as an argument to the built-in functioniter()
, it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to calliter()
or deal with iterator objects yourself. Thefor
statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.- iterator (Iterador)
An object representing a stream of data. Repeated calls to the iterator’s
next()
method return successive items in the stream. When no more data are available aStopIteration
exception is raised instead. At this point, the iterator object is exhausted and any further calls to itsnext()
method just raiseStopIteration
again. Iterators are required to have an__iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as alist
) produces a fresh new iterator each time you pass it to theiter()
function or use it in afor
loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.Mais informações pode ser encontrada em Tipos de Iteração.
- key function (função chave)
A key function or collation function is a callable that returns a value used for sorting or ordering. For example,
locale.strxfrm()
is used to produce a sort key that is aware of locale specific sort conventions.A number of tools in Python accept key functions to control how elements are ordered or grouped. They include
min()
,max()
,sorted()
,list.sort()
,heapq.nsmallest()
,heapq.nlargest()
, anditertools.groupby()
.There are several ways to create a key function. For example. the
str.lower()
method can serve as a key function for case insensitive sorts. Alternatively, an ad-hoc key function can be built from alambda
expression such aslambda r: (r[0], r[2])
. Also, theoperator
module provides three key function constructors:attrgetter()
,itemgetter()
, andmethodcaller()
. See the Sorting HOW TO for examples of how to create and use key functions.- keyword argument (Argumento de Palavra-Chave)
Veja o argument.
- lambda
Uma função de linha anônima consistindo de uma única expression, que é avaliada quando a função é chamada. A sintaxe para criar uma função lambda é
lambda [parameters]: expression
- LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many
if
statements.In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code,
if key in mapping: return mapping[key]
can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.- list
Uma sequence embutida no Python. Apesar do seu nome, é mais próximo de um vetor em outras linguagens do que uma lista encadeada, como o acesso aos elementos é da ordem O(1).
- list comprehension
A compact way to process all or part of the elements in a sequence and return a list with the results.
result = ["0x%02x" % x for x in range(256) if x % 2 == 0]
generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. Theif
clause is optional. If omitted, all elements inrange(256)
are processed.- loader
An object that loads a module. It must define a method named
load_module()
. A loader is typically returned by a finder. See PEP 302 for details.- método mágico
Um sinônimo informal para um special method.
- mapping
A container object that supports arbitrary key lookups and implements the methods specified in the
Mapping
orMutableMapping
abstract base classes. Examples includedict
,collections.defaultdict
,collections.OrderedDict
andcollections.Counter
.- metaclass
The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for taking those three arguments and creating the class. Most object oriented programming languages provide a default implementation. What makes Python special is that it is possible to create custom metaclasses. Most users never need this tool, but when the need arises, metaclasses can provide powerful, elegant solutions. They have been used for logging attribute access, adding thread-safety, tracking object creation, implementing singletons, and many other tasks.
More information can be found in Customizing class creation.
- method (método)
A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called
self
). See function and nested scope.- method resolution order (ordem de resolução de método)
Method Resolution Order is the order in which base classes are searched for a member during lookup. See The Python 2.3 Method Resolution Order for details of the algorithm used by the Python interpreter since the 2.3 release.
- module (módulo)
Um objeto que serve como uma unidade organizacional de código Python. Os módulos têm um namespace contendo objetos Python arbitrários. Os módulos são carregados pelo Python através do processo de: term: importing.
Veja também package.
- MRO
Veja method resolution order.
- mutable (mutável)
Objetos mutáveis podem alterar seus valores, mantendo os respectivos
id()
. Veja também immutable.- named tuple
Any tuple-like class whose indexable elements are also accessible using named attributes (for example,
time.localtime()
returns a tuple-like object where the year is accessible either with an index such ast[0]
or with a named attribute liket.tm_year
).A named tuple can be a built-in type such as
time.struct_time
, or it can be created with a regular class definition. A full featured named tuple can also be created with the factory functioncollections.namedtuple()
. The latter approach automatically provides extra features such as a self-documenting representation likeEmployee(name='jones', title='programmer')
.- namespace
The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local, global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support modularity by preventing naming conflicts. For instance, the functions
__builtin__.open()
andos.open()
are distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear which module implements a function. For instance, writingrandom.seed()
oritertools.izip()
makes it clear that those functions are implemented by therandom
anditertools
modules, respectively.- nested scope (escopo aninhado)
The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another function can refer to variables in the outer function. Note that nested scopes work only for reference and not for assignment which will always write to the innermost scope. In contrast, local variables both read and write in the innermost scope. Likewise, global variables read and write to the global namespace.
- new-style class (novo estilo de classes)
Any class which inherits from
object
. This includes all built-in types likelist
anddict
. Only new-style classes can use Python’s newer, versatile features like__slots__
, descriptors, properties, and__getattribute__()
.More information can be found in New-style and classic classes.
- object (objeto)
Qualquer dado que tenha estado (atributos ou valores) e comportamento definidos (métodos). Também a última classe base de qualquer new-style class.
- package (pacote)
Um module Python é capaz de conter submódulos ou recursivamente, sub-pacotes. Tecnicamente, um pacote é um módulo Python com um atributo
__path__
.- parameter (parâmetro)
A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept. There are four types of parameters:
posicional-ou-nomeado: especifica um argumento que pode ser tanto posicional quanto nomeado. Esse é o tipo padrão de parâmetro, por exemplo foo e bar a seguir:
def func(foo, bar=None): ...
somente-posicional: especifica um argumento que pode ser passado para a função somente por posição. Python não possui sintaxe para definir parâmetros somente-posicionais. Contudo, algumas funções embutidas possuem argumentos somente-posicionais (por exemplo,
abs()
).var-posicional: especifica quem uma sequência arbitrária de argumentos posicionais pode ser fornecida (em adição a qualquer argumento posicional já aceito por outros parâmetros). Tal parâmetro pode ser definido colocando um
*
antes do nome, por exemplo args a seguir:def func(*args, **kwargs): ...
var-nomeado: especifica que, arbitrariamente, muitos argumentos nomeados podem ser fornecidos (em adição a qualquer argumento nomeado já aceito por outros parâmetros). Tal parâmetro pode definido colocando-se
**
antes do nome, por exemplo kwargs no exemplo acima.
Parâmetros podem especificar tanto argumentos opcionais quanto obrigatórios, assim como valores padrões para alguns argumentos opcionais.
See also the argument glossary entry, the FAQ question on the difference between arguments and parameters, and the Function definitions section.
- PEP
Proposta de melhoria do Python. Uma PEP é um documento de design que fornece informação para a comunidade Python, ou descreve uma nova funcionalidade para o Python ou seus predecessores ou ambientes. PEPs devem prover uma especificação técnica concisa e um racional para funcionalidades propostas.
PEPs tem a intenção de ser os mecanismos primários para propor novas funcionalidades significativas, para coletar opiniões da comunidade sobre um problema, e para documentar as decisões de design que foram adicionadas ao Python. O autor da PEP é responsável por construir um consenso dentro da comunidade e documentar opiniões dissidentes.
Veja PEP 1.
- positional argument (argumento posicional)
Veja o argument.
- Python 3000
Apelido para a versão do Python 3.x linha de lançamento (cunhado há muito tempo, quando o lançamento da versão 3 era algo em um futuro muito distante.) Esse termo possui a seguinte abreviação: “Py3k”.
- Pythonic
Uma ideia ou um pedaço de código que segue de perto os idiomas mais comuns da linguagem Python, ao invés de implementar códigos usando conceitos comuns a outros idiomas. Por exemplo, um idioma comum em Python é fazer um loop sobre todos os elementos de uma iterável usando a instrução: for statement. Muitas outras línguas não têm esse tipo de construção, então as pessoas que não estão familiarizadas com o Python usam um contador numérico:
for i in range(len(food)): print food[i]
Ao contrário do método limpo, ou então, Pythônico:
for piece in food: print piece
- reference count
O número de refrências para um objeto. Quando a contagem de referências de um objeto atinge zero, ele é desalocado. Contagem de referências geralmente não é visível no código Python, mas é um elemento chave da implementação CPython. O módulo
sys
define a funçãogetrefcount()
que programadores podem chamar para retornar a contagem de referências para um objeto em particular.- __slots__
A declaration inside a new-style class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application.
- sequence (sequência)
An iterable which supports efficient element access using integer indices via the
__getitem__()
special method and defines alen()
method that returns the length of the sequence. Some built-in sequence types arelist
,str
,tuple
, andunicode
. Note thatdict
also supports__getitem__()
and__len__()
, but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.- slice
An object usually containing a portion of a sequence. A slice is created using the subscript notation,
[]
with colons between numbers when several are given, such as invariable_name[1:3:5]
. The bracket (subscript) notation usesslice
objects internally (or in older versions,__getslice__()
and__setslice__()
).- método especial
Um método que é chamado implicitamente pelo Python para executar uma certa operação em um tipo, como uma adição por exemplo. Tais métodos tem nomes iniciando e terminando com dois underscores. Métodos especiais sestão documentados em Special method names.
- declaração
Uma instrução é parte de uma suíte (um “bloco” de código). Uma instrução é ou uma expression ou uma de várias construções com uma palavra-chave, tal como
if
,while
oufor
.- struct sequence
A tuple with named elements. Struct sequences expose an interface similiar to named tuple in that elements can be accessed either by index or as an attribute. However, they do not have any of the named tuple methods like
_make()
or_asdict()
. Examples of struct sequences includesys.float_info
and the return value ofos.stat()
.- aspas triplas
Uma string que está definida com três ocorrências de aspas duplas (“) ou apóstrofes (‘). Enquanto elas não fornecem nenhuma funcionalidade não disponível com strings de aspas simples, elas são úteis para inúmeras razões. Elas permitem que você inclua aspas simples e duplas não encerradas dentro de uma string, e elas podem utilizar múltiplas linhas sem o uso de caracteres de continuação, fazendo-as especialmente úteis quando escrevemos documentação em docstrings.
- type
O tipo de um objeto Python determina qual tipo de objeto ele é; todos objetos tem um tipo. Um tipo de objeto é acessivel pelo atributo
__class__
ou pode ser recuperado comtype(obj)
.- Novas linhas universais
A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention
'\n'
, the Windows convention'\r\n'
, and the old Macintosh convention'\r'
. See PEP 278 and PEP 3116, as well asstr.splitlines()
for an additional use.- ambiente virtual
Um ambiente de execução isolado que permite usuários Python e aplicações instalarem e atualizarem pacotes Python sem interferir no comportamento de outras aplicações Python em execução no mesmo sistema.
- Máquina Virtual
Um computador definido inteiramente em software. A máquina virtual de Python executa o bytecode emitido pelo compilador de bytecode.
- Zen of Python
Lista de princípios de projeto e filosofias do Python que são úteis para a compreensão e uso da linguagem. A lista é exibida quando se digita “
import this
” no console interativo.