Standardise on class constructor methods for object creation from different formats
- Dominant language
- Python
- Stars
- 67
- Forks
- 18
- Avg merge
- 2h 26m
- Merged PRs (30d)
- 1
Description
I propose we use **class constructor methods** for all methods that instantiate objects from external input formats. This is a common "pythonic" pattern: see for example `pd.DataFrame.from_dict()`, `pd.DataFrame.from_records()`.
Andy & I have been trying to roll out this pattern across resqpy, but currently we're a bit inconsistent and many classes need to be refactored. It is already implemented in a number of classes, for example `resqpy.well.DeviationSurvey.from_data_frame` .
**How constructor methods are called by users**
Class methods are called from the class directly, without first having to instantiate an object:
```python
# Good
survey1 = DeviationSurvey.from_data_frame(df=df)
survey2 = DeviationSurvey.from_ascii_file(path="file.dat")
```
This is cleaner than first instantiating a messy "empty" object, and then calling another method to populate the attributes:
```python
# Not as good
survey = DeviationSurvey(data=None)
survey.from_data_frame(df)
```
**Rationale**
- The init method becomes simpler: does not need any logic relating to file formats, makes it clearer what are the important data attributes
- Init method can assume data is actually given when class is created: can do validation, type checking et cetera in one place.
- Each constructor method is completely independent, the loading is done _before_ the object is instantiated.
**Example implementation**
```python
class DeviationSurvey:
def __init__(self, data):
# Arguments are the fundamental data needed to instantiate the class
self.data = validate_inputs(data) # Data is a mandatory attribute
@classmethod
def from_file(cls, file):
with open(file) as f:
data = f.read()
return cls(data=data) # This calls the init method
```
**Checklist**
- [x] DeviationSurvey
- [x] Polyline
- [x] Property
- [x] TetraGrid
- [ ] #305
- [x] #158
- [ ] #167
- [ ] #303
Contributor guide
Research direction
Start by comparing the implemented DeviationSurvey, Polyline, Property, and TetraGrid patterns with the remaining checklist items (#305, #167, and #303). Review each affected class's current construction and input-format methods, then standardize the applicable object creation paths on class constructor methods and update the checklist when the remaining work is complete.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend-api-design
- Issue type
- Refactor
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100