Python types.FunctionType() Examples

The following are code examples for showing how to use types.FunctionType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: python-pool-performance   Author: JohnStarich   File: pools.py    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 2
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: api.py    MIT License 6 votes vote down vote up
def typeof(self, cdecl):
        """Parse the C type given as a string and return the
        corresponding <ctype> object.
        It can also be used on 'cdata' instance to get its C type.
        """
        if isinstance(cdecl, basestring):
            return self._typeof(cdecl)
        if isinstance(cdecl, self.CData):
            return self._backend.typeof(cdecl)
        if isinstance(cdecl, types.BuiltinFunctionType):
            res = _builtin_function_type(cdecl)
            if res is not None:
                return res
        if (isinstance(cdecl, types.FunctionType)
                and hasattr(cdecl, '_cffi_base_type')):
            with self._lock:
                return self._get_cached_btype(cdecl._cffi_base_type)
        raise TypeError(type(cdecl)) 
Example 3
Project: flasky   Author: RoseOu   File: util.py    MIT License 6 votes vote down vote up
def function_named(fn, name):
    """Return a function with a given __name__.

    Will assign to __name__ and return the original function if possible on
    the Python implementation, otherwise a new function will be constructed.

    This function should be phased out as much as possible
    in favor of @decorator.   Tests that "generate" many named tests
    should be modernized.

    """
    try:
        fn.__name__ = name
    except TypeError:
        fn = types.FunctionType(fn.__code__, fn.__globals__, name,
                                fn.__defaults__, fn.__closure__)
    return fn 
Example 4
Project: bigquerylayers   Author: smandaric   File: _parameterized.py    GNU General Public License v3.0 6 votes vote down vote up
def _ModifyClass(class_object, testcases, naming_type):
  assert not getattr(class_object, '_id_suffix', None), (
      'Cannot add parameters to %s,'
      ' which already has parameterized methods.' % (class_object,))
  class_object._id_suffix = id_suffix = {}
  # We change the size of __dict__ while we iterate over it,
  # which Python 3.x will complain about, so use copy().
  for name, obj in class_object.__dict__.copy().items():
    if (name.startswith(unittest.TestLoader.testMethodPrefix)
        and isinstance(obj, types.FunctionType)):
      delattr(class_object, name)
      methods = {}
      _UpdateClassDictForParamTestCase(
          methods, id_suffix, name,
          _ParameterizedTestIter(obj, testcases, naming_type))
      for name, meth in methods.items():
        setattr(class_object, name, meth) 
Example 5
Project: broccoli   Author: msoedov   File: core.py    MIT License 6 votes vote down vote up
def inject(module, *deps):
    """
    :param module: module instance or module name as string
    :param deps: tuple of dependencies
    :return:
    """
    if isinstance(module, str):
        if module in sys.modules:
            module = sys.modules[module]
        else:
            NameError('{} module not found'.format(module))
    package_modules = sub_modules(module)
    package_namespace = sum([list(vars(m).values()) for m in package_modules],
                            [])
    fn_list = []
    for attr in package_namespace:
        if isinstance(attr, types.FunctionType) and attr.__annotations__:
            fn_list.append(attr)
        elif annotated_class(attr):
            fn_list.append(attr.__init__)
    return bind_batch(fn_list, *deps) 
Example 6
Project: starks   Author: computablelabs   File: test_zero_knowledge.py    MIT License 6 votes vote down vote up
def test_zk_graph_prove_isomorphic_to(self):
    """
    Test proofs of graph isomorphism.

    TODO(rbharath): Create a better test for this function.
    """
    example_graph = [(1, 2), (1, 4), (1, 3), (2, 5), (2, 5), (3, 6), (5, 6)]
    perm_list = random_permutation(6)
    perm_f = make_permutation_function(perm_list)
    permuted_graph = apply_isomorphism(example_graph, perm_f)
    prover = ZKProver(example_graph, permuted_graph, perm_list)
    isomorphism, H = prover.send_isomorphic_copy()
    iso_1 = prover.prove_isomorphic_to(isomorphism, 1)
    assert isinstance(iso_1, types.FunctionType)
    iso_2 = prover.prove_isomorphic_to(isomorphism, 2)
    assert isinstance(iso_2, types.FunctionType) 
Example 7
Project: pcc   Author: jiamo   File: yacc.py    The Unlicense 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 8
Project: pcc   Author: jiamo   File: yacc.py    The Unlicense 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 = 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 9
Project: SublimeKSP   Author: nojanath   File: yacc.py    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 10
Project: SublimeKSP   Author: nojanath   File: yacc.py    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 11
Project: ZCC   Author: hlFu   File: yacc.py    GNU General Public License v2.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 12
Project: ZCC   Author: hlFu   File: yacc.py    GNU General Public License v2.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 = 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 13
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    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 14
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    Apache License 2.0 6 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 15
Project: shenfun   Author: spectralDNS   File: __init__.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def inheritdocstrings(cls):
    """Method used for inheriting docstrings from parent class

    Use as decorator::

         @inheritdocstrings
         class Child(Parent):

    and Child will use the same docstrings as parent even if
    a method is overloaded. The Child class may overload the
    docstring as well and a new docstring defined for a method
    in Child will overload the Parent.
    """
    for name, func in vars(cls).items():
        if isinstance(func, types.FunctionType) and not func.__doc__:
            for parent in cls.__bases__:
                parfunc = getattr(parent, name, None)
                if parfunc and getattr(parfunc, '__doc__', None):
                    func.__doc__ = parfunc.__doc__
                    break
    return cls 
Example 16
Project: wok   Author: bbglab   File: task.py    GNU General Public License v3.0 6 votes vote down vote up
def main(self, *args):
		"""
		A decorator that is used for specifying which is the task main function. Example::

			@task.main
			def main():
				log = task.logger()
				log.info("Hello world")
		"""
		def decorator(f):
			self.set_main(f)
			return f

		if len(args) == 1 and type(args[0]) in [types.FunctionType, types.MethodType]:
			self.set_main(args[0])
			return args[0]
		else:
			return decorator 
Example 17
Project: wok   Author: bbglab   File: task.py    GNU General Public License v3.0 6 votes vote down vote up
def source(self, *args, **kwargs):
		"""
		A decorator that is used to define a function that will
		generate port output data. Example::

			@task.source(out_ports=["x", "sum"])
			def sum_n(x, sum):
				N = task.conf["N"]
				s = 0
				for i in xrange(N):
					x.send(i)
					sum.send(s)
					s += i

		:param out_ports: output ports
		"""
		def decorator(f):
			self.add_source(f, **kwargs)
			return f

		if len(args) == 1 and type(args[0]) in [types.FunctionType, types.MethodType]:
			self.add_source(args[0])
			return args[0]
		else:
			return decorator 
Example 18
Project: wok   Author: bbglab   File: task.py    GNU General Public License v3.0 6 votes vote down vote up
def foreach(self, *args, **kwargs):
		"""
		A decorator that is used to specify which is the function that will
		process each port input data. Example::

			@task.foreach(in_ports = ["in1", "in2"])
			def process(name, value):
				return name + " = " + str(value)

		:param in_ports: input ports
		:param out_ports: output ports
		"""
		def decorator(f):
			self.set_foreach(f, **kwargs)
			return f

		if len(args) == 1 and type(args[0]) in [types.FunctionType, types.MethodType]:
			self.set_foreach(args[0])
			return args[0]
		else:
			return decorator 
Example 19
Project: wok   Author: bbglab   File: task.py    GNU General Public License v3.0 6 votes vote down vote up
def end(self, *args):
		"""A decorator that is used to specify the function that will be
		executed after executing the main function"""
		def decorator(f):
			self.set_end(f)
			return f

		if len(args) == 1 and type(args[0]) in [types.FunctionType, types.MethodType]:
			self.set_begin(args[0])
			return args[0]
		else:
			return decorator

# ======================================================================================================================
# Main task ============================================================================================================
# ====================================================================================================================== 
Example 20
Project: LGWebOSRemote   Author: klattimer   File: remote.py    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 21
Project: tangent   Author: google   File: grads.py    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 22
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, function, name=None):
        """
        Construct a new C{FunctionFeatureDetector} from the given
        function.

        @param function: The function that this feature detector is based
            on.  When this feature detector is applied to a labeled
            text M{lt}, it will return M{C{func}(lt)}.
        @type function: C{LabeledText} -> (any)
        @param name: A name for the function used by this feature
            detector.  This name is used in the string representation
            of the feature detector.
        """
        assert _chktype(1, function, types.FunctionType,
                        types.BuiltinFunctionType, types.ClassType)
        assert _chktype(2, name, types.NoneType, types.StringType)
        self._name = name
        self._func = function 
Example 23
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, function, name=None):
        """
        Construct a new C{FunctionFeatureDetector} from the given
        function.

        @param function: The function that this feature detector is based
            on.  When this feature detector is applied to a labeled
            text M{lt}, it will return M{C{func}(lt)}.
        @type function: C{LabeledText} -> (any)
        @param name: A name for the function used by this feature
            detector.  This name is used in the string representation
            of the feature detector.
        """
        assert _chktype(1, function, types.FunctionType,
                        types.BuiltinFunctionType, types.ClassType)
        assert _chktype(2, name, types.NoneType, types.StringType)
        self._name = name
        self._func = function 
Example 24
Project: pyblish-win   Author: pyblish   File: config.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        self.config = ConvertingDict(config)
        self.config.configurator = self
        # Issue 12718: winpdb replaces __import__ with a Python function, which
        # ends up being treated as a bound method. To avoid problems, we
        # set the importer on the instance, but leave it defined in the class
        # so existing code doesn't break
        if type(__import__) == types.FunctionType:
            self.importer = __import__ 
Example 25
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __methodDict(cls, _dict):
    """helper function for Scrolled Canvas"""
    baseList = list(cls.__bases__)
    baseList.reverse()
    for _super in baseList:
        __methodDict(_super, _dict)
    for key, value in cls.__dict__.items():
        if type(value) == types.FunctionType:
            _dict[key] = value 
Example 26
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getmethparlist(ob):
    "Get strings describing the arguments for the given object"
    argText1 = argText2 = ""
    # bit of a hack for methods - turn it into a function
    # but we drop the "self" param.
    if type(ob)==types.MethodType:
        fob = ob.im_func
        argOffset = 1
    else:
        fob = ob
        argOffset = 0
    # Try and build one for Python defined functions
    if type(fob) in [types.FunctionType, types.LambdaType]:
        try:
            counter = fob.func_code.co_argcount
            items2 = list(fob.func_code.co_varnames[argOffset:counter])
            realArgs = fob.func_code.co_varnames[argOffset:counter]
            defaults = fob.func_defaults or []
            defaults = list(map(lambda name: "=%s" % repr(name), defaults))
            defaults = [""] * (len(realArgs)-len(defaults)) + defaults
            items1 = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
            if fob.func_code.co_flags & 0x4:
                items1.append("*"+fob.func_code.co_varnames[counter])
                items2.append("*"+fob.func_code.co_varnames[counter])
                counter += 1
            if fob.func_code.co_flags & 0x8:
                items1.append("**"+fob.func_code.co_varnames[counter])
                items2.append("**"+fob.func_code.co_varnames[counter])
            argText1 = ", ".join(items1)
            argText1 = "(%s)" % argText1
            argText2 = ", ".join(items2)
            argText2 = "(%s)" % argText2
        except:
            pass
    return argText1, argText2 
Example 27
Project: pyblish-win   Author: pyblish   File: inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def isfunction(object):
    """Return true if the object is a user-defined function.

    Function objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this function was defined
        func_code       code object containing compiled function bytecode
        func_defaults   tuple of any default values for arguments
        func_doc        (same as __doc__)
        func_globals    global namespace in which this function was defined
        func_name       (same as __name__)"""
    return isinstance(object, types.FunctionType) 
Example 28
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pickle_code(co):
    assert isinstance(co, types.CodeType)
    ms = marshal.dumps(co)
    return unpickle_code, (ms,)

# XXX KBK 24Aug02 function pickling capability not used in Idle
#  def unpickle_function(ms):
#      return ms

#  def pickle_function(fn):
#      assert isinstance(fn, type.FunctionType)
#      return repr(fn) 
Example 29
Project: python-pool-performance   Author: JohnStarich   File: pool.py    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 30
Project: python-pool-performance   Author: JohnStarich   File: pool.py    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 31
Project: kuaa   Author: rafaelwerneck   File: myrepr.py    GNU General Public License v3.0 5 votes vote down vote up
def myrepr(obj):
    """
    """
    if isinstance(obj, types.FunctionType):
        return obj.func_name + '()'
    elif isinstance(obj, list):
        reprs = map(myrepr, obj)
        reprs = reduce(lambda x, y: x + ',' + y, reprs)
        return '[' + reprs + ']'
    elif isinstance(obj, tuple):
        if len(obj) == 0:
            return '()'
        reprs = map(myrepr, obj)
        reprs = reduce(lambda x, y: x + ',' + y, reprs)
        reprs += ',' if len(obj) == 1 else ''
        return '(' + reprs + ')'
    elif isinstance(obj, set):
        reprs = myrepr(list(obj))
        return 'set(' + reprs + ')'
    elif isinstance(obj, dict):
        if len(obj) == 0:
            return '{}'
        reprs = zip(map(myrepr, obj.keys()), map(myrepr, obj.values()))
        reprs = map(lambda (k,v): k + ':' + v, reprs)
        reprs = reduce(lambda x, y: x + ',' + y, reprs)
        return '{' + reprs + '}'
    elif isinstance(obj, type):
        return repr(obj).replace(' ', '')
    else:
        return repr(obj) 
Example 32
Project: kuaa   Author: rafaelwerneck   File: hashfile.py    GNU General Public License v3.0 5 votes vote down vote up
def __myrepr(obj):
        """
        """
        if isinstance(obj, types.FunctionType):
            return obj.func_name + '()'
        elif isinstance(obj, list):
            reprs = map(HashFile.__myrepr, obj)
            reprs = reduce(lambda x, y: x + ',' + y, reprs)
            return '[' + reprs + ']'
        elif isinstance(obj, tuple):
            if len(obj) == 0:
                return '()'
            reprs = map(HashFile.__myrepr, obj)
            reprs = reduce(lambda x, y: x + ',' + y, reprs)
            reprs += ',' if len(obj) == 1 else ''
            return '(' + reprs + ')'
        elif isinstance(obj, set):
            reprs = HashFile.__myrepr(list(obj))
            return 'set(' + reprs + ')'
        elif isinstance(obj, dict):
            reprs = zip(map(HashFile.__myrepr, obj.keys()), map(HashFile.__myrepr, obj.values()))
            reprs = map(lambda (k,v): k + ':' + v, reprs)
            reprs = reduce(lambda x, y: x + ',' + y, reprs)
            return '{' + reprs + '}'
        elif isinstance(obj, type):
            return repr(obj).replace(' ', '')
        else:
            return repr(obj) 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sandbox.py    MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: html5parser.py    MIT License 5 votes vote down vote up
def method_decorator_metaclass(function):
    class Decorated(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if isinstance(attribute, types.FunctionType):
                    attribute = function(attribute)

                classDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, classDict)
    return Decorated 
Example 35
Project: flasky   Author: RoseOu   File: langhelpers.py    MIT License 5 votes vote down vote up
def get_cls_kwargs(cls, _set=None):
    """Return the full set of inherited kwargs for the given `cls`.

    Probes a class's __init__ method, collecting all named arguments.  If the
    __init__ defines a \**kwargs catch-all, then the constructor is presumed
    to pass along unrecognized keywords to its base classes, and the
    collection process is repeated recursively on each of the bases.

    Uses a subset of inspect.getargspec() to cut down on method overhead.
    No anonymous tuple arguments please !

    """
    toplevel = _set is None
    if toplevel:
        _set = set()

    ctr = cls.__dict__.get('__init__', False)

    has_init = ctr and isinstance(ctr, types.FunctionType) and \
        isinstance(ctr.__code__, types.CodeType)

    if has_init:
        names, has_kw = inspect_func_args(ctr)
        _set.update(names)

        if not has_kw and not toplevel:
            return None

    if not has_init or has_kw:
        for c in cls.__bases__:
            if get_cls_kwargs(c, _set) is None:
                break

    _set.discard('self')
    return _set 
Example 36
Project: flasky   Author: RoseOu   File: html5parser.py    MIT License 5 votes vote down vote up
def method_decorator_metaclass(function):
    class Decorated(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if isinstance(attribute, types.FunctionType):
                    attribute = function(attribute)

                classDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, classDict)
    return Decorated 
Example 37
Project: flasky   Author: RoseOu   File: html5parser.py    MIT License 5 votes vote down vote up
def method_decorator_metaclass(function):
    class Decorated(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if isinstance(attribute, types.FunctionType):
                    attribute = function(attribute)

                classDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, classDict)
    return Decorated 
Example 38
Project: DJFeet   Author: libre-man   File: test_feedback.py    MIT License 5 votes vote down vote up
def test_feedback_percentage_liked(feedback, expected):
    if isinstance(expected, Number) or isinstance(expected, FunctionType):
        got = f.feedback_percentage_liked({'feedback': feedback})
        if callable(expected):
            assert expected(got)
        else:
            assert abs(got - expected) < EPSILON
    else:
        with pytest.raises(expected):
            got = f.feedback_percentage_liked({'feedback': feedback}) 
Example 39
Project: sic   Author: Yanixos   File: html5parser.py    GNU General Public License v3.0 5 votes vote down vote up
def method_decorator_metaclass(function):
    class Decorated(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if isinstance(attribute, types.FunctionType):
                    attribute = function(attribute)

                classDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, classDict)
    return Decorated 
Example 40
Project: sic   Author: Yanixos   File: monkey.py    GNU General Public License v3.0 5 votes vote down vote up
def get_unpatched(item):
    lookup = (
        get_unpatched_class if isinstance(item, six.class_types) else
        get_unpatched_function if isinstance(item, types.FunctionType) else
        lambda item: None
    )
    return lookup(item) 
Example 41
Project: pytac   Author: dls-controls   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_get_div_rigidity():
    div = utils.get_div_rigidity(3.e+9)
    assert isinstance(div, types.FunctionType)
    numpy.testing.assert_almost_equal(div(numpy.pi), 3.139419278848089e-07)
    numpy.testing.assert_almost_equal(div(1.e+8), 9.993081933333334) 
Example 42
Project: pytac   Author: dls-controls   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_get_mult_rigidity():
    mult = utils.get_mult_rigidity(3.e+9)
    assert isinstance(mult, types.FunctionType)
    numpy.testing.assert_almost_equal(mult(numpy.pi), 31437675.329275224)
    numpy.testing.assert_almost_equal(mult(1.e-8), 0.10006922855944561) 
Example 43
Project: bigquerylayers   Author: smandaric   File: monkey.py    GNU General Public License v3.0 5 votes vote down vote up
def get_unpatched(item):
    lookup = (
        get_unpatched_class if isinstance(item, six.class_types) else
        get_unpatched_function if isinstance(item, types.FunctionType) else
        lambda item: None
    )
    return lookup(item) 
Example 44
Project: AshsSDK   Author: thehappydinoa   File: html5parser.py    MIT License 5 votes vote down vote up
def method_decorator_metaclass(function):
    class Decorated(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if isinstance(attribute, types.FunctionType):
                    attribute = function(attribute)

                classDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, classDict)
    return Decorated 
Example 45
Project: AshsSDK   Author: thehappydinoa   File: monkey.py    MIT License 5 votes vote down vote up
def get_unpatched(item):
    lookup = (
        get_unpatched_class if isinstance(item, six.class_types) else
        get_unpatched_function if isinstance(item, types.FunctionType) else
        lambda item: None
    )
    return lookup(item) 
Example 46
Project: AshsSDK   Author: thehappydinoa   File: states.py    MIT License 5 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish 
Example 47
Project: fastpair   Author: carsonfarmer   File: test_fastpair.py    MIT License 5 votes vote down vote up
def test_init(self):
        fp = FastPair()
        assert fp.min_points == 10
        assert isinstance(fp.dist, FunctionType)
        assert fp.initialized is False
        assert len(fp.points) == 0
        assert len(fp.neighbors) == 0 
Example 48
Project: py2swagger   Author: Arello-Mobile   File: utils.py    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 49
Project: pcc   Author: jiamo   File: lex.py    The Unlicense 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 50
Project: SublimeKSP   Author: nojanath   File: lex.py    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')
# -----------------------------------------------------------------------------