Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do future_statements in Python need to be placed before everything?

PEP 236 states clearly that all future_statements must appear near the top of a module, with only comments, docstrings and the like allowed before them.

I understand that this isn't debatable as a programming practice - it's the rules and they're clear. However, I can't google myself an answer as to why it was decided to be an error rather than just a violation of recommended practices when you fail to place your future_statement at the very top (aka, a warning).

Is it because this way, modules that import their own versions of names that the future_statement will import, will be able to override them, thus ensuring they'll work correctly? Is it to maintain some sort of strong code clarity so that proper coding practices aren't broken because of potential disasters if a __future__ import is accidentally ignored? The PEP isn't enlightening on this and I can't get any leads to finding out why.

like image 864
mechalynx Avatar asked Feb 11 '23 03:02

mechalynx


1 Answers

__future__ statements potentially even have effects on parsing (example: unicode_literals, print_function), as they may modify (or rather switch to a different version of) the grammar. They thus must be known as early as possible. They also certainly have effects on code generation (division).

There are are thus good design reasons to force those statements to be at the start of the parsing and the compilation, in addition to the clarity concerns.

Other imported modules do not have any effect on what is going on in your module with respect to __future__. Which is a good thing, because otherwise other modules could break your module by importing print_function from __future__.

like image 192
Jonas Schäfer Avatar answered Feb 12 '23 16:02

Jonas Schäfer