3

In Python a module imported has a string representation of the form <module <module-name> from <module-path>>.

As an example, after import numpy, print(numpy) returns

<module 'numpy' from 'C:\\Anaconda3\\envs\\python3.9\\lib\\site-packages\\numpy\\__init__.py'>

When dealing with classes one can modify this behaviour through the methods __str__ and __repr__. Is there a way to do the same with modules?

In particular I would like to write a module my_module such that

import my_module as md
print(md)

returns and ad hoc string.

I tried to define a __str__ and __repr__ functions in the module's __init__.py file assuming print would call these functions to provide a string representation of the module, but that does not seem to be the case.

semola
  • 172
  • 8
  • 1
    Methods like `__str__()` are looked up in the *class*, not the instance. And the class that defines modules is an internal type, implemented in C; there's no mechanism for changing its methods from Python code. – jasonharper Dec 08 '21 at 19:02
  • 1
    Actually I can monkey-patch `__str__` and `__repr__` into modules, for example `re.__str__ = lambda: 'A fish'` and if I then call `re.__str__()` we get the fish. But if I call `str(re)` we get the "default" function. Might be hardwired on the CPython side. – vaizki Dec 08 '21 at 19:07

0 Answers0