Skip to content

Instantly share code, notes, and snippets.

@baileywickham
Last active September 23, 2020 04:58
Show Gist options
  • Save baileywickham/5db487d33de21e6c4a0e8a092dadca2b to your computer and use it in GitHub Desktop.
Save baileywickham/5db487d33de21e6c4a0e8a092dadca2b to your computer and use it in GitHub Desktop.
Metaclasses in python
# Create classes based on csv file data
with open("file.csv", 'r') as f:
header = f.readline().split(',')
metaclass = type('csv', (object,), {h:None for h in header})
for line in f.readlines():
m = metaclass()
line = line.split(',')
for i in range(len(header)):
setattr(m, header[i], line[i])
yield m # Return as generator
# These are equivilent definitions
class X:
a = 1
def hello(self, k):
return k
a = type('Y', (object,), {'a':1, 'hello':lambda self, k: k})
print(a().hello('hello from a metaclass'))
# This is equivilent to X(), instances are created with __new__,
# which returns an instance to be initated by __init__.
x = object.__new__(X)
if type(x) == X: # If X were a factory class it wouldn't make sense to call __init__() on it.
x.__init__()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment