Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@poros
poros / star.py
Created October 5, 2015 23:11
Create APIs with multiple aguments instead of a list
def func(msg, numbers):
print msg
for x in numbers:
print x
func("My numbers are:", [0, 1, 2])
"My numbers are:"
0
1
2
@poros
poros / keyword_only_args.py
Last active October 23, 2015 01:34
Keyword-only arguments
def func(arg1, arg2, arg3=10, arg4=0):
...
# problem
func(1, 2, 10, 0)
# or ?
func(1, 2, 0, 10)
# PYTHON 3 ONLY
def func(arg1, arg2, *, arg3=10, arg4=0):
@poros
poros / defaultdict_callable.py
Created October 6, 2015 00:03
Defaultdict with default custom class
from collection import defaultdict
class Number(object):
def __init__(self, N):
self.N = N
def __repr__(self):
return str(self.N)
d = defaultdict(Number)
@poros
poros / dictionary_callbacks.py
Created October 6, 2015 01:02
Dictionary of callbacks or constructors
menu = {
'square': lambda x: x * x,
'cube': lambda x: x * x * x,
'half': lambda x: x / 2,
'double': lambda x: x * 2,
}
command = raw_input()
menu[command](4)
@poros
poros / fixture_composition_mock.py
Last active January 19, 2021 17:02
Compose pytest fixtures at the same level and mock.patch
@pytest.fixture
def stream():
return mock.Mock(spec=Stream)
@pytest.fixture
def output():
return open('test.txt', 'w')
@pytest.fixture
def tailer(self, stream, output):
@poros
poros / type_subclass.py
Created October 6, 2015 01:31
Build a subclass on-the-fly in a pytest fixture
def BaseRobot(object):
def __init__(self):
assert self.owner
@pytest.fixture
def robot():
return type('TestRobot', (BaseRobot,), dict(owner='antonio'))()
# instead of
def TestRobot(BaseRobot):
@poros
poros / pytest_parametrize_ids.py
Created October 6, 2015 01:38
Parametrized pytest testcase with dictionary of parameters and human readable testcase names
test_params = {
'empty_line': ('', {}),
'get_ok': ('GET 200', {'request': 'GET', 'status': '200'}),
'get_not_found': ('GET 404', {'request': 'GET', 'status': '404'}),
}
@pytest.mark.parametrize('line,expected', test_params.values(), ids=test_params.keys())
def test_decode(self, line, expected):
assert Decoder().decode(line) == expected
@poros
poros / mock_side_effect.py
Created October 6, 2015 01:42
Mock side effect
# raise exception
mock = Mock(side_effect=KeyError('foo'))
mock()
# KeyError: 'foo'
# return value based on argument
values = {'a': 1, 'b': 2, 'c': 3}
def side_effect(arg):
return values[arg]
@poros
poros / genlog.py
Last active October 7, 2015 09:06
Process a file in a functional style with generators (no temporary lists!)
wwwlog = open("access-log")
total = 0
for line in wwwlog:
bytestr = line.rsplit(None,1)[1]
if bytestr != '-':
total += int(bytestr)
print "Total", total
@poros
poros / tail_gen.py
Created October 7, 2015 09:18
Follow a file like tail -f with generators
import time
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line