User not logged in - login - register
Home Calendar Books School Tool Photo Gallery Message Boards Users Statistics Advertise Site Info
go to bottom | |
 Message Boards » » Python style question Page [1]  
FroshKiller
All American
51913 Posts
user info
edit post

I'm creating a new-style class in Python 3.6. I've defined a property (with the @property decorator) called interaction_id. This is a string value with a maximum length of 100.

Originally, I had naively written the setter like this:

@interaction_id.setter
def interaction_id(self, value: str):
if len(value) > 100:
raise ValueError("Value may not exceed 100 characters.")

self._interaction_id = value

However, I have other string properties with their own limits, and I want to avoid writing a bunch of fucking boilerplate. I thought it'd be nice to have a decorator like this:
@interaction_id.setter
@max_length(100)
def interaction_id(self, value: str):
self._interaction_id = value

My max_length function looks like this:
def maxlength(length):
def maxlength_decorator(func):
def wrapper(*args, **kwargs):
if len(args[1]) > length:
raise ValueError("Value must not exceed {} characters".format(length))
return func(*args, **kwargs)
return wrapper
return maxlength_decorator

This looks like it's a pretty standard pattern for decorators that take arguments, but is there a better method for setter validation that doesn't involve installing a new module? I don't find the decorator definition very readable (although I doubt anyone's going to look at it).

8/13/2018 5:46:49 PM

 Message Boards » Tech Talk » Python style question Page [1]  
go to top | |
Admin Options : move topic | lock topic

© 2024 by The Wolf Web - All Rights Reserved.
The material located at this site is not endorsed, sponsored or provided by or on behalf of North Carolina State University.
Powered by CrazyWeb v2.39 - our disclaimer.