Skip to content

Instantly share code, notes, and snippets.

@mazza
Created September 29, 2018 17:03
Show Gist options
  • Save mazza/61f4fd18fa7ec58f5c31d224cd3f8f75 to your computer and use it in GitHub Desktop.
Save mazza/61f4fd18fa7ec58f5c31d224cd3f8f75 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#------------------------------------------------------------------------------#
# Snippet to try out a concept of Go2 drafts (generics) using Python. #
#------------------------------------------------------------------------------#
#=> The relevant part is at line 30, where we define a method
# for more than one type at once. Both have field "baz".
# pylint: disable=E1101
# pylint: disable=E1111
# pylint: disable=E1120
def package_main(): # suppose that this scope is a go file
#___ Using Types:
@Type.Struct # One type
def Foo(
bar: int,
baz: str, # <== required
zaz: Any,
): pass
@Type.Struct # Another type
def Zoo(
baz: str, # <== required
): pass
@Func(Foo, Zoo) # <== Method for both types (Foo & Zoo)
def say(self):
print('###', self.baz, '###')
f = Foo(17, '(I\'m f)')
g = Foo(0, 'yaaaeeeey! (I\'m g)', f)
h = Zoo('look, I\'m from another type! (I\'m h)')
g.zaz = h
print(f)
print(g)
g.say()
h.say()
# Note: We use empty functions for structure definitions above for syntatic
# convenience. This avoids using tuples of strings or a maybe-unordered dict
#_____ "Go2-Like" Types definition using decorators:
from typing import Any
def Type(t):
global Type
setattr(Type, t.__name__, t)
return t
def Func(*tlist):
def wrap(f):
for t in tlist:
setattr(t, f.__name__, f)
return f
return wrap
@Type
def Struct(o):
import re
class lit(str): __repr__ = str.__str__
name = o.__name__
spec = o.__annotations__
keys = tuple(spec.keys())
def __repr__(self):
tab = ' '
s = name+'{'
for k in keys:
r = repr(getattr(self, k, None))
r = re.sub('\n', '\n'+tab, r)
s+='\n%s%s: %r' % (tab, k, lit(r))
return s+ '\n}'
def __init__(self, *ar, **kw):
for i, v in enumerate(ar):
setattr(self, self.__slots__[i], v)
for k, v in kw:
setattr(self, k, v)
T = type('Struct', (object,),dict(
__slots__=tuple(keys),
__types__= spec,
__repr__= __repr__,
__str__ = __repr__,
__init__= __init__,
))
return T
package_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment