Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove a method from a module?

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?

like image 414
Chiyaan Suraj Avatar asked Apr 28 '15 10:04

Chiyaan Suraj


People also ask

Which module must be imported to execute remove ()?

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.

How do you get all the methods in a module?

You can use dir(module) to see all available methods/attributes.

How do I delete an imported function in Python?

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.

What is the syntax of remove () a file in Python?

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.


2 Answers

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'
like image 32
valentin Avatar answered Oct 03 '22 19:10

valentin


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.

like image 80
pefu Avatar answered Oct 03 '22 20:10

pefu