__future__ — Definições de instruções de future

Código-fonte: Lib/__ future __.py


Imports of the form from __future__ import feature are called future statements. These are special-cased by the Python compiler to allow the use of new Python features in modules containing the future statement before the release in which the feature becomes standard.

While these future statements are given additional special meaning by the Python compiler, they are still executed like any other import statement and the __future__ exists and is handled by the import system the same way any other Python module would be. This design serves three purposes:

  • Para evitar confundir as ferramentas existentes que analisam as instruções de importação e esperam encontrar os módulos que estão importando.

  • Para documentar quando as mudanças incompatíveis foram introduzidas, e quando elas serão — ou foram — obrigatórias. Esta é uma forma de documentação executável e pode ser inspecionada programaticamente através da importação __future__ e examinando seus conteúdos.

  • To ensure that future statements run under releases prior to Python 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1).

Module Contents

Nenhuma descrição de característica será excluída de __future__. Desde a sua introdução no Python 2.1, os seguintes recursos encontraram o caminho para o idioma usando esse mecanismo:

característica

opcional em

obrigatório em

efeito

nested_scopes

2.1.0b1

2.2

PEP 227: Statically Nested Scopes

geradores

2.2.0a1

2.3

PEP 255: Simple Generators

divisão

2.2.0a2

3.0

PEP 238: Changing the Division Operator

absolute_import

2.5.0a1

3.0

PEP 328: Imports: Multi-Line and Absolute/Relative

with_statement

2.5.0a1

2.6

PEP 343: The “with” Statement

print_function

2.6.0a2

3.0

PEP 3105: Make print a function

unicode_literals

2.6.0a2

3.0

PEP 3112: Bytes literals in Python 3000

generator_stop

3.5.0b1

3.7

PEP 479: StopIteration handling inside generators

annotations

3.7.0b1

Para ser feito [1]

PEP 563: Postponed evaluation of annotations

class __future__._Feature

Cada instrução em __future__.py é da forma:

FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)

Onde, normalmente, OptionalRelease é inferior a MandatoryRelease, e ambos são tuplas de 5 entradas da mesma forma que sys.version_info:

(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)
_Feature.getOptionalRelease()

OptionalRelease registra o primeiro lançamento no qual o recurso foi aceito.

_Feature.getMandatoryRelease()

No caso de um MandatoryRelease que ainda não ocorreu, MandatoryRelease prevê o lançamento em que o recurso se tornará parte da linguagem.

Senão MandatoryRelease registra quando o recurso se tornou parte do idioma; Em versões em ou depois disso, os módulos não precisam mais de uma instrução de future para usar o recurso em questão, mas podem continuar a usar essas importações.

MandatoryRelease may also be None, meaning that a planned feature got dropped or that it is not yet decided.

_Feature.compiler_flag

CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the built-in function compile() to enable the feature in dynamically compiled code. This flag is stored in the _Feature.compiler_flag attribute on _Feature instances.

Ver também

Instruções future

Como o compilador trata as importações de future.

PEP 236 - Back to the __future__

The original proposal for the __future__ mechanism.