Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

python - How can I remove/unimport symbols from __future__ after importing them?

In python 2.x, dividing two integers returns an integer. However, if you use

from ___future___ import division

you can get a float value:

>>> 3/2
1
>>> from __future__ import division
>>> 3/2
1.5
>>> 
>>> 
>>> 3//2
1
>>> 4/3
1.3333333333333333
>>> 

After the import, you have to use // instead of / to do integer division. How can I revert the import so that / does integer division again?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

__future__ imports are special, and cannot be undone. You can read up on their behavior here.

Here are a few relevant portions:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
...
A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session.

Since __future__ statements are handled at compile time as opposed to runtime, there is no runtime method for reverting the changed behavior.

With normal modules you can remove or unimport the module by deleting whatever you imported from the namespace, and deleting the entry for that import in sys.modules (this second part may not be necessary depending on the use case, all it does is force the reloading of the module if it is imported again).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...