Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create self registering factory in Python?

Tags:

python

factory

In C++ or other compile/link based OOP languages, it is relatively easy to implement self-registering factory. Is it possible to do it in Python?

For example, I have a base method class: Vehicle @ vehicle.py, which is abstract. I will have a factory for vehicles @ vehicle_factory.py. I will have other concrete vehicles: Class Car(Vehicle) @ car.py, Class Truck(Vehicle) @ truck.py, etc.

I wish I do not have to touch vehicle_factory.py to register all these concrete vehicles. Every time I create a new vehicle class (such as Bus), I only need to work on its own module bus.py using self-registration. Can this be implemented in Python?

like image 284
Sima Avatar asked Nov 25 '25 19:11

Sima


1 Answers

Sure. This could be done easily with class decorators:

# vehicle.py
class Vehicle(object):
    pass

_vehicle_types = []

def vehicle_type(cls):
    _vehicle_types.append(cls)

def make_vehicle(type_):
    for vt in _vehicle_types:
        if vt.type_ == type_:
            return vt()
    raise ValueError('No vehicle of type "{}" exists'.format(type_))

# car.py
import vehicle

@vehicle.vehicle_type
class Car(vehicle.Vehicle):
    type_ = 'car'

# bus.py
import vehicle

@vehicle.vehicle_type
class Bus(vehicle.Vehicle):
    type_ = 'bus'

However, you'd have to make sure car.py and bus.py were loaded by the interpreter at some point before calling make_vehicle("car") or make_vehicle("bus") respectively.

like image 62
Kyle Willmon Avatar answered Nov 27 '25 09:11

Kyle Willmon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!