How __future__ imports work under the hood

I was passionate about the module __future__- in particular, its ability to change the way operators are parsed in python.

The most interesting thing is how to do something like

from __future__ import print_function

Allows you to use print(and not print_function, as you would expect another normal import).

I read What is __future__ in Python, which is used and how / when to use it, and how it works , and, in particular, came across a specific line:

The future statement is a directive for the compiler that a particular module must be compiled using the syntax or semantics that will be available in the specified future version of Python.

I would like to know the intricacies of what exactly makes this possible. In particular, it’s kind of like

from __future__ import division

python2,

from __future__ import barry_as_FLUFL

<> python3 ( , "__future__" ).

, , , , __future__ .

+4
1

from __future__ import print_function print ( ). , , .

, compiler c_future, PyFutureFeatures, , . .

future.c , future_parse(), import from AST , __future__, .

, barry_as_FLUFL ' != , <>:

if (type == NOTEQUAL) {
    if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) &&
                    strcmp(str, "!=")) {
        PyObject_FREE(str);
        err_ret->error = E_SYNTAX;
        break;
    }
    else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) &&
                    strcmp(str, "<>")) {
        PyObject_FREE(str);
        err_ret->text = "with Barry as BDFL, use '<>' "
                        "instead of '!='";
        err_ret->error = E_SYNTAX;
        break;
    }
}

grepping FUTURE_* compile.h.

, __future__ Python module, ; Python ( flags compile()), .

+5

Source: https://habr.com/ru/post/1684142/


All Articles