Constructs an instance based on the function annotations on an object's
        __init__ method
        :argument clazz the class to instantiate
        :return the instantiated class
15768
def _resolve_class(self, clazz: Any) -> object:
        
        arguments = {}
        if hasattr(clazz.__init__, '__annotations__'):
            annotations = clazz.__init__.__annotations__
            for name, type_hint in annotations.items():
                if name != 'return':
                    arguments[name] = self.resolve(type_hint)
        return clazz(**arguments)
1103937
def create_class(self, method):
        
        self.__dict__.update(dict(method=method))
        temp_class = self.temp('separated.class')
        return temp_class.format(**self.__dict__)
638079
def init(scope):
    
    class SinonGlobals(object): #pylint: disable=too-few-public-methods
        """
        A fully empty class
        External can push the whole `scope` into this class through global function init()
        """
        pass

    global CPSCOPE #pylint: disable=global-statement
    CPSCOPE = SinonGlobals()
    funcs = [obj for obj in scope.values() if isinstance(obj, FunctionType)]
    for func in funcs:
        setattr(CPSCOPE, func.__name__, func)
    return CPSCOPE
1089841
def instantiate(self):
        
        # e.g. model_name_35 = Model()
        code_lines = []

        if not self.instantiated:
            code_lines.append("%s = %s()" % (self.variable_name, self.model.__name__))
            self.instantiated = True

            # Store our variable name for future foreign key references
            pk_name = self.instance._meta.pk.name
            key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name))
            self.context[key] = self.variable_name

        return code_lines
568278
def decorate_all_methods(decorator):
  
  def decorate_class(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
      if name != "__init__":
        setattr(cls, name, decorator(m))
    return cls
  return decorate_class
1187586
def _create_class_proxy(cls, theclass):
        """"""

        def make_method(name):
            def method(self, *args, **kw):
                return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
            return method

        namespace = {}
        for name in cls._special_names:
            if hasattr(theclass, name):
                namespace[name] = make_method(name)
        return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace)
1253660
def instance(cls) -> 'MiddlewareManager':
        

        if cls._instance is None:
            cls._instance = cls()
            cls._instance.init()
        return cls._instance
421261
def create(cls):
        
        if cls not in cls._instances:
            cls._instances[cls] = cls()

        return cls._instances[cls]
339165
def make(cls, **kwargs):
    
    cls_attrs = {f.name: f for f in attr.fields(cls)}

    unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}
    if len(unknown) > 0:
        _LOGGER.warning(
            "Got unknowns for %s: %s - please create an issue!", cls.__name__, unknown
        )

    missing = [k for k in cls_attrs if k not in kwargs]

    data = {k: v for k, v in kwargs.items() if k in cls_attrs}

    # initialize missing values to avoid passing default=None
    # for the attrs attribute definitions
    for m in missing:
        default = cls_attrs[m].default
        if isinstance(default, attr.Factory):
            if not default.takes_self:
                data[m] = default.factory()
            else:
                raise NotImplementedError
        else:
            _LOGGER.debug("Missing key %s with no default for %s", m, cls.__name__)
            data[m] = None

    # initialize and store raw data for debug purposes
    inst = cls(**data)
    setattr(inst, "raw", kwargs)

    return inst
1015743
def _constructor(cls, mapping, configuration):
        
        sequence_type, default_factory, pass_key = configuration
        return cls(default_factory, mapping, sequence_type=sequence_type,
                   pass_key=pass_key)
1315669
def get_class_method(cls_or_inst, method_name):
    
    cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__
    meth = getattr(cls, method_name, None)
    if isinstance(meth, property):
        meth = meth.fget
    elif isinstance(meth, cached_property):
        meth = meth.func
    return meth
357702
def creation_ordered(class_to_decorate):
    

    next_index = functools.partial(next, itertools.count())

    __init__orig = class_to_decorate.__init__

    @functools.wraps(__init__orig, assigned=['__doc__'])
    def __init__(self, *args, **kwargs):
        object.__setattr__(self, '_index', next_index())
        __init__orig(self, *args, **kwargs)

    setattr(class_to_decorate, '__init__', __init__)

    # noinspection PyProtectedMember
    def __lt__(self, other):
        return self._index < other._index  # pragma: no mutate

    setattr(class_to_decorate, '__lt__', __lt__)

    class_to_decorate = functools.total_ordering(class_to_decorate)

    return class_to_decorate
1040771
function constructorTemplate(name) {
  // Creates a function like
  // function CLASS() {
  //   var firstArg = arguments[0];
  //   if (firstArg && firstArg[Symbol.for("lively-instance-restorer")]) {
  //     // for deserializing instances just do nothing
  //   } else {
  //     // automatically call the initialize method
  //     this[Symbol.for("lively-instance-initialize")].apply(this, arguments);
  //   }
  // }

  return funcExpr({id: name ? id(name) : null}, ["__first_arg__"],
    ifStmt(
      binaryExpr(
        id("__first_arg__"),
        "&&",
        member("__first_arg__", funcCall(member("Symbol", "for"), literal("lively-instance-restorer")), true)),
      block(),
      block(
        exprStmt(
          funcCall(
            member(
              member("this", funcCall(member("Symbol", "for"), literal("lively-instance-initialize")), true),
              "apply"), id("this"), id("arguments"))))));
}
1128633
def BuildService(self, cls):
    

    # CallMethod needs to operate with an instance of the Service class. This
    # internal wrapper function exists only to be able to pass the service
    # instance to the method that does the real CallMethod work.
    def _WrapCallMethod(srvc, method_descriptor,
                        rpc_controller, request, callback):
      return self._CallMethod(srvc, method_descriptor,
                       rpc_controller, request, callback)
    self.cls = cls
    cls.CallMethod = _WrapCallMethod
    cls.GetDescriptor = staticmethod(lambda: self.descriptor)
    cls.GetDescriptor.__doc__ = "Returns the service descriptor."
    cls.GetRequestClass = self._GetRequestClass
    cls.GetResponseClass = self._GetResponseClass
    for method in self.descriptor.methods:
      setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
600134
def create(cls):
        

        class NewPopupCreateView(PopupCreateView, cls.parent_class):
            model = cls.model
            form_class = cls.form_class
            popup_name = cls.get_class_verbose_name()
            template_name = cls.get_template_name_create()
            permission_required = cls.get_permission_required('create')

            def get_context_data(self, **kwargs):
                kwargs.update(cls.context_for_all)
                kwargs.update(cls.context_for_create)
                return super(NewPopupCreateView, self).get_context_data(**kwargs)

        return NewPopupCreateView
1073928
def new_instance(settings):
    
    settings = set_default({}, settings)
    if not settings["class"]:
        Log.error("Expecting 'class' attribute with fully qualified class name")

    # IMPORT MODULE FOR HANDLER
    path = settings["class"].split(".")
    class_name = path[-1]
    path = ".".join(path[:-1])
    constructor = None
    try:
        temp = __import__(path, globals(), locals(), [class_name], 0)
        constructor = object.__getattribute__(temp, class_name)
    except Exception as e:
        Log.error("Can not find class {{class}}", {"class": path}, cause=e)

    settings['class'] = None
    try:
        return constructor(kwargs=settings)  # MAYBE IT TAKES A KWARGS OBJECT
    except Exception as e:
        pass

    try:
        return constructor(**settings)
    except Exception as e:
        Log.error("Can not create instance of {{name}}", name=".".join(path), cause=e)
171492
def get_class_that_defined_method(fun):
    
    if inspect.ismethod(fun):
        for cls in inspect.getmro(fun.__self__.__class__):
            if cls.__dict__.get(fun.__name__) is fun:
                return cls
        fun = fun.__func__  # fallback to __qualname__ parsing
    if inspect.isfunction(fun):
        cls = getattr(inspect.getmodule(fun),
                      fun.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0], None)
        if isinstance(cls, type):
            return cls
    return getattr(fun, '__objclass__', None)