英文:
in Python, how to overwrite the str for a module?
问题
当用户输入模块名称并按回车键时,会得到如下字符串:
import pandas as pd
pd
<module 'pandas' from '....'>
如何覆盖这个字符串以适用于我的模块?
(请注意,我指的是一个模块,而不是一个类)
例如,在下面添加一段文本:
<module 'mymodule' from '....'>
my additional custom text
我尝试将以下内容添加到我的模块中:
def __str__():
print('my additional custom text')
以及
def __str__():
return 'my additional custom text'
def __repr__():
print("my additional custom text")
return "my additional custom text"
但什么都没有发生
当然,如果我输入
mymodule.__str__()
我会得到 'my additional custom text'。
英文:
When one types the name of a module and then hits return, one gets a string
like below
import pandas as pd
pd
<module 'pandas' from '....'>
How can I overwrite this string for my own module ?
(Please note that I am referring to a module, not to a class)
For example adding a text below like
<module 'mymodule' from '....'>
my additional custom text
I tried to add this to mymodule:
def __str__():
print('my additional custom text')
and also
def __str__():
return 'my additional custom text'
def __repr__():
print("my additional custom text")
return "my additional custom text"
but nothing happens
Of course, if I type
mymodule.__str__()
I get 'my additional custom text'
答案1
得分: 1
@JonSG 正确,它从 __spec__
中读取 - 我发现所有的逻辑都在 importlib._bootstrap 模块中。
这是如何修改模块名称和路径的方法:
import sys
if __spec__ is not None:
file_path = 'C:/other_file'
name = 'new_name'
__spec__.origin = file_path
if name != __spec__.name:
sys.modules[name] = sys.modules[__spec__.name]
__spec__.name = name
当我导入该文件时:
<module 'new_name' from 'C:/other_file'>
实际上,更改名称需要编辑 sys.modules
,所以请小心。但更改路径看起来完全没问题。
英文:
@JonSG was correct, it reads it from __spec__
- I found all the logic for it is in the importlib._bootstrap module.
This is how you'd modify the module name and path:
import sys
if __spec__ is not None:
file_path = 'C:/other_file'
name = 'new_name'
__spec__.origin = file_path
if name != __spec__.name:
sys.modules[name] = sys.modules[__spec__.name]
__spec__.name = name
When I import the file:
<module 'new_name' from 'C:/other_file'>
Changing the name actually requires editing sys.modules
so be careful. Changing the path however looks completely fine.
答案2
得分: 1
A short answer is: cannot do. Importlib
puts the module's repr
together with its name
and origin
properties. Check out the _module_repr_from_spec
function implementation.
我相信子类化 ModuleSpec 并覆盖其属性也不是可行的选择,除非您决定不使用 Importlib 并以某种方式自行加载模块。
英文:
A short answer is: cannot do. Importlib
puts the module's repr
together with its name
and origin
properties. Check out the _module_repr_from_spec
function implementation.
I believe subclassing ModuleSpec and overriding its attributes is also not a viable option, unless you decide to do without Importlib
and somehow load modules by yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论