Python import as private

Is it possible to create a private import in Python

Questions : Is it possible to create a private import in Python

I am working on a factory in Python and query uvdos python would like to make all the imports query uvdos python «private».

from my_classes import MyClass1, MyClass2 class MyFactory(object): def __init__(self, class_name): if class_name == "my_class_1": return MyClass1() elif class_name == "my_class_2": return MyClass2() 

In this case I would like to have the caller query uvdos python be able to use MyFactory, and not see query uvdos python MyClass1 and MyClass2.

I know there is no such thing as private in query uvdos python Python. What I tried is from my_classes query uvdos python import MyClass1 as _my_class_1 but then I query uvdos python get a message Constant variable imported as query uvdos python non-constant

For now I have solved it like this:

class MyFactory(object): def __init__(self): do my init stuff here def create_myclass_1(self): from my_classes import MyClass1 return MyClass1() def create_myclass_2(self): from my_classes import MyClass2 return MyClass2() 

This does not look very Pythonic to me, but query uvdos python I might be wrong.

Could someone tell me if there is a better query uvdos python way to do this?

Answers 1 : of Is it possible to create a private import in Python

Reading between the lines; do you want help uvdos python to avoid polluting the namespace of your help uvdos python module, so people importing it have an help uvdos python easier time?

Читайте также:  Gradient descent method python

In this case, use the magic variable help uvdos python __all__.

__all__ = ['a', 'b'] def a(): pass def b(): pass def c(): pass 

If you save the above example as help uvdos python test.py, then from test import, you will help uvdos python be able to run both a() and b(), but c() help uvdos python will raise a NameError.

Answers 2 : of Is it possible to create a private import in Python

There is no pythonic and nice way to do help uvdos python this.

and when you import the module (module help uvdos python you use __all__ in it) in the including help uvdos python module,

you are gonna get everything mentioned help uvdos python in __all__.

Answers 3 : of Is it possible to create a private import in Python

You could just create an actual factory help uvdos python function

def my_factory(class_name): if class_name == "my_class_1": return MyClass1() elif class_name == "my_class_2": return MyClass2() 

Alternatively, if you want a little more help uvdos python magic and want it to be treated more help uvdos python like a class, you can override the help uvdos python __new__ method.

class FakeClass(object): def __new__(cls, class_name): if class_name == "my_class_1": cls = MyClass1 elif class_name == "my_class_2": cls = MyClass2 return object.__new__(cls) 

Источник

Оцените статью