Reputation: 1317
How should I implement my package so I can write the following.
Suppose my Module is called Market. It is a folder in the working directory of my python script called goShopping.py
In my goShopping.py I want to be able to write the following piece of code:
import market as mk
B = mk.Banana(0.99)
A = mk.Apple(1.10)
A.buy()
B.buy()
Where Banana and Apple are objects in some file in my Module.
How should the Module market be written?
Let's say that I have a file in the Module folder called fruits.py, There I define Banana and Apple class. I know I can write the above code as follows:
import market.fruits as mk
B = mk.Banana(0.99)
A = mk.Apple(1.10)
A.buy()
B.buy()
But I don't want that.
As a solution I thought about having some declaration in __init__.py
(the __init.py
inside the market folder) like this:
from fruits import Apple,Banana.
But I get the following error:
AttributeError: module 'market' has no attribute 'Banana'
From line:
B = mk.Banana(0.99)
How should I structure and what should I write to be able expose the objects as I want?
I am using Pythonista for iOS. I wonder if this is the problem.
Upvotes: 0
Views: 1892
Reputation: 447
Adding from FolderName.fruits import Apple,Banana
in __init__.py
placed in the folder works for me: I can then then call from the main project from FolderName import Apple,Banana
Adding from fruits import Apple,Banana
in __init__.py
placed in the folder does not work for me
Upvotes: 0
Reputation: 6211
It's likely the module/script is not being imported. This doesn't cause an error message. Try importing a module called 'xyz' and you'll see that as long as you don't try to access it you won't get an error.
The most likely reason is the module isn't in the same folder as your script, or isn't in a subdirectory containing an __init__.py script.
Your script should be able to import any module in the same folder as itself. You can also import modules from packages. A package is a folder containing one or more python modules and a special module called __init__.py which marks the folder as a package. The package folder needs to be in the PYTHONPATH or be a subdirectory of the current working directory so Python can find it, but sub-package folders don't.
Check this article which gives a nice explanation of how this works.
Upvotes: 0