I’ve lost count of the number of times I’ve seen Python newbies asking why they’re getting the TypeError: 'module' object is not callable
error:
>>> import pprint
>>> pprint([[1, 2], [3, 4]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>>
And even a more experienced Python user like myself often find it annoying having to repeat the same name in the form of the boilerplate of:
from tqdm import tqdm
for i in tqdm(range(10)): # let's pretend there's no trange for illustration's' sake
...
rather than a simple:
import tqdm
for i in tqdm(range(10)):
...
when all I want from a module is to call its main function or class that is named the same as the module itself.
Would it not make the usage friendlier if Python allowed a module to be callable by automatically resolving a call to a module object to its attribute of the same name?
To allow cases where the main callable is cased/spelled differently from the module name, such as decimal.Decimal
, we can consider either making decimal.decimal
an alias to decimal.Decimal
, or accept a new module-level dunder such as __call__
:
# _pydecimal.py
class Decimal(object):
...
decimal = Decimal # alias approach
__call__ = Decimal # dunder approach
However, this would mean we would then see codes spelling the same callable differently:
import decimal
d = decimal('1.23')
and
from decimal import Decimal
d = Decimal('1.23')
so whether or not to support calling a non-namesake callable when a module is called is more debatable.