def __init__(self): group = self.AddGroup('Regular Keys') #list = sorted(tv_keys_standard, key=lambda tup: tup[2]) list = tv_keys_standard for className,code,name in list: clsAttributes = dict(name=name, description="<b>" + name + "</b> (" + code + ")", value=code) cls = ClassType(className, (KeyAction,), clsAttributes) group.AddAction(cls) group = self.AddGroup('Extended Keys') list = sorted(tv_keys_extended, key=lambda tup: tup[2]) for className,code,name in list: clsAttributes = dict(name=name, description="<b>" + name + "</b> (" + code + ")", value=code) cls = ClassType(className, (KeyAction,), clsAttributes) group.AddAction(cls) group = self.AddGroup('Other Keys') list = sorted(tv_keys_other, key=lambda tup: tup[2]) for className,code,name in list: clsAttributes = dict(name=name, description="<b>" + name + "</b> (" + code + ")", value=code) cls = ClassType(className, (KeyAction,), clsAttributes) group.AddAction(cls) self.AddAction(self.MyKey)
def __init__(self): self.host = "localhost" self.port = 4025 self.envisalinkuser = "******" self.envisalinkpass = "******" self.isSessionRunning = False self.timeline = "" self.waitStr = None self.waitFlag = threading.Event() self.session = None self.debug = False self.lastupdatevalue = "" group = self.AddGroup('Envisalink Virtual Keypad') className = 'ArmStay' clsAttributes = dict(name='Arm Stay', command='3') cls = ClassType(className, (NvAction, ), clsAttributes) group.AddAction(cls) className = 'ArmAway' clsAttributes = dict(name='Arm Away', command='2') cls = ClassType(className, (NvAction, ), clsAttributes) group.AddAction(cls) className = 'Off' clsAttributes = dict(name='Off', command='1') cls = ClassType(className, (NvAction, ), clsAttributes) group.AddAction(cls) self.AddAction(self.MyCommand) self.AddEvents()
def __init__(self): self.host = 'localhost' self.port = 4025 self.envisalinkuser = '******' self.envisalinkpass = '******' self.isSessionRunning = False self.isAuthenticated = False self.waitStr = None self.waitFlag = threading.Event() self.session = None self.debug = False group = self.AddGroup('Envisalink Virtual Keypad') className = 'ArmStay' clsAttributes = dict(name='Arm Stay', command = '3') cls = ClassType(className, (NvAction,), clsAttributes) group.AddAction(cls) className = 'ArmAway' clsAttributes = dict(name='Arm Away', command = '2') cls = ClassType(className, (NvAction,), clsAttributes) group.AddAction(cls) className = 'Off' clsAttributes = dict(name='Off', command = '1') cls = ClassType(className, (NvAction,), clsAttributes) group.AddAction(cls) self.AddAction(self.MyCommand) self.AddEvents()
def AddAction( self, actionCls, clsName=None, name=None, description=None, value=None, hidden=False ): if not issubclass(actionCls, eg.ActionBase): raise Exception("Actions must be subclasses of eg.ActionBase") if clsName is not None: actionCls = ClassType( clsName, (actionCls, ), dict(name=name, description=description, value=value), ) plugin = self.plugin pluginInfo = plugin.info actionClsName = actionCls.__name__ icon = pluginInfo.icon if actionCls.iconFile: try: path = join(pluginInfo.path, actionCls.iconFile + ".png") icon = eg.Icons.PathIcon(path) except: eg.PrintError( "Error while loading icon file %s" % actionCls.iconFile ) if icon == eg.Icons.PLUGIN_ICON: icon = eg.Icons.ACTION_ICON else: icon = eg.Icons.ActionSubIcon(icon) text = self.Translate(plugin, actionCls, actionClsName) actionCls = ClassType( actionClsName, (actionCls, ), dict( name=text.name, description=text.description, plugin=plugin, info=ActionInfo(icon), text=text, Exceptions=eg.Exceptions ) ) pluginInfo.actions[actionClsName] = actionCls actionCls.OnAddAction() if not hidden: self.items.append(actionCls) return actionCls
def get_wrapped(cls, rdf_types): """I return an appropriate subclass of `cls` for the given `rdf_types`. "Appropriate" means that the subclass will inherit the `registered mixin <register_wrapper>`:func: class associated with `rdf_types`. When inheriting several classes, the rdf types will first be sorted in lexicographic order; this ensures for deterministic behaviour when several mix-in classes define the same method. """ rdf_types = tuple(sorted(rdf_types)) ret = _CLASS_CACHE.get((cls, rdf_types)) if ret is None: parents = [cls] cls_name = cls.__name__ for typ in rdf_types: mixin = _WRAPPER_REGISTRY.get(typ) if mixin is None or issubclass(cls, mixin): continue else: parents.append(mixin) cls_name = "%s_%s" % (cls_name, mixin.__name__) if len(parents) == 1: ret = cls else: ret = ClassType(cls_name, tuple(parents), {}) _CLASS_CACHE[(cls, rdf_types)] = ret return ret
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._apply_rule(widget, rule, rule, template_ctx=ctx) return widget
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if not name in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, defs, fn = self.templates[name] name, baseclasses key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._push_widgets() self._push_ids() self.idmap = copy(global_idmap) self.idmap['root'] = widget self.idmap['ctx'] = QueryDict(ctx) self.build_item(widget, defs, is_rule=True) self._pop_ids() self._pop_widgets() return widget
def __getattr__(self, name): classes = self.classes if name not in classes: raise FactoryException('Unknown class <%s>' % name) item = classes[name] cls = item['cls'] # No class to return, import the module if cls is None: if item['module']: module = __import__(name=item['module'], fromlist='.') if not hasattr(module, name): raise FactoryException( 'No class named <%s> in module <%s>' % (name, item['module'])) cls = item['cls'] = getattr(module, name) elif item['baseclasses']: rootwidgets = [] for basecls in item['baseclasses'].split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) else: raise FactoryException('No information to create the class') return cls
def test_suite(): suite = TestSuite() for kv in ( 'OO', 'II', 'IO', 'OI', 'IF', 'LL', 'LO', 'OL', 'LF', ): for name, bases in ( ('BTree', (MappingBase, TestCase)), ('Bucket', (MappingBase, TestCase)), ('TreeSet', (SetTests, TestCase)), ('Set', (SetTests, TestCase)), ): klass = ClassType(kv + name + 'Test', bases, dict(t_type=globals()[kv + name])) suite.addTest(makeSuite(klass)) suite.addTest(makeSuite(NastyConfict)) return suite
def FromModuleInfo(cls, moduleInfo): self = cls.__new__(cls) self.__dict__.update(moduleInfo.__dict__) pathname = join(self.path, "__init__.py") if not exists(pathname): eg.PrintError("File %s does not exist" % pathname) return None if self.path.startswith(eg.corePluginDir): moduleName = "eg.CorePluginModule." + self.pluginName else: moduleName = "eg.UserPluginModule." + self.pluginName try: if moduleName in sys.modules: module = sys.modules[moduleName] else: module = __import__(moduleName, None, None, ['']) except: eg.PrintTraceback( "Error while loading plugin-file %s." % self.path, 1 ) return None pluginCls = module.__pluginCls__ self.module = module self.pluginCls = pluginCls englishText = pluginCls.text if englishText is None: englishText = ClassType("EmptyDefaultText", (), {}) englishText.name = self.englishName englishText.description = self.englishDescription # TODO: the text class should be referenced by the GUID instead of # pluginCls.__name__ translatedText = getattr(eg.text.Plugin, pluginCls.__name__, None) if translatedText is None: setattr(eg.text.Plugin, pluginCls.__name__, englishText) text = englishText else: SetDefault(translatedText, englishText) text = translatedText pluginCls.text = text pluginCls.name = text.name pluginCls.description = text.description return self
def FromModuleInfo(cls, moduleInfo): self = cls.__new__(cls) self.__dict__.update(moduleInfo.__dict__) pathname = join(self.path, "__init__.py") if not exists(pathname): eg.PrintError("File %s does not exist" % pathname) return None if self.path.startswith(eg.corePluginDir): moduleName = "eg.CorePluginModule." + self.pluginName else: moduleName = "eg.UserPluginModule." + self.pluginName try: if moduleName in sys.modules: module = sys.modules[moduleName] else: module = __import__(moduleName, None, None, ['']) except: eg.PrintTraceback( eg.text.Error.pluginLoadError % self.path, 1 ) raise eg.Exceptions.PluginLoadError() pluginCls = module.__pluginCls__ self.module = module self.pluginCls = pluginCls englishText = pluginCls.text if englishText is None: englishText = ClassType("EmptyDefaultText", (), {}) englishText.name = self.englishName englishText.description = self.englishDescription # TODO: the text class should be referenced by the GUID instead of # pluginCls.__name__ translatedText = getattr(eg.text.Plugin, pluginCls.__name__, None) if translatedText is None: setattr(eg.text.Plugin, pluginCls.__name__, englishText) text = englishText else: SetDefault(translatedText, englishText) text = translatedText pluginCls.text = text pluginCls.name = text.name pluginCls.description = text.description return self
def Translate(self, plugin, actionCls, actionClsName): defaultText = actionCls.text if defaultText is None: defaultText = ClassType(actionClsName, (), {}) translatedText = getattr(plugin.text, actionClsName, None) if translatedText is None: translatedText = ClassType(actionClsName, (), {}) setattr(plugin.text, actionClsName, translatedText) SetDefault(translatedText, defaultText) if not hasattr(translatedText, "name"): name = actionCls.name translatedText.name = actionClsName if name is None else name if not hasattr(translatedText, "description"): description = actionCls.description translatedText.description = (translatedText.name if description is None else description) return translatedText
def Translate(self, plugin, actionCls, actionClsName): defaultText = actionCls.text if defaultText is None: defaultText = ClassType(actionClsName, (), {}) translatedText = getattr(plugin.text, actionClsName, None) if translatedText is None: translatedText = ClassType(actionClsName, (), {}) setattr(plugin.text, actionClsName, translatedText) SetDefault(translatedText, defaultText) if not hasattr(translatedText, "name"): name = actionCls.name translatedText.name = actionClsName if name is None else name if not hasattr(translatedText, "description"): description = actionCls.description translatedText.description = ( translatedText.name if description is None else description ) return translatedText
def load(val, import_custom_exceptions, instantiate_custom_exceptions, instantiate_oldstyle_exceptions): if val == consts.EXC_STOP_ITERATION: return StopIteration # optimization if type(val) is str: return val # deprecated string exceptions (modname, clsname), args, attrs, tbtext = val if import_custom_exceptions and modname not in sys.modules: try: mod = __import__(modname, None, None, "*") except ImportError: pass if instantiate_custom_exceptions: cls = getattr(sys.modules[modname], clsname, None) elif modname == "exceptions": cls = getattr(exceptions, clsname, None) else: cls = None if not isinstance(cls, (type, ClassType)): cls = None elif issubclass(cls, ClassType) and not instantiate_oldstyle_exceptions: cls = None elif not issubclass(cls, BaseException): cls = None if cls is None: fullname = "%s.%s" % (modname, clsname) if fullname not in _generic_exceptions_cache: fakemodule = {"__module__": "%s.%s" % (__name__, modname)} if isinstance(GenericException, ClassType): _generic_exceptions_cache[fullname] = ClassType( fullname, (GenericException, ), fakemodule) else: _generic_exceptions_cache[fullname] = type( fullname, (GenericException, ), fakemodule) cls = _generic_exceptions_cache[fullname] # support old-style exception classes if isinstance(cls, ClassType): exc = InstanceType(cls) else: exc = cls.__new__(cls) exc.args = args for name, attrval in attrs: setattr(exc, name, attrval) if hasattr(exc, "_remote_tb"): exc._remote_tb += (tbtext, ) else: exc._remote_tb = (tbtext, ) return exc
def AddGroup(self, name, description=None, iconFile=None, identifier=None): """ Create and add a new sub-group. """ plugin = self.plugin if identifier is not None: description = name if description is None else description defaultText = ClassType(identifier, (), { "name": name, "description": description }) translatedText = getattr(plugin.text, identifier, None) if translatedText is None: translatedText = ClassType(identifier, (), {}) setattr(plugin.text, identifier, translatedText) SetDefault(translatedText, defaultText) name = translatedText.name description = translatedText.description group = ActionGroup(plugin, name, description, iconFile) self.items.append(group) return group
def __init__(self): self.host = '192.168.32.18' self.database = 'RA2' self.dbuser = '******' self.dbpass = '******' self.isSessionRunning = False self.waitStr = None self.waitFlag = threading.Event() self.session = None self.debug = False group = self.AddGroup('No Return Commands') className = 'NoReturnExecute' clsAttributes = dict(name='No Return Execute', parameterDescription='SQL Statement') cls = ClassType(className, (ParAction, ), clsAttributes) group.AddAction(cls)
def __init__(self): for deviceid, devicetype in sorted(CONFIG.items()): devicelocation = LOCATION[deviceid] group = self.AddGroup('TestRoom - ' + deviceid + ' ' + devicelocation) for className, descr, act, pre in DEVICE_ACTIONS: command = pre + 'OUTPUT,' + deviceid + ',' + act clsAttributes = dict(name=descr, action=act, prefix=pre, deviceid=deviceid, devicetype=devicetype, devicelocation=devicelocation, command=command) cls = ClassType(className + deviceid, (MyAction, ), clsAttributes) # +deviceid added group.AddAction(cls)
def __new__(cls, cls_name, bases, cls_dict): if cls_dict.get("__module__") != __name__: # class is not defined in this module # replace _ObjectBase with object in list of base classes bases = tuple(object if base is _ObjectBase else base for base in bases) if cls_name != "build": if not any(issubclass(base, BuildPlugin) for base in bases): # class is not a build plugin if any(isinstance(base, type) for base in bases): # new-style class return type(cls_name, bases, cls_dict) else: # old-style class from types import ClassType return ClassType(cls_name, bases, cls_dict) # inject base class, if none is specified if bases in ((), (object,)): bases = (BuildPlugin,) return super(MetaBuildPlugin, cls).__new__(cls, cls_name, bases, cls_dict)
def load(val, import_custom_exceptions, instantiate_custom_exceptions, instantiate_oldstyle_exceptions): """ Loads a dumped exception (the tuple returned by :func:`dump`) info a throwable exception object. If the exception cannot be instantiated for any reason (i.e., the security parameters do not allow it, or the exception class simply doesn't exist on the local machine), a :class:`GenericException` instance will be returned instead, containing all of the original exception's details. :param val: the dumped exception :param import_custom_exceptions: whether to allow this function to import custom modules (imposes a security risk) :param instantiate_custom_exceptions: whether to allow this function to instantiate "custom exceptions" (i.e., not one of the built-in exceptions, such as ``ValueError``, ``OSError``, etc.) :param instantiate_oldstyle_exceptions: whether to allow this function to instantiate exception classes that do not derive from ``BaseException``. This is required to support old-style exceptions. Not applicable for Python 3 and above. :returns: A throwable exception object """ if val == consts.EXC_STOP_ITERATION: return StopIteration # optimization if type(val) is str: return val # deprecated string exceptions (modname, clsname), args, attrs, tbtext = val if import_custom_exceptions and modname not in sys.modules: try: __import__(modname, None, None, "*") except Exception: pass if instantiate_custom_exceptions: if modname in sys.modules: cls = getattr(sys.modules[modname], clsname, None) else: cls = None elif modname == exceptions_module.__name__: cls = getattr(exceptions_module, clsname, None) else: cls = None if is_py3k: if not isinstance(cls, type) or not issubclass(cls, BaseException): cls = None else: if not isinstance(cls, (type, ClassType)): cls = None elif issubclass(cls, ClassType) and not instantiate_oldstyle_exceptions: cls = None elif not issubclass(cls, BaseException): cls = None if cls is None: fullname = "%s.%s" % (modname, clsname) # py2: `type()` expects `str` not `unicode`! fullname = str(fullname) if fullname not in _generic_exceptions_cache: fakemodule = {"__module__": "%s/%s" % (__name__, modname)} if isinstance(GenericException, ClassType): _generic_exceptions_cache[fullname] = ClassType( fullname, (GenericException, ), fakemodule) else: _generic_exceptions_cache[fullname] = type( fullname, (GenericException, ), fakemodule) cls = _generic_exceptions_cache[fullname] cls = _get_exception_class(cls) # support old-style exception classes if ClassType is not type and isinstance(cls, ClassType): exc = InstanceType(cls) else: exc = cls.__new__(cls) exc.args = args for name, attrval in attrs: try: setattr(exc, name, attrval) except AttributeError: # handle immutable attrs (@property) pass exc._remote_tb = tbtext return exc
def __new__(cls, activity, model, field): attrs = dict(FieldMultiplexWrapper.__dict__) del attrs['__new__'] mod_cls = ClassType('FieldMultiplexWrapperMod', (field.__class__, ), attrs) return mod_cls(activity, model, field)
def MakeCls(name): baseCls = getattr(eg, name) cls = ClassType(name, (ItemMixin, baseCls), itemNamespace) self.XMLTag2ClassDict[cls.xmlTag.lower()] = cls return cls