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?
2 Answers 2
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.
1 Comment
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()
Comments
Explore related questions
See similar questions with these tags.