Python class factory ... or?

We have a database library in C# that we can use like this:

DatabaseConnection conn = DatabaseConnection.FromConnectionString("...");

This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.

Internally, the DatabaseConnection class is an abstract class implementing some of the basic methods, but the FromConnectionString method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.

The connection string contains information about what kind of database engine and version this connection is for.

I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?

conn = DatabaseConnection("...")

or using a class method?

conn = DatabaseConnection.FromConnectionString("...")

is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?

Ok, let me ask a different question... What is the pythonic way of doing this?

I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.


Asked by: Miranda698 | Posted: 24-09-2021






Answer 1

This is possible in Python, but is probably not the best way to do it. The class factory pattern is essentially a workaround for languages that don't have first class classes. Since Python does have first class classes, you can store a class in a variable, and use that class directly to create instances. To change what class is created, store a different class in the variable.

For example:

class class1:
  def greet(self):
    print "hi"

class class2:
  def greet(self):
    print "hello"

maker = class1
obj1 = maker()

maker = class2
obj2 = maker()

obj1.greet() # prints "hi"
obj2.greet() # prints "hello"

Answered by: Freddie892 | Posted: 25-10-2021



Answer 2

Python doesn't care why type you return.

def DatabaseConnection( str ):   
    if ( IsOracle( str ) ):   
        return OracleConnection( str )  
    else: 
        return SomeOtherConnection( str )

Answered by: Emily943 | Posted: 25-10-2021



Answer 3

The first one is absolutely possible, and preferable in my opinion. In python, there's really not a whole lot of magic behind constructors. For all intents and purposes, they're just like any other function. I've used this design pattern a few times to indicate that a class shouldn't be instantiated directly, for example:

def DatabaseConnectionFromString(connection_string)
    return _DatabaseConnection(connection_string)

def DatabaseConnectionFromSomethingElse(something_else)
    connection_string = convert_something_else_into_string(something_else)
    return _DatabaseConnection(connection_string)

class _DatabaseConnection(object):
    def __init__(self, connection_string):
        self.connection_string = connection_string

Of course, that's a contrived example, but that should give you a general idea.

EDIT: This is also one of the areas where inheritance isn't quite as frowned upon in python as well. You can also do this:

DatabaseConnection(object):
    def __init__(self, connection_string):
        self.connection_string = connection_string

DatabaseConnectionFromSomethingElse(object)
    def __init__(self, something_else):
        self.connection_string = convert_something_else_into_string(something_else)

Sorry that's so verbose, but I wanted to make it clear.

Answered by: Alberta261 | Posted: 25-10-2021



Similar questions

python - Kivy class factory error

I tried to make a program with a screen manager an images you can click on. I first I tried to store the kivy file within a string variable and return the string variable, but I got this error message: kivy.factory.FactoryException: Unknown class <BILD1> So I tried to return the Screenmanager, but it did not seem to work. I still got the same error message, could you please help me....


Python - Class Factory

I'm using classes to design network conversations, I have this code: class Conversation(object): __metaclass__ = ABCMeta def __init__(self, received=0, sent=0): self.sent = sent self.received = received def __str__(self): return "<Conversation: received=" + str(self.received) + " sent=" + str(self.sent) + " >" def __eq__(self, other): return isinstanc...


python - Making a smart class factory in Django

I've been trying to figure this out for a while now with little success. I'm attempting to write a class factory that plays nice with Django's ORM, so that I can take a model schema like this: Product SubclassOfProduct0 SubclassOfProduct1 .... To work like this: Product.objects.get(pk=7) // returns the result of SubclassOfProduct0(pk=7) Product.objects.filter(p...


python - How to use a Pyro proxy object as a factory?

I want to use Pyro with an existing set of classes that involve a factory pattern, i.e. an object of Class A (typically there will only be one of these) is used to instantiate objects of Class B (there can be an arbitrary number of these) through a factory method . So, I'm exposing an object of Class A as the Pyro proxy object. I've extended the Pyro


How to unit test factory in python?

When unit testing class one should test only against public interface of its collaborators. In most cases, this is easily achieved replacing collaborators with fake objects - Mocks. When using dependency injection properly, this should be easy most times. However, things get complicated when trying to test factory class. Let us see example Module wheel class Wheel: ...


python - Should I create a factory class or a getobj method?

I've been reading stackoverflow for years, and this is my first post. I've tried searching, but I can't really find anything that I both understand, and matches my scenario. Yes, I'm total OOP newbie, so please explain things as plainly as possible. OK, I'm trying to write a Python script that calls Rsync to make a backup. I'm essentially calling the script from root's crontab. Because this opens up secur...


python - How to list available suds factory types

The short version is I'm trying to figure out if there's a way to list all the types available to calls to Client.factory.create() after loading a WSDL. I have a parameter that is of a complex type that includes an array of another complex type. The suds factory doesn't seem to know how to create the type that belongs in the array, so I don't know how to populate the array. When I pass the type name into factory....


python - How to create a hidden factory?

I know it's been covered before but I'm just not getting it... I want to create a class that is called with a filename but, depending on the filename's extension, it morphs to one of several subclasses. It think its a factory pattern, and I've done that before using a staticmethod, but I'm trying now, not entirely for kicks, to do it with a common instantiation of the base class. Is this possible? ...


python - Kivy class factory error

I tried to make a program with a screen manager an images you can click on. I first I tried to store the kivy file within a string variable and return the string variable, but I got this error message: kivy.factory.FactoryException: Unknown class <BILD1> So I tried to return the Screenmanager, but it did not seem to work. I still got the same error message, could you please help me....


python - How to make normal class from a factory in another module?

[The day after] I figured it out- I didn't even know what question to ask. The solution is to extend the golbals() dictionary of the user module with the dictionary of structure classes I build while parsing the.c and 'h files. globals().update(Structures.struct_dict) is all it took to be able to instantiate my derived classes without having to jump through hoops. Thanks for the help (whether i...


python - Error in Django Test using Factory Boy

I use Factory Boy in my Django project. Could you please explain my mistake to me: why am I having the error when I ran 'tests.py' - 'ValueError: "" needs to have a value for field "post" before this many-to-many relationship can be used.' Here is my code: import factory from . import models # factories class TagFactory(factory.Factory): class Meta: model = models.Tag name = ...


python - Create a mix of string and digit with Factory Boy in django

I want to create a mix of string and digits like this: "XL1A" or "PP25" for one field in my database.How can I do that? I'm using only uppercase letter for now. class CardFactory(DjangoModelFactory): class Meta: model = Card serial_number = FuzzyText(length=4, chars=string.ascii_uppercase) Also, is there anyway to create random pattern rules for FuzzX in Factory Boy such a...


Factory pattern in Python

Closed. This question needs to be more focused. It ...


python - How do I add a factory created type as a header in suds?

I can't seem to get suds working with my setup. I have to pass a context, with a remote user set before I can use any of the functions in the API. What I tried to do was this: client = Client(url, username=userid, password=password) apiContext = client.factory.create("apiCallContext") # This is listed in the types apiContext.remoteUser = "serviceAccount" # when I print the client clie...


python - Making a smart class factory in Django

I've been trying to figure this out for a while now with little success. I'm attempting to write a class factory that plays nice with Django's ORM, so that I can take a model schema like this: Product SubclassOfProduct0 SubclassOfProduct1 .... To work like this: Product.objects.get(pk=7) // returns the result of SubclassOfProduct0(pk=7) Product.objects.filter(p...


python - How to use a Pyro proxy object as a factory?

I want to use Pyro with an existing set of classes that involve a factory pattern, i.e. an object of Class A (typically there will only be one of these) is used to instantiate objects of Class B (there can be an arbitrary number of these) through a factory method . So, I'm exposing an object of Class A as the Pyro proxy object. I've extended the Pyro


python - What to return in Factory Methods?

I have a class Node which I want it to have multiple constructors. I was reading online about factory methods and apparently, it is the cleanest Pythonic way of implementing constructors. My class looks as follows so far: class Node(object): element = None left = None right = None def __init__(self, element): self.element = element @classmethod def tree(cos, element, l...


How to unit test factory in python?

When unit testing class one should test only against public interface of its collaborators. In most cases, this is easily achieved replacing collaborators with fake objects - Mocks. When using dependency injection properly, this should be easy most times. However, things get complicated when trying to test factory class. Let us see example Module wheel class Wheel: ...


python - Should I create a factory class or a getobj method?

I've been reading stackoverflow for years, and this is my first post. I've tried searching, but I can't really find anything that I both understand, and matches my scenario. Yes, I'm total OOP newbie, so please explain things as plainly as possible. OK, I'm trying to write a Python script that calls Rsync to make a backup. I'm essentially calling the script from root's crontab. Because this opens up secur...


python - How to list available suds factory types

The short version is I'm trying to figure out if there's a way to list all the types available to calls to Client.factory.create() after loading a WSDL. I have a parameter that is of a complex type that includes an array of another complex type. The suds factory doesn't seem to know how to create the type that belongs in the array, so I don't know how to populate the array. When I pass the type name into factory....


python - Factory Boy vs. custom objects

The question: What are the advantages of using Factory Boy in the following situation? I don't really see why I shouldn't just deliver my own custom objects. If I am wrong please show me why. I am using Factory Boy to make user instances during my tests, which creates a UserProfile object dynamically (standard recipe from Factory_Boy


python - Factory Design Pattern

I am trying to implement Factory Design Pattern and have done this far till now. import abc class Button(object): __metaclass__ = abc.ABCMeta html = "" def get_html(self, html): return self.html class ButtonFactory(): def create_button(self, type): baseclass = Button() targetclass = type.baseclass.capitalize() return targetclass button_obj = ButtonFactory(...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top