-1

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'

minivip
  • 195
  • 1
  • 6

2 Answers2

1

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

Peter
  • 3,186
  • 3
  • 26
  • 59
  • What can be done is to leave the real path name, and append a string to it. I had actually hoped it was something less invasive to do. Thanks to everyone that helped clarify the issue – minivip Apr 18 '23 at 05:56
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.

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.