Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
a-recknagel / hack.py
Created November 14, 2019 08:05
ugly runtime install
try:
import requests
except Exception:
from pip._internal.main import main as pip_main
pip_main(['install', 'requests'])
import requests
print(f"installed requests version {requests.__version__}")
@a-recknagel
a-recknagel / veget.py
Created November 11, 2019 07:29
ClassVar based dataclass instance counter
from dataclasses import dataclass, field
from typing import ClassVar, List
@dataclass
class Veget:
index: int = field(init=False)
name: str
price: float
quantity: int
@a-recknagel
a-recknagel / _untimed_code.py
Last active August 29, 2019 12:20
Timing re operations
# code that I would write in an interactive session to perform a re.search or re.sub
# setup code
>>> import re
>>> text = open('lorem_ipsum.txt').read() # filled with https://loremipsum.io/generator/?n=99&t=p
>>> regex = re.compile('foo')
# test code for re.search
>>> regex.search(text) # returns None, there is no foo in lorem ipsum it seems
@a-recknagel
a-recknagel / .coveragerc
Created August 28, 2019 14:13
gitlab CI template
[run]
branch = True
source = my_django_lib
omit =
src/my_django_lib/settings.py
*/__init__.py
[paths]
source = src
@a-recknagel
a-recknagel / mypackage.mypackage.__init__.py
Last active August 22, 2019 14:15
packaging and version fields
__version__ = '1.2.3'
@a-recknagel
a-recknagel / piping.py
Last active August 22, 2019 07:23
change pipes in idle
import os
import sys
from subprocess import run, PIPE, STDOUT
# set pipes
IN_IDLE = 'idlelib' in sys.modules
if IN_IDLE:
STD_OUT = PIPE
STD_ERR = STDOUT
else:
@a-recknagel
a-recknagel / simple_proxy.py
Created August 15, 2019 14:59
simple proxy
from collections import defaultdict
class Proxy:
def __init__(self, instance):
self.instance = instance
self.last_call = None
self.call_map = defaultdict(int)
def __getattr__(self, name):
@a-recknagel
a-recknagel / function_to_method.py
Last active August 14, 2019 08:06
descriptors #1
def a(self):
return self
# write, and optionally modify class A in a way where the following will work
inst = A()
print(inst.sub.a() is inst) # True
# ------------------------------------- instance methods through class binding
# if there were no subspace, this would just work:
@a-recknagel
a-recknagel / call.py
Last active August 8, 2019 07:39
Callstacks
# no callstack, we directly crash through to the intepreter
>>> raise ValueError()
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError
# we raise in a function, we crash to line two, which called the function
>>> def a():
... raise ValueError()
...
@a-recknagel
a-recknagel / skip_classVars.py
Created August 7, 2019 11:34
inspect __init__ to skip classVars
from dataclasses import InitVar, field, dataclass
import typing
import inspect
import re
CV = typing.ClassVar # this kills the regex ._.
@dataclass
class Foo: