[Python-ideas] Make import an expression
kenlhilton at gmail.com
Sat Jul 14 04:24:32 EDT 2018
Just a curious idea I had. The subject says it all. "import" is currently a
statement, which means it cannot be used inside anything else. Currently,
the only way to import a module inside an expression is to use the
__import__ function, which is both cumbersome and takes up more space
(which is disadvantageous in things like code golf).
I propose making "import" an expression, thus allowing the syntactic sugar
of "import module" -> "__import__('module')" to be graduated to the
expression level. Because of operator precedence, I suspect that in most
cases one would need to surround the expression with parentheses.
An additional effect that is not seen with using __import__ is that the
module's name is bound to the current scope the way it is with a normal
Examples of where this could be used:
Importing on the fly to generate one value:
secret = (import random).randint(1, 100)
Quick use of itertools in generator expressions:
(i * i for i in (import itertools).accumulate(generate_numbers()))
Re-using a function from a module after importing it in an expression:
b = a * (import math).tan(math.radians(45)) #math.radians is valid
because (import math) binds "math" to the current scope
What are your thoughts?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas