Is it possible to remove a method from a module?

Is it possible to remove a method from a ready-made module in python? I recently tried to write python code in a browser-based trading platform where they allow us to import the python 'time' package, but the time package did not have a sleep () method. While I was trying to import the sleep method, it gave me an attribute error. When I asked for technical support for the people of this platform, I found out that they do not support the sleep () method. I'm just wondering how can we do this? Is it just removing a method from a package? Or are there any better ways?

+5
source share
3 answers

You can remove methods (functions) from the namespace at run time. This is called a monkey patch. Example in an interactive session:

Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.sleep(2) >>> del time.sleep >>> time.sleep(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'sleep' 

But back to your original question: I believe that on the platform you are using, they could replace several standard library modules (including the time module) using custom versions. Therefore, you should ask them how you can achieve the desired delay without resorting to lively waiting.

+6
source
 import time time.sleep(1) del time.sleep time.sleep(1) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-07a34f5b1e42> in <module>() ----> 1 time.sleep(1) AttributeError: 'module' object has no attribute 'sleep' 
+1
source

If you don't have the time.sleep method, you can easily write your own (although not very accurate or efficient):

 def sleep(seconds): a = time.time() b = time.time() while b - a < seconds: b = time.time() 

Here are some accuracy tests I performed (just the print statement to find out how often it gets into the loop):

  >>> sleep (1)
 2.86102294922e-06
 0.0944359302521
 0.14835691452
 0.198939800262
 0.249089956284
 0.299441814423
 0.349442958832
 0.398970842361
 0.449244022369
 0.498914003372
 0.549893856049
 0.600338935852
 0.648976802826
 0.700131893158
 0.750012874603
 0.800500869751
 0.850263834
 0.900727987289
 0.950336933136
 1.00087189674

Accuracy remains in the 100th minute of a second. :) You may not have a method because it changed the source code or ran some things in the interpreter before your code started to run (using the del keyword, as in other answers).

+1
source

All Articles