jeudi 9 février 2017

Factoring out data validation using Python decorators

Vote count: 0

I have the following two functions in a class of a project that I am currently working on:

def stage_changes(self, change_set_name):
    change_set_id = self._get_change_set_id(change_set_name)
    # Perform validation on change set ID
    self._stage_changes_internal(change_set_id)

def commit_changes(self, change_set_name):
    change_set_id = self._get_change_set_id(change_set_name)
    # Perform validation on change set ID (same validation as first function)
    # Perform some other computation using change set ID
    self._commit_changes_internal(change_set_id, ...)

I'm looking to factor the first two shared lines out of these functions, namely

change_set_id = self._get_change_set_id(change_set_name)
# Perform validation on change set ID

My questions:

  1. This seems like a natural place to use a decorator, since I'm attempting to refactor a shared epilogue out of multiple functions. Does using a decorator actually make sense here, or am I trying to be too creative in a place where I should just be calling a simple helper function?
  2. If it does make sense to use a decorator, how would I go about structuring it? It seems as though it might be cumbersome to do so, given that I need the value computed in the common epilogue to perform additional computation in each function(i.e. the shared logic does more than just produce a side-effect, it returns a value).

Cheers!

asked 15 secs ago

Let's block ads! (Why?)



Factoring out data validation using Python decorators

Aucun commentaire:

Enregistrer un commentaire