Can I remove a method from a ready module in python? Recently i was trying to write a python code in a browser based trading platform where in they allow usto import python 'time' package but the time package didn't have sleep() method. While i was trying to import sleep method it gave me attribute error. On asking the technical support people of that platform i got to know that they don't support sleep() method. I am just wondering how could we do that? is it just deleting the method from the package? Or are there any better ways?
Using the os module in python To use the os module to delete a file, we first need to import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter. You can not just delete a file but also a directory using the os module.
You can use dir(module) to see all available methods/attributes.
To remove an imported module in Python: Use the del statement to delete the sys reference to the module. Use the del statement to remove the direct reference to the module.
remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
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'
It is possible to remove methods (functions) from a name space at run time. This is called monkey patching. 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 might have replaced several standard library modules (including the time module) with customized versions. So you should ask them how you can achieve the delay you want without having to resort to busy waiting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With