I'm a minor contributor to a package where people are meant to do this (Foo.Bar.Bar is a class):
>>> from Foo.Bar import Bar
>>> s = Bar('a')
Sometimes people do this by mistake (Foo.Bar is a module):
>>> from Foo import Bar
>>> s = Bar('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
This might seems simple, but users still fail to debug it, I would like to make it easier. I can't change the names of Foo or Bar but I would like to add a more informative traceback like:
TypeError("'module' object is not callable, perhaps you meant to call 'Bar.Bar()'")
I read the Callable modules Q&A, and I know that I can't add a __call__ method to a module (and I don't want to wrap the whole module in a class just for this). Anyway, I don't want the module to be callable, I just want a custom traceback. Is there a clean solution for Python 3.x and 2.7+?
3 Answers 3
Add this to top of Bar.py: (Based on this question)
import sys
this_module = sys.modules[__name__]
class MyModule(sys.modules[__name__].__class__):
def __call__(self, *a, **k): # module callable
raise TypeError("'module' object is not callable, perhaps you meant to call 'Bar.Bar()'")
def __getattribute__(self, name):
return this_module.__getattribute__(name)
sys.modules[__name__] = MyModule(__name__)
# the rest of file
class Bar:
pass
Note: Tested with python3.6 & python2.7.
7 Comments
__class__ reassigned.__init__.py. Your current problems are easy to understand and easy to explain. The problems you'll give yourself by trying to change the error message are likely to be much harder to understand and explain.Bar module was actually called as a function, rather than something else triggering a TypeError. Also, it's likely to interfere with other excepthook replacements, and it's incompatible with IPython.What you want is to change the error message when is is displayed to the user. One way to do that is to define your own excepthook.
Your own function could:
- search the calling frame in the traceback object (which contains informations about the
TypeErrorexception and the function which does that), - search the
Barobject in the local variables, - alter the error message if the object is a module instead of a class or function.
In Foo.__init__.py you can install a your excepthook
import inspect
import sys
def _install_foo_excepthook():
_sys_excepthook = sys.excepthook
def _foo_excepthook(exc_type, exc_value, exc_traceback):
if exc_type is TypeError:
# -- find the last frame (source of the exception)
tb_frame = exc_traceback
while tb_frame.tb_next is not None:
tb_frame = tb_frame.tb_next
# -- search 'Bar' in the local variable
f_locals = tb_frame.tb_frame.f_locals
if 'Bar' in f_locals:
obj = f_locals['Bar']
if inspect.ismodule(obj):
# -- change the error message
exc_value.args = ("'module' object is not callable, perhaps you meant to call 'Foo.Bar.Bar()'",)
_sys_excepthook(exc_type, exc_value, exc_traceback)
sys.excepthook = _foo_excepthook
_install_foo_excepthook()
Of course, you need to enforce this algorithm...
With the following demo:
# coding: utf-8
from Foo import Bar
s = Bar('a')
You get:
Traceback (most recent call last):
File "/path/to/demo_bad.py", line 5, in <module>
s = Bar('a')
TypeError: 'module' object is not callable, perhaps you meant to call 'Foo.Bar.Bar()'
2 Comments
There are a lot of ways you could get a different error message, but they all have weird caveats and side effects.
Replacing the module's
__class__with atypes.ModuleTypesubclass is probably the cleanest option, but it only works on Python 3.5+.Besides the 3.5+ limitation, the primary weird side effects I've thought of for this option are that the module will be reported callable by the
callablefunction, and that reloading the module will replace its class again unless you're careful to avoid such double-replacement.Replacing the module object with a different object works on pre-3.5 Python versions, but it's very tricky to get completely right.
Submodules, reloading, global variables, any module functionality besides the custom error message... all of those are likely to break if you miss some subtle aspect of the implementation. Also, the module will be reported callable by
callable, just like with the__class__replacement.Trying to modify the exception message after the exception is raised, for example in
sys.excepthook, is possible, but there isn't a good way to tell that any particularTypeErrorcame from trying to call your module as a function.Probably the best you could do would be to check for a
TypeErrorwith a'module' object is not callablemessage in a namespace where it looks plausible that your module would have been called - for example, if theBarname is bound to theFoo.Barmodule in either the frame's locals or globals - but that's still going to have plenty of false negatives and false positives. Also,sys.excepthookreplacement isn't compatible with IPython, and whatever mechanism you use would probably conflict with something.
Right now, the problems you have are easy to understand and easy to explain. The problems you would have with any attempt to change the error message are likely to be much harder to understand and harder to explain. It's probably not a worthwhile tradeoff.
Comments
Explore related questions
See similar questions with these tags.
FootofooandBar(the module) tobarwould go a long way in indicating that they're not classes, and people would be less likely to confusebarwithBar.FooandBar, which should be insnake_casefollowing PEP8. Trying to call a lowercase name to instantiate an object would immediately fall to your eye as a bit weird, at least for non-beginners in Python.