Python Properties in an easy and typed-checked way

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 10.07.20
@author: eisenmenger
"""

# Imagine you're creating a class with several properties, then you will most likely use the built-in property function
# but as you maybe noticed before this will be not really conform with the DRY principal


class Dummy:
attr = 1

@property
def a(self):
return self.attr

@a.setter
def a(self, val):
self.attr = val


# I want to present you a package from an awesome developer called Rudd van der Ham
# he created the package easy_property which you can find here https://github.com/salabim/easy_property
# this will help you to be conform with the DRY principal, and you know on the first sign what the method will do

from easy_property import getter_setter, setter, getter


class Dummy:
attr = 1

@getter_setter # here you will have all in one place
def a(self, val=None):
if val is not None:
self.attr = val
return val

@setter # a setter only method
def b(self, val):
self.attr = val

@getter # a getter only method
def b(self, val):
return self.attr


# Now we will have in my eyes only one tiny problem, checking the type.
# Therefore I extended my project https://github.com/FelixTheC/strongtyping#setter
# and include the easy_property setter and getter_setter so that we can do now the following with the help of typing

from strongtyping.strong_typing import setter, getter_setter


class Dummy:
attr = 1

@getter_setter
def a(self, val: int =None):
if val is not None:
self.attr = val
return self.attr

@setter
def b(self, val: int):
self.attr = val


if __name__ == '__main__':

d = Dummy()

d.a = 100
print(d.a)
d.b = 3
print(d.a)

d.a = 'Some string' # will raise a TypeMisMatch Exception
d.b = 'Some other string' # will raise a TypeMisMatch Exception

easy_property
strongtyping


Link: strongtyping

10 Jul. 20
Zurück

© 2017 - 2020 FtC-Webdev