Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to remove/unimport libs was imported before [duplicate]

Tags:

python

As we know that, in python 2.x, if we divide two integer values it results in an int. However, if using from __future__ import division, we instead get a float value.

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

So, // instead of / should be used if we want integers after importing __future__.division, but I want to know how to make / to return integers again.

Is there any way to un-import or remove the previously imported module?


There is a method to unimport libs or Modules in IDLE, that is to Restart it by using Ctrl+F6 or Options in Menu

like image 700
Marslo Avatar asked Sep 19 '12 15:09

Marslo


2 Answers

__future__ looks like a module but isn't really. Importing it actually affects the compilation options of the current module. There's no way to "undo" it, since it effectively happens before the module is even executed.

If it were any other "normal" module, there are ways, but you're out of luck here. Either deal with the changed semantics, or put the code that needs different compilation in a separate module.

like image 29
bukzor Avatar answered Sep 29 '22 17:09

bukzor


python has reload to re-import an already imported module (which shouldn't be used in production code), but there is no way (that I know) to un-import a module once it's been imported.

Of course, you can just delete the reference to that module in your current namespace:

import module
module.foo()
del module
module.foo() #NameError, can't find `module`

Another point is that __future__ isn't really a module. It's more of an instruction to tell the parser how to behave. As such, when put in a file, it needs to be the first thing in there (before any other imports, etc). The fact that you can import __future__ from anywhere in an interactive session is a special case.

like image 139
mgilson Avatar answered Sep 29 '22 16:09

mgilson