
On Fri, 8 Apr 2022 at 18:29, Malthe <mborch@gmail.com> wrote:
This is an idea which has been brought up before, sometimes introduced as "heresy". But an interesting twist has surfaced now which is typing.
But firstly, let me present the idea. It is very simple, that Python should have declarative imports, usable anywhere using a simple syntax, @<dotted-name>.
For example, `some_regex = @re.compile(...)`.
What happens then is that before anything else in that module, that symbol is imported:
from re import compile as _mangled_re_compile
It must be the very first thing (hoisting) because when else would it happen?
JavaScript has this feature. ES6 modules are always imported declaratively and always before the rest of the script is executed. It is *extremely* annoying. Most of the time, it behaves the same way as Python's dynamic imports, but any time it doesn't, the "imports before the rest of the code" feature is nothing but hassle. Here's an alternative: Have a whitelist of modules that you make use of in this way. Any time you refer to a name that's on that whitelist and doesn't have an assigned meaning in the module, insert an import statement at the top of the script. It's not too hard to set up your editor to be able to do this (eg in SciTE, I can press Ctrl+1 to quickly run a script; a lot of editors let you configure a code formatter that runs automatically on save, which would also work), and then you retain full control of exactly where the importing happens. ChrisA