Skip to content

rudy-reyn/python-recipes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 

Repository files navigation

Python recipes

Overview

This package includes various potentially useful miscellaneous functions and classes, including:

  • Infix operators
  • Variable guards
  • Function pipes
  • Anonymous types

Examples

Infix function operators

Includes infixed function factory for creating infixed functions. These can be used to create pseudo binary operators.

>>> @infixed
>>> def divides(a, b):
...     return b % a == 0
...
>>> 10 |divides| 100
True
>>> @infixed('+')
>>> def strcat(x, y):
...     return  str(x) + str(y)
...
>>> 1 +strcat+ 2
'12'
>>>
>>> Infix = infixed("|")
>>>
>>> @Infix
>>> def tee(content, filename):
...     print(content)
...     with open(filename, "wb+") as file:
...         bytes_written = file.write(content)
...     return bytes_written
...
>>> bytes_written = 'Hello, World!' |tee| "filename.txt"
Hello, World!

Variable guards

>>> from recipes import guard
>>>
>>> natural_num = guard(1, lambda n: n > 0)
>>> natural_num.value
1
>>> zero.value = -1
ValueError("Value does not pass guard")

Guards can also accept types

>>> n = guard(0, (int, float, complex))
>>> n.value
0
>>> n.value = "0"
ValueError("Value does not pass guard")

Pipe functions

>>> from recipes import pipefunc

>>> @pipefunc
>>> def factorial(n, a=1):
...     if n <= 0:
...         return a
...     return factorial(n - 1, n * a)

>>> factorial(5)
120

>>> 5 | factorial
120

Anonymous tuples

>>> from recipes import Tuple

>>> ab = Tuple(a=1, b=2)
>>> print(ab)
(a=1, b=2)

>>> print(Tuple(1, 2, c=3))
(1, 2, c=3)

>>> xy = Tuple(x=1, y=2)
>>> print(xy[0], xy[1])
1 2
>>> print(xy.x, xy.y)
1 2
>>> print(*xy)
1 2

About

miscellaneous function and class factories

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages