Skip to content

Instantly share code, notes, and snippets.

View treyhunner's full-sized avatar
🐍
💖

Trey Hunner treyhunner

🐍
💖
View GitHub Profile
@treyhunner
treyhunner / shell.py
Last active May 22, 2024 20:00
New Python REPL (Python 3.13+) in Django shell
# fork of https://github.com/django/django/blob/b7c7209c67f742eda8184c46f139e0e1cb16a1f4/django/core/management/commands/shell.py
import os
import select
import sys
import traceback
from django.core.management import BaseCommand, CommandError
from django.utils.datastructures import OrderedSet
@treyhunner
treyhunner / super.py
Created March 1, 2022 18:40
The built-in super function, re-implemented
import inspect
_SENTINEL = object()
class super:
"""The built-in super "function" re-implemented."""
@treyhunner
treyhunner / utf8ify.py
Last active September 22, 2022 18:30
I implemented code to convert unicode code points to UTF-8, just for fun. Inspired by https://sethmlarson.dev/blog/utf-8
"""
Just some code that needlessly converts unicode codepoints to UTF-8.
Example:
$ python utf8ify.py U+2728
Bytes: 0xe2 0x9c 0xa8
Text: ✨
$ python utf8ify.py U+1F3F3 U+FE0F U+200D U+1F308
@treyhunner
treyhunner / my_unicodedata_db.py
Created January 21, 2022 23:07
Generates a JSON file of all unicode characters, their name, and their aliases. This is a hack but it works.
"""
Tool that names each unicode character based on their name or their aliases
Must be run from the cpython repo root directory:
https://github.com/python/cpython/tree/3.10
Relies on Tools.unicode being an importable path due to implicit packages
"""
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
@treyhunner
treyhunner / reversible_flags.py
Created January 21, 2022 18:21
Python script to identify all Unicode flags that represent a different flag when reversed
"""
Script to print all Unicode flag emoji are also a valid flag when reversed.
Output of this script:
🇦🇬 (Antigua and Barbuda) reverses to 🇬🇦 (Gabon)
🇦🇱 (Albania) reverses to 🇱🇦 (Lao People's Democratic Republic)
🇦🇲 (Armenia) reverses to 🇲🇦 (Morocco)
🇦🇶 (Antarctica) reverses to 🇶🇦 (Qatar)
🇦🇸 (American Samoa) reverses to 🇸🇦 (Saudi Arabia)
@treyhunner
treyhunner / walrus_oddity.py
Created November 10, 2021 16:04
Operator precedence walrus operator oddity
"""
while n < 10 and chunk := f.read(256): # SyntaxError
while n < 10 and (chunk := f.read(256)): # Works
while chunk := f.read(256) and n < 10: # chunk will be a boolean 😮
"""
from io import StringIO
@treyhunner
treyhunner / rectangle.py
Created November 5, 2021 16:49
Demo of property getter/setter in Python
class Rectangle:
def __init__(self, width, height):
self.width, self.height = width, height
def __repr__(self):
return f"Rectangle({self.width}, {self.height})"
@property
def area(self):
@treyhunner
treyhunner / easy_repr.py
Created November 4, 2021 19:32
Example of sorting a dictionary of attributes by keys
def easy_repr(obj):
"""
Function to find the type of an object and its attributes
Example:
>>> class Point:
... def __init__(self, x, y, z, color=None):
... self.x, self.y, self.z = x, y, z
... self.color = color
@treyhunner
treyhunner / flatten_time.py
Created November 2, 2021 20:27
Demo of why sum(list_of_lists, []) is a bad idea (from a performance perspective)
"""
Demonstration of how slow sum can be for flattening lists-of-lists
Output on my machine:
0.019118324998999014 itertools.chain.from_iterable
0.03325132900135941 comprehension
10.947899631002656 sum
Using sum on a list results in a loop inside a loop (a new list is made for
each new sub-list) so the more sub lists there are, the bigger the timing
# django.template.defaulttags.autoescape rewritten using Python 3.10's match/case statement
@register.tag
def autoescape(parser, token):
"""
Force autoescape behavior for this block.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
match token.contents.split():
case [_, ('on' | 'off') as arg]:
nodelist = parser.parse(('endautoescape',))