This is almost always a bad idea, but if you really want to do it…
If you print out or otherwise inspect the print
function, you'll see it's in the module builtins
. That's your clue. So, you can do this:
debugmodule.py:
import builtins
builtins.debug = debug
Now, after an import debugmodule
, any other module can just call debug
instead of debugmodule.debug
.
Is it possible to do from the C side binding?
In CPython, C extension module can basically do the same thing that a pure Python module does. Or, even more simply, write a _debugmodule.so
in C, then a debugmodule.py
that imports it and copies debug
into builtins
.
If you're embedding CPython, you can do this just by injecting the function into the builtins
module before starting the script/interactive shell/whatever, or at any later time.
While this definitely works, it's not entirely clear whether this is actually guaranteed to work. If you read the docs, it says:
As an implementation detail, most modules have the name __builtins__
made available as part of their globals. The value of __builtins__
is normally either this module or the value of this module’s __dict__
attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
And, at least in CPython, it's actually that __builtins__
module or dict that gets searched as part of the lookup chain, not the builtins
module. So, it might be possible that another implementation could look things up in __builtins__
like CPython does, but at the same time not make builtins
(or user modifications to it) automatically available in __builtins__
, in which case this wouldn't work. (Since CPython is the only 3.x implementation available so far, it's hard to speculate…)
If this doesn't work on some future Python 3.x implementation, the only option I can think of is to get your function injected into each module, instead of into builtins. You could do that with a PEP-302 import hook (which is a lot easier in 3.3 than it was when PEP 302 was written… read The import system for details).
In 2.x, instead of a module builtins
that automatically injects things into a magic module __builtins__
, there's just a magic module __builtin__
(notice the missing s
). You may or may not have to import
it (so you might as well, to be safe). And you may or may not be able to change it. But it works in (at least) CPython and PyPy.
So, what's the right way to do it? Simple: instead of import debugmodule
, just from debugmodule import debug
in all of your other modules. That way it ends up being a module-level global in every module that needs it.