pythonstringoverwrite

in Python, how to overwrite the str for a module?


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'


Solution

  • @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.