Last active
June 24, 2019 17:17
-
-
Save crodriguez1a/7d1929f6ad09b82f392191b7518e8c59 to your computer and use it in GitHub Desktop.
Pythonic Pure Functions with Static Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Background: | |
Pure functions are functions that have no side effects and always perform | |
the same computation resulting in the same ouput, given a set inputs. These | |
functions should only ever have access to the function scope. (1) | |
Static Methods (using @staticmethod decorator) can conceptually be treated as | |
"pure" since they do not have access to the either `cls` or `self` and must in | |
turn rely soley on input parameters to compute output. | |
""" | |
class MyName: | |
def __init__(self, name:str): | |
# initialize name | |
self._name = self.capitalize(name) | |
@staticmethod | |
def capitalize(name:str) -> str: # no access to self or cls | |
# pure, since it only ever peforms the same computation and only has access to function scope (name parameter) | |
return name.upper() | |
@property | |
def name(self) -> str: | |
return self._name | |
my_name:MyName = MyName(name='Berto') | |
print(my_name.name) # -> BERTO | |
caps_name = my_name.capitalize('Ernesto') | |
print(caps_name) # -> ERNESTO | |
# NOTE: in practice, you may not choose to encapsulate something as generic as capitalization. | |
# Sources: | |
# 1. Becoming Functional - Joshua Backfield |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment