line_profiler: what am I doing wrong?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 10 20:17:22 EST 2015


Neal Becker wrote:


> To quote from https://pypi.python.org/pypi/line_profiler/
> 
> $ kernprof -l script_to_profile.py
> kernprof will create an instance of LineProfiler and insert it into the
> __builtins__ namespace with the name profile. 

Ewww!!!! What a Ruby-esque interface, that makes me sad :-( And what if you
have your own profile global name?

And *wrong* too. `__builtins__` is a private CPython implementation detail.
The way to monkey-patch the built-ins in Python 2 is to inject the object
into `__builtin__` (no s), or `builtins` in Python 3. Seeing as
line_profiler is written in C, perhaps the author (Robert Kern) doesn't
care about supporting Jython or IronPython, but there may be Python
implementations (PyPy perhaps?) which can run C code but don't have
__builtins__.


In any case, it sounds like it isn't working. Try creating this simple file:

# demo.py
print(profile)  # Does profile actually get injected into the builtins?


then running it:

kernprof -l demo.py


If that still gives a NameError, you have a bug in kernprof. Or possibly you
have broken it -- perhaps you are accidentally shadowing one of its modules
with a module of your own?



-- 
Steven




More information about the Python-list mailing list