4

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?

2
  • from the zen of python: "explicit is better than implicit" Commented Jul 2, 2010 at 14:24
  • 1
    In addition to Stargazer's answer, don't forget that Python allows you to have multiple unrelated classes in the same file. So you don't need to split things up as much as you do in Java. Commented Jul 2, 2010 at 14:31

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I just looked at Django, and they import what they need when they need it. Guess that might be the way to do it.
-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.
I agree that it is not good style, but that wasn't what he was asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.