Python new.classobj() Examples

The following are 13 code examples of new.classobj(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module new , or try the search function .
Example #1
Source File: test_imp.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_cp13736(self):
        import os
        _f_imp_cp13736 = os.path.join(self.test_dir, "impcp13736.py")
        shortName = _f_imp_cp13736.rsplit(os.sep, 1)[1].split(".")[0]

        self.write_to_file(_f_imp_cp13736, """
class Test(object):
    def a(self):
        return 34
""")

        import sys
        if sys.platform=="win32" and "." not in sys.path:
            sys.path.append(".")
        import new
        import imp

        moduleInfo = imp.find_module(shortName)
        module = imp.load_module(shortName, moduleInfo[0], moduleInfo[1], moduleInfo[2])
        t = new.classobj('Test1', (getattr(module, 'Test'),), {})
        i = t()
        self.assertEqual(i.a(), 34)

        moduleInfo[0].close()
        self.delete_files(_f_imp_cp13736) 
Example #2
Source File: test_adbapi.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeSQLTests(base, suffix, globals):
    """
    Make a test case for every db connector which can connect.

    @param base: Base class for test case. Additional base classes
                 will be a DBConnector subclass and unittest.TestCase
    @param suffix: A suffix used to create test case names. Prefixes
                   are defined in the DBConnector subclasses.
    """
    connectors = [GadflyConnector, SQLiteConnector, PyPgSQLConnector,
                  PsycopgConnector, MySQLConnector, FirebirdConnector]
    for connclass in connectors:
        name = connclass.TEST_PREFIX + suffix
        klass = new.classobj(name, (connclass, base, unittest.TestCase), base.__dict__)
        globals[name] = klass

# GadflyADBAPITestCase SQLiteADBAPITestCase PyPgSQLADBAPITestCase
# PsycopgADBAPITestCase MySQLADBAPITestCase FirebirdADBAPITestCase 
Example #3
Source File: test_adbapi.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def makeSQLTests(base, suffix, globals):
    """Make a test case for every db connector which can connect.

    @param base: Base class for test case. Additional base classes
                 will be a DBConnector subclass and unittest.TestCase
    @param suffix: A suffix used to create test case names. Prefixes
                   are defined in the DBConnector subclasses.
    """
    connectors = [GadflyConnector, SQLiteConnector, PyPgSQLConnector,
                  PsycopgConnector, MySQLConnector, FirebirdConnector]
    for connclass in connectors:
        name = connclass.TEST_PREFIX + suffix
        import new
        klass = new.classobj(name, (connclass, base, unittest.TestCase), {})
        globals[name] = klass

# GadflyADBAPITestCase SQLiteADBAPITestCase PyPgSQLADBAPITestCase
# PsycopgADBAPITestCase MySQLADBAPITestCase FirebirdADBAPITestCase 
Example #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        self.serial = None
        self.response = None
        self.method = 0
        self.hwndMarantzControl = None

        for groupname, list in commandsList:
            group = self.AddGroup(groupname)
            for classname, title, desc, app, serial in list:
                if desc is None:
                    desc = title
                clsAttributes = dict(name=title, description=desc, appcmd=app, serialcmd=serial)
                cls = new.classobj(classname, (MarantzSerialAction,), clsAttributes)
                group.AddAction(cls)

        group = self.AddGroup('Volume')
        group.AddAction(MarantzSerialSetVolumeAbsolute)
        group.AddAction(MarantzSerialSetVolumeRelative) 
Example #5
Source File: attrmap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def hook__setattr__(obj):
    if not hasattr(obj,'__attrproxy__'):
        C = obj.__class__
        import new
        obj.__class__=new.classobj(C.__name__,(C,)+C.__bases__,
            {'__attrproxy__':[],
            '__setattr__':lambda self,k,v,osa=getattr(obj,'__setattr__',None),hook=hook: hook(self,k,v,osa)}) 
Example #6
Source File: recipe-572213.py    From code with MIT License 5 votes vote down vote up
def save_classobj(self, obj):
    """ Save an interactively defined classic class object by value """
    if obj.__module__ == '__main__':
        args = (obj.__name__, obj.__bases__, obj.__dict__)
        self.save_reduce(new.classobj, args, obj=obj)
    else:
        pickle.Pickler.save_global(self, obj, name) 
Example #7
Source File: recipe-577130.py    From code with MIT License 5 votes vote down vote up
def get_options_dict(configFile):
  f = open(configFile)
  d = yaml.load(f)
  f.close()
  objs = {}
  for k,v in d.items():
    oClz = classobj('%sOptions'%k.capitalize(),(ConfigOptions,), {})
    obj = oClz(**d[k])
    objs[oClz.__name__]=obj
  return ConfigOptions(**objs)
# 
Example #8
Source File: attrmap.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def hook__setattr__(obj):
    if not hasattr(obj,'__attrproxy__'):
        C = obj.__class__
        import new
        obj.__class__=new.classobj(C.__name__,(C,)+C.__bases__,
            {'__attrproxy__':[],
            '__setattr__':lambda self,k,v,osa=getattr(obj,'__setattr__',None),hook=hook: hook(self,k,v,osa)}) 
Example #9
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        self.host = "localhost"
        self.port = 2663
        self.isSessionRunning = False
        self.timeline = ""
        self.waitStr = None
        self.waitFlag = threading.Event()
        self.PlayState = -1
        self.lastMessage = {}
        self.lastSubtitleNum = 0
        self.lastSubtitlesEnabled = False
        self.lastAudioTrackNum = 0

        group = self.AddGroup('Requests')
        for className, scancode, descr in ttRequests:
            clsAttributes = dict(name=descr, value=scancode)
            cls = new.classobj(className, (stdAction,), clsAttributes)
            group.AddAction(cls)

        group = self.AddGroup('Commands')
        for className, scancode, descr, ParamDescr in ttCommands:
            clsAttributes = dict(name=descr, value=scancode)
            if ParamDescr == "":
                 if className[0:3] == "IP_":
                    cls = new.classobj(className, (stdAction,), clsAttributes)
                 else:
                    cls = new.classobj(className, (wmAction,), clsAttributes)
            else:
                cls = new.classobj(className, (stdActionWithStringParameter,), clsAttributes)
                cls.parameterDescription = ParamDescr
            group.AddAction(cls) 
Example #10
Source File: __init__.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def WithEvents(disp, user_event_class):
  """Similar to DispatchWithEvents - except that the returned
  object is *not* also usable as the original Dispatch object - that is
  the returned object is not dispatchable.

  The difference is best summarised by example.

  >>> class IEEvents:
  ...    def OnVisible(self, visible):
  ...       print "Visible changed:", visible
  ...
  >>> ie = Dispatch("InternetExplorer.Application")
  >>> ie_events = WithEvents(ie, IEEvents)
  >>> ie.Visible = 1
  Visible changed: 1

  Compare with the code sample for DispatchWithEvents, where you get a
  single object that is both the interface and the event handler.  Note that
  the event handler instance will *not* be able to use 'self.' to refer to
  IE's methods and properties.

  This is mainly useful where using DispatchWithEvents causes
  circular reference problems that the simple proxy doesn't deal with
  """
  disp = Dispatch(disp)
  if not disp.__class__.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
    try:
      ti = disp._oleobj_.GetTypeInfo()
      disp_clsid = ti.GetTypeAttr()[0]
      tlb, index = ti.GetContainingTypeLib()
      tla = tlb.GetLibAttr()
      gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
      # Get the class from the module.
      disp_class = gencache.GetClassForProgID(str(disp_clsid))
    except pythoncom.com_error:
      raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
  else:
    disp_class = disp.__class__
  # Get the clsid
  clsid = disp_class.CLSID
  # Create a new class that derives from 2 classes - the event sink
  # class and the user class.
  import new
  events_class = getevents(clsid)
  if events_class is None:
    raise ValueError("This COM object does not support events.")
  result_class = new.classobj("COMEventClass", (events_class, user_event_class), {})
  instance = result_class(disp) # This only calls the first base class __init__.
  if hasattr(user_event_class, "__init__"):
    user_event_class.__init__(instance)
  return instance 
Example #11
Source File: explorer.py    From python-for-android with Apache License 2.0 4 votes vote down vote up
def watchObject(self, object, identifier, callback):
        """Watch the given object.

        Whenever I think the object might have changed, I'll send an
        ObjectLink of it to the callback.

        The identifier argument is used to generate identifiers for
        objects which are members of this one.
        """
        if type(object) is not types.InstanceType:
            raise TypeError, "Sorry, can only place a watch on Instances."

        # uninstallers = []

        dct = {}
        reflect.addMethodNamesToDict(object.__class__, dct, '')
        for k in object.__dict__.keys():
            dct[k] = 1

        members = dct.keys()

        clazzNS = {}
        clazz = new.classobj('Watching%s%X' %
                             (object.__class__.__name__, id(object)),
                             (_MonkeysSetattrMixin, object.__class__,),
                             clazzNS)

        clazzNS['_watchEmitChanged'] = new.instancemethod(
            lambda slf, i=identifier, b=self, cb=callback:
            cb(b.browseObject(slf, i)),
            None, clazz)

        # orig_class = object.__class__
        object.__class__ = clazz

        for name in members:
            m = getattr(object, name)
            # Only hook bound methods.
            if ((type(m) is types.MethodType)
                and (m.im_self is not None)):
                # What's the use of putting watch monkeys on methods
                # in addition to __setattr__?  Well, um, uh, if the
                # methods modify their attributes (i.e. add a key to
                # a dictionary) instead of [re]setting them, then
                # we wouldn't know about it unless we did this.
                # (Is that convincing?)

                monkey = _WatchMonkey(object)
                monkey.install(name)
                # uninstallers.append(monkey.uninstall)

        # XXX: This probably prevents these objects from ever having a
        # zero refcount.  Leak, Leak!
        ## self.watchUninstallers[object] = uninstallers 
Example #12
Source File: explorer.py    From BitTorrent with GNU General Public License v3.0 4 votes vote down vote up
def watchObject(self, object, identifier, callback):
        """Watch the given object.

        Whenever I think the object might have changed, I'll send an
        ObjectLink of it to the callback.

        The identifier argument is used to generate identifiers for
        objects which are members of this one.
        """
        if type(object) is not types.InstanceType:
            raise TypeError, "Sorry, can only place a watch on Instances."

        # uninstallers = []

        dct = {}
        reflect.addMethodNamesToDict(object.__class__, dct, '')
        for k in object.__dict__.keys():
            dct[k] = 1

        members = dct.keys()

        clazzNS = {}
        clazz = new.classobj('Watching%s%X' %
                             (object.__class__.__name__, id(object)),
                             (_MonkeysSetattrMixin, object.__class__,),
                             clazzNS)

        clazzNS['_watchEmitChanged'] = new.instancemethod(
            lambda slf, i=identifier, b=self, cb=callback:
            cb(b.browseObject(slf, i)),
            None, clazz)

        # orig_class = object.__class__
        object.__class__ = clazz

        for name in members:
            m = getattr(object, name)
            # Only hook bound methods.
            if ((type(m) is types.MethodType)
                and (m.im_self is not None)):
                # What's the use of putting watch monkeys on methods
                # in addition to __setattr__?  Well, um, uh, if the
                # methods modify their attributes (i.e. add a key to
                # a dictionary) instead of [re]setting them, then
                # we wouldn't know about it unless we did this.
                # (Is that convincing?)

                monkey = _WatchMonkey(object)
                monkey.install(name)
                # uninstallers.append(monkey.uninstall)

        # XXX: This probably prevents these objects from ever having a
        # zero refcount.  Leak, Leak!
        ## self.watchUninstallers[object] = uninstallers 
Example #13
Source File: loadrecipe.py    From conary with Apache License 2.0 4 votes vote down vote up
def _copyReusedRecipes(self):
        # XXX HACK - get rid of this when we move the
        # recipe classes to the repository.
        # makes copies of some of the superclass recipes that are
        # created in this module.  (specifically, the ones with buildreqs)
        recipeClassDict = {}
        for recipeClass in self.module.__dict__.values():
            if (type(recipeClass) != type or
                    not issubclass(recipeClass, recipe.Recipe)):
                continue
            numParents = len(inspect.getmro(recipeClass))
            recipeClassDict[recipeClass.__name__] = (numParents, recipeClass)
        # create copies of recipes by the number of parents they have
        # a class always has more parents than its parent does,
        # if you copy the superClasses first, the copies will.
        recipeClasses = [ x[1]  for x in sorted(recipeClassDict.values(),
                                                key=lambda x: x[0]) ]
        for recipeClass in recipeClasses:
            className = recipeClass.__name__
            # when we create a new class object, it needs its superclasses.
            # get the original superclass list and substitute in any
            # copies
            mro = list(inspect.getmro(recipeClass)[1:])
            newMro = []
            for superClass in mro:
                superName = superClass.__name__
                newMro.append(self.module.__dict__.get(superName, superClass))

            newDict = {}
            for name, attr in recipeClass.__dict__.iteritems():
                if type(attr) in [ types.ModuleType, types.MethodType,
                                   types.UnboundMethodType,
                                   types.FunctionType,
                                   staticmethod,
                                   # don't copy in flags, as they
                                   # need to have their data copied out
                                   use.LocalFlagCollection]:
                    newDict[name] = attr
                else:
                    newDict[name] = copy.deepcopy(attr)

            self.module.__dict__[className] = \
                            new.classobj(className, tuple(newMro), newDict)