> On Jul 14, 2018, at 4:24 AM, Ken Hilton <kenlhil...@gmail.com> wrote:
>
> Hi all,
>
> 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
> import statement.
>
> 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?
>
> Sharing,
> Ken Hilton;
>
First thought is that ‘code golf’ is unlikely to be a big reason to add
something like this, especially since there is already a way to do what you
want, just spelled somewhat longer.
Your syntax is likely going to add complexity to the expression parser, and if
as you indicate most of the time your going to need the parentheses, you might
as well spell (import xx) as import(xx) which makes a lot less of a change to
the parser.
This gives us two distinctions from what we currently have, the operation is
spelt as import instead of __import__, and we have dropped the need for putting
quotes around the module name.
I don’t see a major issue with the first point, (except for the Zen of having
only 1 obvious way to do something) though it might make sense to look at the
discussion when __import__ was added to see why it was spelt that way.
For the second, you are basically just removing the need to put the module name
in quotes, but this then loses the ability to put a variable name there to
allow making the module to use be changed at run-time.
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/