Skip to content

Instantly share code, notes, and snippets.

@icecrime
Last active August 29, 2015 13:57
Show Gist options
  • Save icecrime/9705220 to your computer and use it in GitHub Desktop.
Save icecrime/9705220 to your computer and use it in GitHub Desktop.
Go interfaces and type assertions compared to Python's Abstract Base Classes
#!/usr/bin/env python
import abc
### Go equivalent
#
# type Lock interface {
# Lock()
# Unlock()
# }
class Lock:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def Lock():
pass
@abc.abstractmethod
def Unlock():
pass
### Go equivalent
#
# type Mutex struct {}
#
# func (m Mutex) Lock() {}
# func (m Mutex) Unlock() {}
class Mutex(object):
def Lock():
pass
def Unlock():
pass
# /!\ This is the important difference /!\
# Pyhon's abc requires explicit type registration.
Lock.register(Mutex)
### Go equivalent
#
# func main() {
# var m Mutex
# var o interface{} = m
#
# res, ok := o.(Lock)
# fmt.Println(res, ok)
# }
def type_assertion(instance, type_):
return instance if isinstance(instance, type_) else None
if __name__ == "__main__":
m = Mutex()
print type_assertion(m, Lock)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment