In path setup, I wrongly wrote the code: os.chdir = '\some path', which turns the function os.chdir() into a string. Is there any quick way to restore the function without restarting the software? Thanks!
Asked
Active
Viewed 2,925 times
2 Answers
7
Kicking os
out of the modules cache can make it freshly importable again:
>>> import sys, os
>>> os.chdir = "d'oh!"
>>> os.chdir()
TypeError: 'str' object is not callable
>>> del sys.modules['os']
>>> import os
>>> os.chdir
<function posix.chdir>

wim
- 338,267
- 99
- 616
- 750
2
>>> import os
Assign to the chdir
method a string value:
>>> os.chdir = '\some path'
>>> os.chdir
'\some path'
Use reload
to, well, reload the module. reload
will reload a previously imported module.
>>> reload(os)
>>> os.chdir
<built-in function chdir>

blacksite
- 12,086
- 10
- 64
- 109
-
While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – andreas Sep 28 '16 at 07:53
-
This will work as-is in Python 2, but in Python 3 onwards, `reload` needs to be imported differently. Please see [this question](https://stackoverflow.com/a/437591/8305056) for how to import `reload` depending on your version of Python. – girlvsdata Aug 22 '18 at 00:27