1

I've been searching for this for ages and can't find anything. I'm an experienced programmer, but recently switched to Python.

In short, I want to expand/evolve an object-oriented library of related classes into a namespace with multiple separate files (due to complexity and the desire for increased modularity) :

Currently, I might have :

# file lib/NameSpace.py
class Foo(object):
 def __init__(self):
 ....
class Bar(object):
 def __init__(self):
 ....
class Baz(object):
 def __init__(self):
 ....

And with this my program can do this:

import NameSpace
a = NameSpace.Foo()
b = NameSpace.Bar()

Now, these classes are getting complicated and Foo and Bar are functionally different though related in the conceptual NameSpace, so I want to move them to separate files within the namespace but otherwise keep my code library the same.

So, I think I want a file structure like this:

lib/NameSpace
lib/NameSpace/__init__.py
lib/NameSpace/Foo.py
lib/NameSpace/Bar.py
lib/NameSpace/Baz.py

But this would require me to change all the runtime code to initialize these as so:

import NameSpace.Foo
a = NameSpace.Foo.Foo() 
# ***Boo.**** Why u not like 'a = NameSpace.Foo()'?

So, how I do structure these things to not have to add the 'Foo' class name to the module 'Foo'? I could accomplish this by editing init.py to be a factory, like so:

#lib/NameSpace/__init__.py
import NameSpace.Foo as NSF
def Foo(*args, **kwargs):
 return(NSF.Foo(*args,**kwargs))

But that just seems more inelegant than I expect from Python. Is there a better way to do it?

asked Sep 5, 2017 at 15:24

2 Answers 2

1

In your __init__.py

from .Foo import Foo
from .Bar import Bar
from .Baz import Baz

naming the files differently than your classes prevents the overwrite.

answered Sep 5, 2017 at 15:27
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thanks!
0

For simplicity, you could import the Foo class from the module just like this:

from NameSpace.Foo import Foo

After that, you can create an object of Foo class like this:

a = Foo()

If you like, you can provide a different name when you import things too:

from NameSpace.Foo import Foo as F
a = F()
answered Sep 5, 2017 at 15:32

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.