2

Let's pretend that I have this file called file1.py:

from app1 import ClassX

class Class1:
    pass

class Class2:
    pass

If in another file called file2.py I want to import Class1 and Class2 without explicit import this classes I usually need to use

from file1 import *

My problem is, when I do it I'm importing the ClassX too, but I don't want to import the ClassX and I don't to import Class1 and Class2 explicit.

There is some way to import only the classes that I really developed in File1?

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
Rubico
  • 374
  • 2
  • 12
  • 4
    This is what [`__all__`](http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python) is for. It controls what is automatically included when you `from foo import *`. – Jonathon Reinhart Sep 25 '15 at 17:09

1 Answers1

2

To put a finer point on Jonathon Reinhart's comment on the question:

# app2.py
from app1 import ClassX

__all__ = ['Class1', 'Class2']

class Class1:
    pass

class Class2:
    pass

 

# test.py
from app2 import *

c = Class1()
d = Class2()
try:
    e = ClassX()
except NameError:
    print "Working as intended!"
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Adam, this is cool. But I can see just one problem, if I create an Class3 on file1.py, I need to add to __all__ var. There is another way to do this? Whitout need of add to __all__ every time I create a new class? – Rubico Sep 25 '15 at 17:33
  • 3
    @Rubico there's no way (that I'm aware of) to create a so-called "blacklist" of items to be imported. You should really try to avoid the `from modulename import *` construction, anyway. – Adam Smith Sep 25 '15 at 17:34