1

I have a folder:

tastyfood

I have four classes:

chocolate.py
sweets.py
crisps.py
tuna.py

Say I wanted to put the four classes in the folder tastyfood

So I can make importations like:

import tastyfood 

and all the classes are imported rather than each class being imported.

I understand you can use __init__.py and have been reading posts like this But I am unable to find a way to do what I would like.

Any one have suggestions?

asked Jan 18, 2014 at 22:55
1
  • 1
    The answer you link describes exactly what you need to do; what are you stuck on? Commented Jan 18, 2014 at 22:57

2 Answers 2

3

Preamble: This technique can be useful if you have big classes of hundreds lines. If your classes are quite small, you should put them in one single file called tastyfood.py and you'll get the same behaviour, without folders.

If you want to use a folder to classify your classes, you need to have this folder structure:

tastyfood/
 __init__.py
 chocolate.py
 sweets.py
 crisps.py
 tuna.py
example.py # example file quoted above

and the __init__.py can contains import statement to make your life easier:

from chocolate import Chocolate
from sweets import Sweet
# ... import everything you want in the tastyfood namespace

so these examples, which can be found in example.py, can be valid:

import tastyfood
choco = tastyfood.Chocolate()
from tastyfood import Chocolate
choco = Chocolate()
from tastyfood.chocolate import Chocolate # still works too
choco = Chocolate() 
answered Jan 18, 2014 at 23:05
Sign up to request clarification or add additional context in comments.

Comments

0

So all the classes are located in tastyfood/ , correct? You need to put an empty __init__.py file in that folder, along with the other files and you will be able to import them like that.

jonrsharpe
123k31 gold badges278 silver badges488 bronze badges
answered Jan 18, 2014 at 22:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.