2

I'm writing a library of Python functions to transform a dataset, and for each one I need to make some basic checks on the transformed data:

  1. There should be no negative values in the dataset after transforming
  2. The sum of all values in the transformed dataset should be in some specified ratio to the sum of the values before transforming.

For the first task, I can give all my functions a decorator with a name like check_for_negatives.

For the second task however, the ratio of output to input will vary with each call to a particular function, depending on the input parameters - so the caller might expect the sum of the dataset to be unchanged, or to be x1.5, for different calls of the same function.

The only way I can see to do this with decorators is to have a decorator to check the input:output ratio, but pass in the expected ratio as an argument to the function itself (though the function wouldn't use it directly). This doesn't seem very nice; is there a better way?

1 Answer 1

2

You can use a class as a decorator, so that you can define instance variables that you can change at runtime. Example implementation here

in your case you would have a ratio instance variable so that before each call to the decorated function foo you could set foo.ratio to the appropiate value.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I don't think I do want that, because the expected ratio will depend on the function arguments - it's not constant for a given function. The caller needs to be able to pass in the expected ratio in some way.
Thanks, that works and is certainly nicer than passing magic arguments to the function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.