views:

48

answers:

1

I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them.

I am trying to achieve the same behavior in python. Is this possible?

I've tried various solutions, for example by importing everything in a file which I import everywhere. That works, but I have to type myClass = rootFolder.folder2.folder3.MyClass() each time I want to access a foreign class.

Could you show me an example for how a python architecture over several directories works? Do you really have to import all the classes you need in each file?

Imagine that I'm writing a web framework. Will the users of the framework have to import everything they need in their files?

A: 

Put everything into a folder (doesn't matter the name), and make sure that that folder has a file named __init__.py (the file can be empty).

Then you can add the following line to the top of your code:

from myfolder import *

That should give you access to everything defined in that folder without needing to give the prefix each time.

You can also have multiple depths of folders like this:

from folder1.folder2 import *

Let me know if this is what you were looking for.

Stargazer712
I just looked at Django, and they import what they need when they need it. Guess that might be _the_ way to do it.
Baversjo
-1: using `from ... import *` is horrible style, either specify explicitly what to import, e.g. `from test import test1, test2`. Or better don't use `from` at all and optionally just shorten the names like `import test.inner_test as it`.
nikow
I agree that it is not good style, but that wasn't what he was asking.
Stargazer712