Strong typing implementation for Python

gal kauffman gal.kauffman at gmail.com
Sun Oct 11 15:46:47 EDT 2015


> You can run your code inside a class definition, abuse metaclassing to
replace the namespace with yourown dict and override the __setitem__
function. Then you can implement a var function so it inspect into it's
caller namespace, and inserts the given key into it.
This hack doesn't apply on any sub scope, is not scaleable, and is generaly
bad.

import inspect

# Implement how you see right
class VarError(NameError):
pass
class MissingVarError(VarError):
pass
class ExisitngVarError(VarError):
pass

def namespacemeta(namespace):
class _(type):
@classmethod
def __prepare__(metacls, name, bases):
return namespace()
return _

class staticnamespace(dict):
PRE_USER_SETTED_ITENS = 2

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.items_setted = 0

def var_setitem(self, key, typ):
# Use descriptor object for better control
# Implement type-checking yourself
return super().__setitem__(key, typ)

def __setitem__(self, key, value):
if self.items_setted >= staticnamespace.PRE_USER_SETTED_ITENS: # Ugly hack,
probably won't work IRL
if key not in self:
raise MissingVarError(key)

self.items_setted += 1
return super().__setitem__(key, value)

def var(key, typ):
calling_namespace = inspect.currentframe().f_back.f_locals
if key in calling_namespace:
raise ExisitngVarError(key)

calling_namespace.var_setitem(key, typ)

class _(object, metaclass=namespacemeta(staticnamespace)):
if __name__ == '__main__':
try:
a = 13
except MissingVarError:
print("Couldn't set 'a'")

var('a', int)
a = 37
print(a)

try:
var('a', str)
except ExisitngVarError:
print ("Can't call var twice with the same variable name")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20151011/592cc430/attachment.html>


More information about the Python-list mailing list