Skip to content

Instantly share code, notes, and snippets.

@mssola
Created October 23, 2013 12:35
Show Gist options
  • Save mssola/7117835 to your computer and use it in GitHub Desktop.
Save mssola/7117835 to your computer and use it in GitHub Desktop.
Map model names into database tables by using metaprogramming in Python.
class Persistent(type):
def __new__(self, name, bases, dct):
self.tables = dict()
return super(Persistent, self).__new__(self, name, bases, dct)
def __init__(self, name, bases, dct):
table = name.lower() + 's'
self.tables[self] = table
super(Persistent, self).__init__(name, bases, dct)
class Model(object, metaclass = Persistent):
def table_name(self):
return Persistent.tables[self.__class__]
class User(Model):
pass
u = User()
print(u.table_name())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment