Python types.FunctionType() Examples

The following are 30 code examples for showing how to use types.FunctionType(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module types , or try the search function .

Example 1
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    License: Apache License 2.0 7 votes vote down vote up
def _make_skel_func(code, cell_count, base_globals=None):
    """ Creates a skeleton function object that contains just the provided
        code and the correct number of cells in func_closure.  All other
        func attributes (e.g. func_globals) are empty.
    """
    # This is backward-compatibility code: for cloudpickle versions between
    # 0.5.4 and 0.7, base_globals could be a string or None. base_globals
    # should now always be a dictionary.
    if base_globals is None or isinstance(base_globals, str):
        base_globals = {}

    base_globals['__builtins__'] = __builtins__

    closure = (
        tuple(_make_empty_cell() for _ in range(cell_count))
        if cell_count >= 0 else
        None
    )
    return types.FunctionType(code, base_globals, None, None, closure) 
Example 2
Project: python-pool-performance   Author: JohnStarich   File: pools.py    License: MIT License 6 votes vote down vote up
def run_test(work_type: FunctionType, job_sets: Sequence, trials: int,
             pool_class: type, worker_count: int) -> Mapping:
    pool = pool_class(worker_count)
    if work_type == 'compute':
        test_func = pool.run_compute_test
    elif work_type == 'network':
        test_func = pool.run_network_test
    else:
        raise Exception("Invalid work type: {}".format(work_type))
    results = map(
        lambda jobs: test_func(jobs, trials, show_progress=True),
        tqdm(job_sets, desc=pool_class.__name__),
    )
    summarized_results = list(map(summarize_test, results))
    pool.destroy_pool()
    return summarized_results 
Example 3
Project: SublimeKSP   Author: nojanath   File: yacc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func,types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = 1
                return

            eline = func_code(self.error_func).co_firstlineno
            efile = func_code(self.error_func).co_filename
            module = inspect.getmodule(self.error_func)
            self.modules[module] = 1

            argcount = func_code(self.error_func).co_argcount - ismethod
            if argcount != 1:
                self.log.error("%s:%d: p_error() requires 1 argument",efile,eline)
                self.error = 1

    # Get the tokens map 
Example 4
Project: SublimeKSP   Author: nojanath   File: yacc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_'): continue
            if name == 'p_error': continue
            if isinstance(item,(types.FunctionType,types.MethodType)):
                line = func_code(item).co_firstlineno
                module = inspect.getmodule(item)
                p_functions.append((line,module,name,item.__doc__))

        # Sort all of the actions by line number
        p_functions.sort()
        self.pfuncs = p_functions


    # Validate all of the p_functions 
Example 5
Project: aws-ops-automator   Author: awslabs   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def default(self, o):
        if types.FunctionType == type(o):
            return o.__name__
        # sets become lists
        if isinstance(o, set):
            return list(o)
        # date times become strings
        if isinstance(o, datetime):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, type):
            return str(o)
        if isinstance(o, Exception):
            return str(o)
        if isinstance(o, set):
            return str(o, 'utf-8')
        if isinstance(o, bytes):
            return str(o, 'utf-8')
        
        return json.JSONEncoder.default(self, o) 
Example 6
Project: myhdl   Author: myhdl   File: _always_seq.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def always_seq(edge, reset):
    callinfo = _getCallInfo()
    sigargs = []
    if not isinstance(edge, _WaiterList):
        raise AlwaysSeqError(_error.EdgeType)
    edge.sig._read = True
    edge.sig._used = True
    sigargs.append(edge.sig)
    if reset is not None:
        if not isinstance(reset, ResetSignal):
            raise AlwaysSeqError(_error.ResetType)
        reset._read = True
        reset._used = True
        sigargs.append(reset)
    sigdict = _get_sigdict(sigargs, callinfo.symdict)

    def _always_seq_decorator(func):
        if not isinstance(func, FunctionType):
            raise AlwaysSeqError(_error.ArgType)
        if _isGenFunc(func):
            raise AlwaysSeqError(_error.ArgType)
        if func.__code__.co_argcount > 0:
            raise AlwaysSeqError(_error.NrOfArgs)
        return _AlwaysSeq(func, edge, reset, callinfo=callinfo, sigdict=sigdict)
    return _always_seq_decorator 
Example 7
Project: myhdl   Author: myhdl   File: _always.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def always(*args):
    callinfo = _getCallInfo()
    sigargs = []
    for arg in args:
        if isinstance(arg, _Signal):
            arg._read = True
            arg._used = True
            sigargs.append(arg)
        elif isinstance(arg, _WaiterList):
            arg.sig._read = True
            arg.sig._used = True
            sigargs.append(arg.sig)
        elif not isinstance(arg, delay):
            raise AlwaysError(_error.DecArgType)
    sigdict = _get_sigdict(sigargs, callinfo.symdict)

    def _always_decorator(func):
        if not isinstance(func, FunctionType):
            raise AlwaysError(_error.ArgType)
        if _isGenFunc(func):
            raise AlwaysError(_error.ArgType)
        if func.__code__.co_argcount > 0:
            raise AlwaysError(_error.NrOfArgs)
        return _Always(func, args, callinfo=callinfo, sigdict=sigdict)
    return _always_decorator 
Example 8
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    License: Apache License 2.0 6 votes vote down vote up
def save_pypy_builtin_func(self, obj):
        """Save pypy equivalent of builtin functions.

        PyPy does not have the concept of builtin-functions. Instead,
        builtin-functions are simple function instances, but with a
        builtin-code attribute.
        Most of the time, builtin functions should be pickled by attribute. But
        PyPy has flaky support for __qualname__, so some builtin functions such
        as float.__new__ will be classified as dynamic. For this reason only,
        we created this special routine. Because builtin-functions are not
        expected to have closure or globals, there is no additional hack
        (compared the one already implemented in pickle) to protect ourselves
        from reference cycles. A simple (reconstructor, newargs, obj.__dict__)
        tuple is save_reduced.

        Note also that PyPy improved their support for __qualname__ in v3.6, so
        this routing should be removed when cloudpickle supports only PyPy 3.6
        and later.
        """
        rv = (types.FunctionType, (obj.__code__, {}, obj.__name__,
                                   obj.__defaults__, obj.__closure__),
              obj.__dict__)
        self.save_reduce(*rv, obj=obj) 
Example 9
Project: LGWebOSRemote   Author: klattimer   File: remote.py    License: MIT License 6 votes vote down vote up
def getCommands(cls):
        excludes = [
            'opened',
            'closed',
            'received_message',
            'exec_command',
            'getCommands'
        ]
        out = []
        m = [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
        for method in m:
            if method.startswith("_" + cls.__name__):
                continue
            if method in excludes:
                continue
            if method.startswith("__"):
                continue
            out.append(method)
        out.sort()
        return out 
Example 10
Project: tangent   Author: google   File: grads.py    License: Apache License 2.0 6 votes vote down vote up
def get_module_functions(modules):
  """Finds functions that do not have implemented derivatives.

  Args:
    modules: A list of Python modules. Functions contained in these modules
        will be checked for membership in 'implemented', and if not found,
        will be added to an 'unimplemented' set
    implemented: A Python object containing implemented derivatives. A function
        should be checkable for membership using the `fn in implemented` syntax.

  Returns:
    module_fns: A set of functions, builtins or ufuncs in `modules`.
  """
  module_fns = set()
  for module in modules:
    for key in dir(module):
      attr = getattr(module, key)
      if isinstance(
          attr, (types.BuiltinFunctionType, types.FunctionType, numpy.ufunc)):
        module_fns.add(attr)
  return module_fns 
Example 11
Project: pyGSTi   Author: pyGSTio   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def with_temp_path(filename=None):
    """Decorator version of ``IOBase.temp_path``"""
    arg_fn = None
    if isinstance(filename, types.FunctionType):
        # Decorator was used without calling, so `filename' is actually the decorated function
        arg_fn = filename
        filename = None

    def decorator(fn):
        @functools.wraps(fn)
        def inner(self, *args, **kwargs):
            with self.temp_path(filename) as tmp_path:
                return fn(self, tmp_path, *args, **kwargs)
        return inner
    if arg_fn is not None:
        return decorator(arg_fn)
    else:
        return decorator 
Example 12
Project: misp42splunk   Author: remg427   File: yacc.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map 
Example 13
Project: misp42splunk   Author: remg427   File: yacc.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_') or name == 'p_error':
                continue
            if isinstance(item, (types.FunctionType, types.MethodType)):
                line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno)
                module = inspect.getmodule(item)
                p_functions.append((line, module, name, item.__doc__))

        # Sort all of the actions by line number; make sure to stringify
        # modules to make them sortable, since `line` may not uniquely sort all
        # p functions
        p_functions.sort(key=lambda p_function: (
            p_function[0],
            str(p_function[1]),
            p_function[2],
            p_function[3]))
        self.pfuncs = p_functions

    # Validate all of the p_functions 
Example 14
Project: recipes-py   Author: luci   File: recipe_api.py    License: Apache License 2.0 6 votes vote down vote up
def __new__(mcs, name, bases, attrs):
    """Automatically wraps all methods of subclasses of RecipeApi with
    @infer_composite_step. This allows defer_results to work as intended without
    manually decorating every method.
    """
    wrap = lambda f: infer_composite_step(f) if f else f
    for attr in attrs:
      if attr in RecipeApiMeta.WHITELIST:
        continue
      val = attrs[attr]
      if isinstance(val, types.FunctionType):
        attrs[attr] = wrap(val)
      elif isinstance(val, property):
        attrs[attr] = property(
          wrap(val.fget),
          wrap(val.fset),
          wrap(val.fdel),
          val.__doc__)
    return super(RecipeApiMeta, mcs).__new__(mcs, name, bases, attrs) 
Example 15
Project: Jtyoui   Author: jtyoui   File: FucStr.py    License: MIT License 6 votes vote down vote up
def string_function(module: [str, ModuleType], func: str, *args, **kwargs):
    """根据字符串方法名来进行调用模块方法

    :param module: 模块名
    :param func: 模块中的方法名字
    :param args: 方法里面的参数值
    :param kwargs: 方法里面的参数值
    :return: 返回一个返回值
    """
    if isinstance(module, ModuleType):
        if hasattr(module, func):
            func_or_var = getattr(module, func)
            if isinstance(func_or_var, FunctionType):
                return func_or_var(*args, **kwargs)
            else:
                return func_or_var
        else:
            print(f'{func}不是一个方法')
    elif isinstance(module, str):
        m = __import__(module)
        return string_function(m, func, *args, **kwargs)
    else:
        print(f'{module}不是一个模块')
    return None 
Example 16
Project: ripozo   Author: vertical-knowledge   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_get_apimethods(self):
        """
        Tests that the function _get_apimethods
        appropriately gets apimethods and that they
        are class methods not _apiclassmethod instances.
        """
        class MyResource(ResourceBase):
            @apimethod(methods=['GET'])
            @apimethod(methods=['POST'])
            def fake1(cls):
                pass

            @apimethod(route='/hey', methods=['GET'])
            def fake2(self):
                pass

        names = []
        for name, clsmethod in _get_apimethods(MyResource):
            names.append(name)
            self.assertIsInstance(clsmethod, types.FunctionType)
        self.assertIn('fake1', names)
        self.assertIn('fake2', names)
        self.assertEqual(len(names), 2) 
Example 17
Project: moler   Author: nokia   File: helpers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def call_base_class_method_with_same_name(obj):
    """
    Run base class method.

    :param obj: class object which methods will be decorated.
    :return: class object with decorated methods
    """
    if hasattr(obj, "__dict__"):
        if obj.__dict__.items():
            for attributeName in dir(obj):
                attribute = getattr(obj, attributeName)

                if "_decorate" in dir(attribute):
                    if isinstance(attribute, (FunctionType, MethodType)):
                        setattr(obj, attributeName, _wrapper(method=attribute, obj=obj))

    return obj 
Example 18
Project: moler   Author: nokia   File: moler_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _decorate(obj=None, check_steps_end=False):
        # check that decorated function is not statimethod or classmethod
        if not obj:
            raise ExecutionException("Decorator for 'staticmethod' or 'classmethod' not implemented yet.",
                                     )

        if hasattr(obj, "__dict__"):
            if obj.__dict__.items():
                for attributeName in dir(obj):
                    if attributeName == "_already_decorated":
                        break

                    attribute = getattr(obj, attributeName)

                    if not attributeName.startswith("_"):
                        if isinstance(attribute, (FunctionType, MethodType)):
                            setattr(obj, attributeName, MolerTest._wrapper(attribute, check_steps_end=check_steps_end))
            else:
                obj = MolerTest._wrapper(obj, check_steps_end=check_steps_end)
        else:
            raise ExecutionException("No '__dict__' in decorated object.")

        return obj 
Example 19
Project: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def construct_anew(self, line_data_func=None, exclude_member=None,
                       census=None, pop_hist_func=None):
        self.pop_hist = PopHist()  # this will record pops across time
        # Make sure varieties are present in the history
        if self.pop_hist_setup is not None:
            self.pop_hist_setup(self.pop_hist)
        else:
            for mbr in self.members:
                self.pop_hist.record_pop(mbr, self.pop_count(mbr))

        self.plot_title = self.name
        self.user = None
        # these funcs will be stored as attrs...
        # but only if they're really funcs!
        # cause we're gonna try to call them
        if isinstance(census, FunctionType):
            print("Adding custom census func")
            self.attrs[CENSUS_FUNC] = census
        if isinstance(pop_hist_func, FunctionType):
            self.attrs["pop_hist_func"] = pop_hist_func
        if isinstance(line_data_func, FunctionType):
            self.attrs["line_data_func"] = line_data_func
        self.exclude_member = exclude_member
        self.womb = []  # for agents waiting to be born
        self.switches = []  # for agents waiting to switch groups
        self.handle_user_type() 
Example 20
Project: indras_net   Author: gcallah   File: agent.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if hasattr(o, 'to_json'):
            return o.to_json()
        elif isinstance(o, np.int64):
            return int(o)
        elif isinstance(o, types.FunctionType):
            return get_func_name(o)  # can't JSON a function!
        else:
            return json.JSONEncoder.default(self, o) 
Example 21
Project: gql   Author: graphql-python   File: conftest.py    License: MIT License 5 votes vote down vote up
def get_server_handler(request):
    """Get the server handler.

    Either get it from test or use the default server handler
    if the test provides only an array of answers.
    """

    if isinstance(request.param, types.FunctionType):
        server_handler = request.param

    else:
        answers = request.param

        async def default_server_handler(ws, path):

            try:
                await WebSocketServer.send_connection_ack(ws)
                query_id = 1

                for answer in answers:
                    result = await ws.recv()
                    print(f"Server received: {result}")

                    if isinstance(answer, str) and "{query_id}" in answer:
                        answer_format_params = {"query_id": query_id}
                        formatted_answer = answer.format(**answer_format_params)
                    else:
                        formatted_answer = answer

                    await ws.send(formatted_answer)
                    await WebSocketServer.send_complete(ws, query_id)
                    query_id += 1

                await WebSocketServer.wait_connection_terminate(ws)
                await ws.wait_closed()
            except ConnectionClosed:
                pass

        server_handler = default_server_handler

    return server_handler 
Example 22
Project: python-pool-performance   Author: JohnStarich   File: pool.py    License: MIT License 5 votes vote down vote up
def map(self, work_func: FunctionType, inputs: Sequence) -> Sequence:
        raise NotImplementedError("{} does not implement map"
                                  .format(self.__class__.__name__)) 
Example 23
Project: python-pool-performance   Author: JohnStarich   File: pool.py    License: MIT License 5 votes vote down vote up
def _run_test(self, work_func: FunctionType, work_resource: object,
                  jobs: int, trials: int,
                  show_progress: bool=False) -> Mapping:
        results = {
            'jobs': jobs,
            'trials': trials,
            'time': [],
            'blocks': [],
        }
        # Forcibly evaluate the inputs to prevent time/resources taken up later
        inputs = list(zip(
            [work_resource] * jobs,
            range(jobs)
        ))
        trial_iter = range(trials)
        if show_progress is True and trials > 2:
            trial_iter = tqdm(trial_iter, desc='trials')
        gc.collect()
        for _ in trial_iter:
            # Run trial of pool map function and measure it
            gc.collect()
            blocks_start = sys.getallocatedblocks()
            time_start = time.time()
            list(self.map(work_func, inputs))
            time_end = time.time()
            results['time'].append(time_end - time_start)
            # Get allocated blocks before garbage collection to show peak usage
            blocks_end = sys.getallocatedblocks()
            results['blocks'].append(blocks_end - blocks_start)
        return results 
Example 24
Project: py2swagger   Author: Arello-Mobile   File: utils.py    License: MIT License 5 votes vote down vote up
def get_decorators(function):
    # If we have no func_closure, it means we are not wrapping any other functions.
    decorators = []

    try:
        func_closure = six.get_function_closure(function)
    except AttributeError:
        return decorators
    if not func_closure:
        return [function]
    # Otherwise, we want to collect all of the recursive results for every closure we have.
    for closure in func_closure:
        if isinstance(closure.cell_contents, types.FunctionType):
            decorators.extend(get_decorators(closure.cell_contents))
    return [function] + decorators 
Example 25
Project: SublimeKSP   Author: nojanath   File: lex.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _form_master_re(relist,reflags,ldict,toknames):
    if not relist: return []
    regex = "|".join(relist)
    try:
        lexre = re.compile(regex,re.VERBOSE | reflags)

        # Build the index to function map for the matching engine
        lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1)
        lexindexnames = lexindexfunc[:]

        for f,i in lexre.groupindex.items():
            handle = ldict.get(f,None)
            if type(handle) in (types.FunctionType, types.MethodType):
                lexindexfunc[i] = (handle,toknames[f])
                lexindexnames[i] = f
            elif handle is not None:
                lexindexnames[i] = f
                if f.find("ignore_") > 0:
                    lexindexfunc[i] = (None,None)
                else:
                    lexindexfunc[i] = (None, toknames[f])
        
        return [(lexre,lexindexfunc)],[regex],[lexindexnames]
    except Exception:
        m = int(len(relist)/2)
        if m == 0: m = 1
        llist, lre, lnames = _form_master_re(relist[:m],reflags,ldict,toknames)
        rlist, rre, rnames = _form_master_re(relist[m:],reflags,ldict,toknames)
        return llist+rlist, lre+rre, lnames+rnames

# -----------------------------------------------------------------------------
# def _statetoken(s,names)
#
# Given a declaration name s of the form "t_" and a dictionary whose keys are
# state names, this function returns a tuple (states,tokenname) where states
# is a tuple of state names and tokenname is the name of the token.  For example,
# calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
# ----------------------------------------------------------------------------- 
Example 26
Project: Pytorch-Networks   Author: HaiyangLiu1997   File: opt_factory.py    License: MIT License 5 votes vote down vote up
def state_dict(self):
        import types
        state_dict = {key: value for key, value in self.__dict__.items() if key not in ('optimizer', 'lr_lambdas')}
        state_dict['lr_lambdas'] = [None] * len(self.lr_lambdas)

        for idx, fn in enumerate(self.lr_lambdas):
            if not isinstance(fn, types.FunctionType):
                state_dict['lr_lambdas'][idx] = fn.__dict__.copy()

        return state_dict 
Example 27
Project: aws-ops-automator   Author: awslabs   File: test_action.py    License: Apache License 2.0 5 votes vote down vote up
def get_methods(cls):
        return [x for x, y in list(cls.__dict__.items()) if type(y) == FunctionType and x.startswith("test_")] 
Example 28
Project: aws-ops-automator   Author: awslabs   File: test_action.py    License: Apache License 2.0 5 votes vote down vote up
def get_methods(cls):
        return [x for x, y in list(cls.__dict__.items()) if type(y) == FunctionType and x.startswith("test_")] 
Example 29
Project: aws-ops-automator   Author: awslabs   File: test_action.py    License: Apache License 2.0 5 votes vote down vote up
def get_methods(cls):
        return [x for x, y in list(cls.__dict__.items()) if type(y) == FunctionType and x.startswith("test_")] 
Example 30
Project: aws-ops-automator   Author: awslabs   File: test_action.py    License: Apache License 2.0 5 votes vote down vote up
def get_methods(cls):
        return [x for x, y in list(cls.__dict__.items()) if type(y) == FunctionType and x.startswith("test_")]