Given the hierarchy of an abstract class, it detects the appropriate concrete subclass (deterministically) that satisfies certain attributes obtained as a parameter. Useful for implementing the Strategy design pattern.
Project description
SuitableClassFinder
Given the hierarchy of an abstract class, it detects the appropriate concrete subclass (deterministically) that satisfies certain attributes obtained as a parameter. Useful for implementing the Strategy design pattern.
[!NOTE] This is a Python port from a useful tool which I used in my times as a Smalltalk developer and I miss a lot. It's part from a set of snippets called Smalltools-st.
Example
Let's imagine that we have the following hierarchy:
from abc import ABC
class Vehicle(ABC):
def __init__(self, brand, color):
self.brand = brand
self.color = color
class Car(Vehicle):
def __init__(self, doors_amount, *args):
self.doors_amount = doors_amount
super().__init__(*args)
class Bike(Vehicle):
pass
class Motorbike(Vehicle):
pass
And we are consuming some silly API. The response could be something like:
vehicles = [
{'type':'car', 'doors':5, 'motor':1400, 'brand':'renault', 'color':'red'},
{'type':'bike', 'doors':0, 'motor':0, 'brand':'trek', 'color':'orange'},
{'type':'motorbike', 'doors':0, 'motor':250, 'brand':'yamaha', 'color':'black'},
{'type':'car', 'doors':3, 'motor':1200, 'brand':'volkswagen', 'color':'white'},
...
]
Adding just this snippet to Vehicle:
@classmethod
def can_handle(cls, vehicle_type):
return cls.__name__.lower() == vehicle_type
...we can get the right subclass for each json, just passing the type string attribute to the suitable_for method:
from smalltools.behavior.suitable_class_finder import SuitableClassFinder
SuitableClassFinder(Vehicle).suitable_for(vehicles[0]['type']) # Returns Car
[!TIP] The
can_handlemethod is what we called thesuitable_methodand its arguments are thesuitable_object.
But, what if the API response is not so easy?
vehicles = [
{'doors':5, 'motor':1400, 'brand':'renault', 'color':'red'},
{'doors':0, 'motor':0, 'brand':'trek', 'color':'orange'},
{'doors':0, 'motor':250, 'brand':'yamaha', 'color':'black'},
{'doors':3, 'motor':1200, 'brand':'volkswagen', 'color':'white'},
...
]
Don't worry. We can do something like this:
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, brand, color):
self.brand = brand
self.color = color
@classmethod
@abstractmethod
def can_handle(cls, doors, motor):
pass
class Car(Vehicle):
def __init__(self, doors_amount, *args):
self.doors_amount = doors_amount
super().__init__(*args)
@classmethod
def can_handle(cls, doors, motor):
return doors > 0 and motor > 0
class Bike(Vehicle):
@classmethod
def can_handle(cls, doors, motor):
return doors == 0 and motor == 0
class Motorbike(Vehicle):
@classmethod
def can_handle(cls, doors, motor):
return doors == 0 and motor > 0
Check that you can pass multiple arguments to the suitable_method. So we have to do the next lines:
from smalltools.behavior.suitable_class_finder import SuitableClassFinder
vehicle = vehicles[0]
SuitableClassFinder(Vehicle).suitable_for(vehicle['doors'], vehicle['motor']) # Returns Car
Okey, and if you have objects with different "shapes"?
vehicles = [
{'doors':5, 'motor':1400, 'brand':'renault', 'color':'red'},
{'brand':'trek', 'color':'orange'},
{'motor':250, 'brand':'yamaha', 'color':'black'},
{'doors':3, 'motor':1200, 'brand':'volkswagen', 'color':'white'},
...
]
Then, you can pass the entire json and process it:
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, brand, color):
self.brand = brand
self.color = color
@classmethod
@abstractmethod
def can_handle(cls, raw_json):
pass
class Car(Vehicle):
def __init__(self, doors_amount, *args):
self.doors_amount = doors_amount
super().__init__(*args)
@classmethod
def can_handle(cls, raw_json):
return 'doors' in raw_json and raw_json['doors'] > 0
class Bike(Vehicle):
@classmethod
def can_handle(cls, raw_json):
return 'doors' not in raw_json and 'motor' not in raw_json
class Motorbike(Vehicle):
@classmethod
def can_handle(cls, raw_json):
return 'doors' not in raw_json and 'motor' in raw_json and raw_json['motor'] > 0
As simple as that!
from smalltools.behavior.suitable_class_finder import SuitableClassFinder
SuitableClassFinder(Vehicle).suitable_for(vehicles[0]) # Returns Car
The sky is the limit!
Notes
- The different
can_handlecases should be disjoint. If there are many subclasses that suits to one case, it will raise an exception. - Subclasses should cover all possible cases. If there is a case that doesn't match with any subclass, then an exception will be thrown.
- You can use a different method than
can_handle. Just replace the desired method in thesuitable_methodargument ofsuitable_forfunction. This could be useful when you have a complexsuitable_objectand you want to be more explicit with the name of the method. - Sometimes, it could be good to return a default class when no result is found (instead of raising an exception). You can do this with the
default_subclassargument ofsuitable_formethod. It's disabled by default, as mentioned at the second item.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file suitable_class_finder-0.1.3.tar.gz.
File metadata
- Download URL: suitable_class_finder-0.1.3.tar.gz
- Upload date:
- Size: 5.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a1a3de4250bee919be3237bc57750d0600aa7a64721c53fae30540f52f65e114
|
|
| MD5 |
7a9f5e935f62235790a53ca67d4f5d2b
|
|
| BLAKE2b-256 |
54d72479d12eeeda34d9b6842e978fab695449c80bcddfb2b2d1886b8eeec601
|
File details
Details for the file suitable_class_finder-0.1.3-py3-none-any.whl.
File metadata
- Download URL: suitable_class_finder-0.1.3-py3-none-any.whl
- Upload date:
- Size: 5.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2c69332c1b247d24eae547f0093155170f89bef3e11c01ef756813aafa36c5bc
|
|
| MD5 |
373b2b383f7a1c883d644bd4c3514cc5
|
|
| BLAKE2b-256 |
98d0c0a857e3e6dff5e51503dafadd9392ac83d9a5d49f7d62ce64c15457f351
|