Reputation: 385
Is there a way to combine import and from import in one statement?
Can:
from random import choice
import random
be combined into one statement?
Upvotes: 4
Views: 1488
Reputation: 20336
I think MartijnPieters was a little hasty. It is true that it is weird, but here is one way:
random, choice = (lambda x: (x, x.choice))(__import__("random"))
You see, __import__("random")
returns the random
module object. We then pass that to a lambda
function. That lambda
function returns the module and the module's choice
attribute as a tuple. We then assign random
and choice
to that tuple. I would never use this in regular code, but you can do it this way. I would do:
import random
choice = random.choice
Upvotes: 4
Reputation: 1122152
No, they can't.
See the import
statement grammar:
import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )* | "from" relative_module "import" identifier ["as" name] ( "," identifier ["as" name] )* | "from" relative_module "import" "(" identifier ["as" name] ( "," identifier ["as" name] )* [","] ")" | "from" module "import" "*"
The import module
and from relative_module import
forms are two entirely separate forms in the grammar.
Upvotes: 7