Skip to content

Instantly share code, notes, and snippets.

@wolever
Last active December 23, 2015 07:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/6603290 to your computer and use it in GitHub Desktop.
Save wolever/6603290 to your computer and use it in GitHub Desktop.
Short Python tips, sometimes with a Django bent, sometimes without unit tests.
def _autofmthelper(name, fmt, postprocess=None):
def fmtfunc(self):
result = fmt.format(self=self)
if postprocess is not None:
result = postprocess(self, result)
return result
fmtfunc.__name__ = name
return fmtfunc
def autounicode(fmt):
""" Returns a simple ``__unicode__`` function::
>>> class Person(object):
... name = "Alex"
... __unicode__ = autounicode("{self.name}")
...
>>> unicode(Person())
u'Alex'
>>>
"""
return _autofmthelper("__unicode__", unicode(fmt))
def autostr(fmt):
""" Returns a simple ``__str__`` function::
>>> class Person(object):
... name = "Alex"
... __str__ = autostr("{self.name}")
...
>>> str(Person())
'Alex'
>>>
"""
fmt = str(fmt)
return _autofmthelper("__str__", str(fmt))
def autorepr(fmt):
""" Returns a simple ``__repr__`` function::
>>> class Person(object):
... name = "Alex"
... __repr__ = autorepr("name={self.name!r}")
...
>>> repr(Person())
"<__main__.Person name='Alex' at 0x...>"
>>>
"""
return _autofmthelper("__repr__", str(fmt), lambda self, result: (
"<%s.%s %s at 0x%x>" %(
self.__class__.__module__,
self.__class__.__name__,
result,
id(self),
)
))
# Django URLs can be nested within one file!
# Have a bunch of URLs with a verbose prefix? Group them together!
# boo bad and ugly and not fun:
urlpatterns = patterns(''
url('^(?P<wikipage_title_slug>\w+)-(?P<wikipage_id>\w+)/history$', …),
url('^(?P<wikipage_title_slug>\w+)-(?P<wikipage_id>\w+)/edit$', …),
url('^(?P<wikipage_title_slug>\w+)-(?P<wikipage_id>\w+)/discuss$', …),
url('^(?P<wikipage_title_slug>\w+)-(?P<wikipage_id>\w+)/permissions$', …),
)
# yay happy and pretty and fun:
urlpatterns = patterns(''
url('^(?P<wikipage_title_slug>\w+)-(?P<wikipage_id>\w+)/', include(patterns('',
url('^history$', …),
url('^edit$', …),
url('^discuss$', …),
url('^permissions$', …),
)),
)
def quote_component(s):
""" Returns a strint suitable for use as any component in a URL::
>>> quote_component("/ +%#")
'%2F%20%2B%25%23'
Note that this is especially useful with Django's ``reverse()``, which
does not automatically quote anything::
reverse("my-view", kwargs={"name": quote_component(person.name)})
"""
return urllib.quote(smart_str(s), safe="-_.!~*'()")
from django.template.defaultfilters import slugify
def slug_property(attr):
""" ``property`` which returns a slugified version of ``attr``. Useful
with Models::
>>> class WikiPage(m.Model):
... title = m.CharField(max_length=64)
... title_slug = slug_property("title")
...
>>> p = WikiPage(title="Hello, World!")
>>> p.title_slug
'hello-world'
"""
def slug_property_helper(self):
return slugify(getattr(self, attr))
return property(slug_property_helper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment