0

I'm trying to add a couple of miscellaneous development helpers to my python project in such a way that I don't need to either import them or declare them global at the call site, just to save myself some typing.

Example usage would be something like:

# Somewhere, maybe src/__init__.py?
from pprint import pprint
superduperglobaleasyusenamespace.p = pprint

# A different file somewhere in my project
def whatever():
    p('hello')

I looked at builtin but wasn't able to get it to work. If that's the correct solution, provide example code that works in python3.

jstaab
  • 3,449
  • 1
  • 27
  • 40

1 Answers1

0

Add this as very first line in your program:

__builtins__.p = pprint

In general, it is not recommend to modify the builtin name space. An import is just one line after all.

Example

# mod1.py

from pprint import pprint

__builtins__.p = pprint

import mod2

and

# mod2.p

print(p)

Now:

python mod1.py 
<function pprint at 0x10df28e18>
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • This does not work for me when calling `p` in a different file, I've tried the exact same thing. – jstaab Mar 02 '18 at 19:33
  • Sorry. It is `__builtins__` with a `s` at the end. – Mike Müller Mar 02 '18 at 20:39
  • Ok, this does technically work – maybe I should clarify my question a bit more. I'd like to get this to work with no explicit import between the file. I have a large project, and I want `pprint` to be available in every file, with no import, and without forcing the project to be run through a parent file (as in your example). Think php/apache auto prepend. – jstaab Mar 08 '18 at 18:00
  • You program hast to start somewhere. Import and assign to `__builtins__` at the very beginning. No further imports needed. – Mike Müller Mar 08 '18 at 18:13
  • My program has multiple entry points, none of which are the `__main__` module (for example, I export a uwsgi handler which gunicorn calls), and `__builtins__` acts like a dict when you're not in the `__main__` module. – jstaab Mar 08 '18 at 19:19
  • Did you try if it works? You only need to two lines of code. – Mike Müller Mar 09 '18 at 06:09
  • Your solution doesn't work if the module where you modify `__builtins__` isn't also `__main__`, because in any non-`__main__` module, `__builtins__` is a dict (and manipulating that dict is something I've fiddled with a bunch and hasn't worked). But yes, I did try it, in a couple configurations. – jstaab Mar 09 '18 at 16:26