问题
Are there any other uses for Python's "from" keyword aside from import
statements?
回答1:
No and yes.
According to the official Python 2.7.2 grammar, the only occurrence of the word from
is in the clause import_from
, so no.
In the Python 3.1.3 grammar a new clause
raise_stmt: 'raise' [test ['from' test]]
appears, so yes.
回答2:
In Python 2.x, the only use of from
is for the from x import y
statement. However, for Python 3.x, it can be used in conjunction with the raise
statement, e.g.:
try:
raise Exception("test")
except Exception as e:
raise Exception("another exception") from e
回答3:
There is a new syntax for delegating to a subgenerator in Python 3.3 which uses the from
keyword.
回答4:
The following use
from __future__ import some_feature
is syntactically identical to an import statement but instead of importing a module, it changes the behavior of the interpreter in some fashion, depending on the value of some_feature
.
For example, from __future__ import with_statement
allows you to use Python's with
statement in Python 2.5, even though the with
statement wasn't added to the language until Python 2.6. Because it changes the parsing of source files, any __future__
imports must appear at the beginning of a source file.
See the __future__ statement documentation for more information.
See the __future__ module documentation for a list of possible __future__
imports and the Python versions they are available in.
回答5:
Since there are a lot of updates to python from the time of posting the question, here is a new use case of from keyword in python3 will show you the use with an example
def flatten(l):
for element in l:
if type(element) == type(list()):
yield from flatten(element)
else:
yield element
def flatten2(l):
for element in l:
if type(element) == type(list()):
yield flatten2(element)
else:
yield element
unflatted_list = [1,2,3,4,[5,6,[7,8],9],10]
flatted_list = list(flatten(unflatted_list))
flatted_list2 = list(flatten2(unflatted_list))
print(flatted_list) # [1,2,3,4,5,6,7,8,9,10]
print(flatted_list2) # [1, 2, 3, 4, <generator object flatten2 at 0x000001F1B4F9B468>, 10]
来源:https://stackoverflow.com/questions/7219082/uses-of-pythons-from-keyword