Skip to content

Instantly share code, notes, and snippets.

View bmispelon's full-sized avatar

Baptiste Mispelon bmispelon

View GitHub Profile
@bmispelon
bmispelon / checkchoices.py
Last active December 6, 2020 17:39
A Django management command to find model fields where the declared choices doesn't match what's in the database
"""
When a model field defines a `choices` attribute, Django doesn't actually
generate a database constraint for that, which means it's possible to insert
data that doesn't match the choices.
See https://adamj.eu/tech/2020/01/22/djangos-field-choices-dont-constrain-your-data/
This command scans your database to try and find which fields have mismatched
data.
By default it scans all fields of all models of all installed apps, doing one
@bmispelon
bmispelon / test_enums.py
Created October 27, 2020 18:17 — forked from hjwp/test_enums.py
Better string enums
import random
from enum import Enum, EnumMeta, IntEnum
class GoatEnumMeta(EnumMeta):
def __getitem__(cls, item):
if isinstance(item, int):
item = cls._member_names_[item]
return super().__getitem__(item)
@bmispelon
bmispelon / tuple.py
Created May 20, 2020 13:51
How to handle tuple creation in a generic way?
def my_tuple_function(t):
"""
Return a new tuple of the same length containing only zeroes.
"""
tuple_class = type(t)
return tuple_class(*(0 for _ in t)) # works for namedtuple
return tuple_class((0 for _ in t)) # works for plain tuple
# https://mobile.twitter.com/dabeaz/status/1199367834691932160
"""
As a oneliner:
ᚐ = type('ᚐ',(object,),{'ᚐ':{},'__getattr__':lambda s,a:s.ᚐ[a],'__setattr__':lambda s,a,v:s.ᚐ.__setitem__(a,s.ᚐ[a]+v)if a in s.ᚐ else s.ᚐ.__setitem__(a,v)})()
for ᚐ.i, ᚐ.s in [(600, 'sa'), (60, 'ta'), (6, 'n')]:
pass
@bmispelon
bmispelon / cooldigits.py
Created November 25, 2019 10:35
A script to convert boring ASCII digits in your strings. Try it with `./cooldigits.py $(date)`
import argparse
from functools import partial
import unicodedata
# based on https://www.fileformat.info/info/unicode/category/Nd/list.htm
ALPHABETS = {
'ARABIC-INDIC',
'EXTENDED ARABIC-INDIC',
'NKO',
'DEVANAGARI',
@bmispelon
bmispelon / fullwidth.py
Created November 29, 2018 12:33
Fun with fullwidth unicode characters
class MyClass:
my_attr = 42
print(MyClass.my_attr)
print(MyClass.my_attr)
print(getattr(MyClass, 'my_attr'))
print(getattr(MyClass, 'my_attr'))
@bmispelon
bmispelon / CPV.txt
Created October 23, 2018 12:20
A list of CPV codes with their checksum. Can you guess the checksum algorithm used?
03000000-1
03100000-2
03110000-5
03111000-2
03111100-3
03111200-4
03111300-5
03111400-6
03111500-7
03111600-8
from django.forms.widgets import MultiWidget
def form_to_POST(form):
"""
Given a form, convert its initial data into a dict that can simulate
the request.POST that would be generated if that form was submitted as-is.
This will respect the form's prefix and will convert all field values to
strings.
"""
Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.mail import send_mail
>>> send_mail('hello', 'world', '[email protected]', [u'Báptiste [asdf] <[email protected]>'])
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
"""
ValueError: not enough values to unpack (expected 3, got 2)
ValueError: too many values to unpack (expected 3)
"""
def unpack(iterable, length):
i = iter(iterable)
ret = [x for x, _ in zip(i, range(length))]