How to structure packages

Littlefield, Tyler tyler at tysdomain.com
Wed Sep 7 14:11:23 EDT 2011


On 9/7/2011 9:56 AM, bclark76 wrote:
> I'm learning python, and was playing with structuring packages.
>
> Basically I want to have a package called mypackage that defines a
> number of classes and functions.
>
>
> so I create:
>
> mypackage
>      __init__.py
>      myfunc.py
>      MyClass.py
>
>
> my __init__.py is blank.
>
> my MyClass.py looks like:
>
> import blah
>
> class MyClass(blahblah):
>      blah
>      blah
>      blah
>
>
> then I have a run.py that looks like
>
> from mypackage import MyClass
>
>
> x = MyClass()
>
>
> This doesn't work because MyClass is mypackage.MyClass.MyClass.
> There's this MyClass module 'in the way'.
>
You can use the __init__.py to promote that class up. so:
from myclass import myclass
So that means that myclass will just be in mypackage.myclass, and thus 
your from mypackage import myclass would work perfectly. I'm not sure if 
this is how you're supposed to do it, but it works.

> I'm trying to follow the rule that every file defines only one class.
> I could define MyClass in __init__.py, but then what if I wanted to
> define more classes in the mypackage package? My one class per file
> rule goes out the window.
>
> Is this rule wrongheaded, or is there another way to do this?
>
>
> Thanks.
>


-- 

Take care,
Ty
Web: http://tds-solutions.net

Sent from my toaster.




More information about the Python-list mailing list