4

I am building an application in Python and I have my whole package. While I really like the fact that you have to explicitly state every import you need, I was wondering if there is a way to add some function or class to the global scope implicitly.

In my example a want a Factory class that should be available in all files. Classes like dict, str and so on are all available and I thought maybe it is possible to add my own class to the global scope in the same way in my __init__.py.

Is this possible?

javex
  • 7,198
  • 7
  • 41
  • 60
  • Yes, it must be possible. Have you tried yet? – Lev Levitsky Jul 01 '12 at 09:16
  • As far as I know, there is no real way to add a module to the builtins (…that needs less code than importing the module). – Creshal Jul 01 '12 at 09:20
  • 1
    See http://stackoverflow.com/questions/11124578/automatically-import-modules-when-entering-the-python-or-ipython-interpreter/11124610#11124610 – Dhara Jul 01 '12 at 09:22

1 Answers1

0

For interactive mode, add all your import definitions to a file (say all_my_imports.py) like below:

from abc import xyz
from my_stuff import *

And, point the environment variable PYTHONSTARTUP to it.

From a script, simply import the file that contains the above definitions:

from all_my_imports import * 

Remember, it is not good to depend on this functionality, it's (almost) always better to explicitly import all your modules.

Dhara
  • 6,587
  • 2
  • 31
  • 46
  • Not exactly the answer is was looking for, but I guess I have to wrap my head around this kind of explicit import. For information: I am working on a web application and would rather not use environment variables. Nevermind though, I will just explicitly import stuff. – javex Jul 01 '12 at 10:24
  • Well, then use the 2nd option I state: put all your definitions in a file and import that single file. And indeed, you do need to 'wrap your head' around being explicit, it's one of the ideas central to Python and what gives it such readability – Dhara Jul 01 '12 at 10:53