sys._getframe.f_locals

Here are the examples of the python api sys._getframe.f_locals taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

37 Examples 7

Example 1

Project: spyral Source File: compat.py
Function: setter
        def setter(self, fset):
            cls_ns = sys._getframe(1).f_locals
            for key, value in cls_ns.iteritems():
                if value == self:
                    propname = key
                    break
            cls_ns[propname] = property(self.fget, fset,
                                        self.fdel, self.__doc__)
            return cls_ns[propname]

Example 2

Project: ReproWeb Source File: repr.py
Function: dump
def dump(obj=missing):
    """Print the object details to stdout._write (for the interactive
    console of the web debugger.
    """
    gen = DebugReprGenerator()
    if obj is missing:
        rv = gen.dump_locals(sys._getframe(1).f_locals)
    else:
        rv = gen.dump_object(obj)
    sys.stdout._write(rv)

Example 3

Project: PyFITS Source File: util.py
    def __ter(self, f, arg):
        args = [self._fget, self._fset, self._fdel, self.__doc__]
        args[arg] = f
        cls_ns = sys._getframe(1).f_locals
        for k, v in iteritems(cls_ns):
            if v is self:
                property_name = k
                break

        cls_ns[property_name] = lazyproperty(*args)

        return cls_ns[property_name]

Example 4

Project: energy Source File: energy.py
Function: setter
        def setter(self, fset):
            ns = sys._getframe(1).f_locals
            for k, v in ns.iteritems():
                if v == self:
                    propname = k
                    break
            ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
            return ns[propname]

Example 5

Project: cgstudiomap Source File: utils.py
Function: find_locals
def find_locals(func,depth=0):
    '''apply func to the locals at each stack frame till func returns a non false value'''
    while 1:
        _ = func(sys._getframe(depth).f_locals)
        if _: return _
        depth += 1

Example 6

Project: extdbg Source File: watcher.py
def add_watcher_attribute(name, watch_get=False):
    def attr_watch_get(self):
        value = getattr(self, '_add_watcher_' + name, 'unset')
        if watch_get:
            pprint(from_where_called(), name, 'is', value)
        return value

    def attr_watch_set(self, value):
        pprint(from_where_called(), name, 'set to', value)
        setattr(self, '_add_watcher_' + name, value)

    sys._getframe(1).f_locals[name] = property(attr_watch_get, attr_watch_set)

Example 7

Project: PythonUtils Source File: misc.py
def explicitly(name, stackadd=0):
	"""
	This is an alias for adding to '__all__'.  Less error-prone than using
	__all__ itself, since setting __all__ directly is prone to stomping on
	things implicitly exported via L{alias}.

	@note Taken from PyExport (which could turn out pretty cool):
	@li @a http://codebrowse.launchpad.net/~glyph/
	@li @a http://glyf.livejournal.com/74356.html
	"""
	packageVars = sys._getframe(1+stackadd).f_locals
	globalAll = packageVars.setdefault('__all__', [])
	globalAll.append(name)

Example 8

Project: music-player Source File: __init__.py
def NSDictionaryOfVariableBindings(*names):
    """
    Return a dictionary with the given names and there values.
    """
    import sys
    variables = sys._getframe(1).f_locals

    return {
        nm: variables[nm]
        for nm in names
    }

Example 9

Project: protocyt Source File: meta.py
    def __new__(mcs, name, bases, internals):
        doc = internals.get('__doc__')
        if doc is not None:
            scope = sys._getframe(1).f_locals
            module_name = internals.get('__module__')
            protocol_name = '_'.join(
                (module_name.replace('_', '').replace('.', '_'), name)
                )
            module = sys.modules[module_name]
            output_dir = Path.from_file(module.__file__).up()
            from_source(inspect.cleandoc(doc), protocol_name, output_dir, True)
            protocol = __import__(protocol_name, scope, scope, [], -1)
            base = getattr(protocol, name)
            return type.__new__(mcs, name, bases + (base,), internals)
        else:
            return type.__new__(mcs, name, bases, internals)

Example 10

Project: flypy Source File: entrypoints.py
def scoping_decorator(decorator):
    @wraps(decorator)
    def decorator_wrapper(*args, **kwargs):
        scope = kwargs.pop('scope', sys._getframe(1).f_locals)
        if applyable(args, kwargs):
            return decorator(*args, scope=scope)
        return lambda f: decorator(f, *args, scope=scope, **kwargs)

    return decorator_wrapper

Example 11

Project: mythbox Source File: interface.py
Function: invariant
def invariant(call):
    f_locals = sys._getframe(1).f_locals
    tags = f_locals.setdefault(TAGGED_DATA, {})
    invariants = tags.setdefault('invariants', [])
    invariants.append(call)
    return _decorator_non_return

Example 12

Project: aiohttp Source File: test_client_functional_oldstyle.py
Function: define
    @staticmethod
    def define(rmatch):
        def wrapper(fn):
            f_locals = sys._getframe(1).f_locals
            mapping = f_locals.setdefault('_mapping', [])
            mapping.append((re.compile(rmatch), fn.__name__))
            return fn

        return wrapper

Example 13

Project: weboob Source File: property.py
Function: setter
    def setter(self, fset):
        cls_ns = sys._getframe(1).f_locals
        for k, v in cls_ns.iteritems():
            if v == self:
                propname = k
                break
        cls_ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
        return cls_ns[propname]

Example 14

Project: weboob Source File: property.py
Function: deleter
    def deleter(self, fdel):
        cls_ns = sys._getframe(1).f_locals
        for k, v in cls_ns.iteritems():
            if v == self:
                propname = k
                break
        cls_ns[propname] = property(self.fget, self.fset, fdel, self.__doc__)
        return cls_ns[propname]

Example 15

Project: TwistedBot Source File: interface.py
def taggedValue(key, value):
    """Attaches a tagged value to an interface at definition time."""
    f_locals = sys._getframe(1).f_locals
    tagged_values = f_locals.setdefault(TAGGED_DATA, {})
    tagged_values[key] = value
    return _decorator_non_return

Example 16

Project: HoneyConnector Source File: _compat.py
Function: setter
        def setter(self, value):
            cls_ns = sys._getframe(1).f_locals
            for k, v in cls_ns.iteritems():
                if v == self:
                    name = k
                    break
            cls_ns[name] = property(self.fget, value, self.fdel, self.__doc__)
            return cls_ns[name]

Example 17

Project: pytest Source File: pytester.py
    def assert_contains(self, entries):
        __tracebackhide__ = True
        i = 0
        entries = list(entries)
        backlocals = sys._getframe(1).f_locals
        while entries:
            name, check = entries.pop(0)
            for ind, call in enumerate(self.calls[i:]):
                if call._name == name:
                    print_("NAMEMATCH", name, call)
                    if eval(check, backlocals, call.__dict__):
                        print_("CHECKERMATCH", repr(check), "->", call)
                    else:
                        print_("NOCHECKERMATCH", repr(check), "-", call)
                        continue
                    i += ind + 1
                    break
                print_("NONAMEMATCH", name, "with", call)
            else:
                pytest.fail("could not find %r check %r" % (name, check))

Example 18

Project: ra Source File: utils.py
def caller_scope(back=1):
    import sys
    return sys._getframe(back + 1).f_locals

Example 19

Project: headphones Source File: __init__.py
Function: expose
def expose(func=None, alias=None):
    """Expose the function, optionally providing an alias or set of aliases."""
    def expose_(func):
        func.exposed = True
        if alias is not None:
            if isinstance(alias, basestring):
                parents[alias.replace(".", "_")] = func
            else:
                for a in alias:
                    parents[a.replace(".", "_")] = func
        return func

    import sys
    import types
    if isinstance(func, (types.FunctionType, types.MethodType)):
        if alias is None:
            # @expose
            func.exposed = True
            return func
        else:
            # func = expose(func, alias)
            parents = sys._getframe(1).f_locals
            return expose_(func)
    elif func is None:
        if alias is None:
            # @expose()
            parents = sys._getframe(1).f_locals
            return expose_
        else:
            # @expose(alias="alias") or
            # @expose(alias=["alias1", "alias2"])
            parents = sys._getframe(1).f_locals
            return expose_
    else:
        # @expose("alias") or
        # @expose(["alias1", "alias2"])
        parents = sys._getframe(1).f_locals
        alias = func
        return expose_

Example 20

Project: NOT_UPDATED_Sick-Beard-Dutch Source File: __init__.py
Function: expose
def expose(func=None, alias=None):
    """Expose the function, optionally providing an alias or set of aliases."""
    def expose_(func):
        func.exposed = True
        if alias is not None:
            if isinstance(alias, basestring):
                parents[alias.replace(".", "_")] = func
            else:
                for a in alias:
                    parents[a.replace(".", "_")] = func
        return func
    
    import sys, types
    if isinstance(func, (types.FunctionType, types.MethodType)):
        if alias is None:
            # @expose
            func.exposed = True
            return func
        else:
            # func = expose(func, alias)
            parents = sys._getframe(1).f_locals
            return expose_(func)
    elif func is None:
        if alias is None:
            # @expose()
            parents = sys._getframe(1).f_locals
            return expose_
        else:
            # @expose(alias="alias") or
            # @expose(alias=["alias1", "alias2"])
            parents = sys._getframe(1).f_locals
            return expose_
    else:
        # @expose("alias") or
        # @expose(["alias1", "alias2"])
        parents = sys._getframe(1).f_locals
        alias = func
        return expose_

Example 21

Project: ReproWeb Source File: script.py
Function: run
def run(namespace=None, action_prefix='action_', args=None):
    """Run the script.  Participating actions are looked up in the caller's
    namespace if no namespace is given, otherwise in the dict provided.
    Only items that start with action_prefix are processed as actions.  If
    you want to use all items in the namespace provided as actions set
    action_prefix to an empty string.

    :param namespace: An optional dict where the functions are looked up in.
                      By default the local namespace of the caller is used.
    :param action_prefix: The prefix for the functions.  Everything else
                          is ignored.
    :param args: the arguments for the function.  If not specified
                 :data:`sys.argv` without the first argument is used.
    """
    if namespace is None:
        namespace = sys._getframe(1).f_locals
    actions = find_actions(namespace, action_prefix)

    if args is None:
        args = sys.argv[1:]
    if not args or args[0] in ('-h', '--help'):
        return print_usage(actions)
    elif args[0] not in actions:
        fail('Unknown action \'%s\'' % args[0])

    arguments = {}
    types = {}
    key_to_arg = {}
    long_options = []
    formatstring = ''
    func, doc, arg_def = actions[args.pop(0)]
    for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
        real_arg = arg.replace('-', '_')
        if shortcut:
            formatstring += shortcut
            if not isinstance(default, bool):
                formatstring += ':'
            key_to_arg['-' + shortcut] = real_arg
        long_options.append(isinstance(default, bool) and arg or arg + '=')
        key_to_arg['--' + arg] = real_arg
        key_to_arg[idx] = real_arg
        types[real_arg] = option_type
        arguments[real_arg] = default

    try:
        optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
    except getopt.GetoptError, e:
        fail(str(e))

    specified_arguments = set()
    for key, value in enumerate(posargs):
        try:
            arg = key_to_arg[key]
        except IndexError:
            fail('Too many parameters')
        specified_arguments.add(arg)
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for argument %s (%s): %s' % (key, arg, value))

    for key, value in optlist:
        arg = key_to_arg[key]
        if arg in specified_arguments:
            fail('Argument \'%s\' is specified twice' % arg)
        if types[arg] == 'boolean':
            if arg.startswith('no_'):
                value = 'no'
            else:
                value = 'yes'
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for \'%s\': %s' % (key, value))

    newargs = {}
    for k, v in arguments.iteritems():
        newargs[k.startswith('no_') and k[3:] or k] = v
    arguments = newargs
    return func(**arguments)

Example 22

Project: patterns Source File: __init__.py
Function: compile_func
def compile_func(func, tree):
    def wrap_func(func_tree, arg_names):
        return FunctionDef(
            name = func_tree.name + '__wrapped',
            args = make_arguments(lmap(A, arg_names)),
            decorator_list = [],
            body = [
                func_tree,
                Return(value=N(func_tree.name))
            ]
        )

    context = sys._getframe(2).f_locals
    if getattr(func, '__closure__', None) or getattr(func, 'func_closure', None):
        kwargs = context.copy()
        tree.body[0] = wrap_func(tree.body[0], kwargs.keys())
        _compile_func(func, tree, context)
        func.__code__ = context[func.__name__ + '__wrapped'](**kwargs).__code__
        return func
    else:
        _compile_func(func, tree, context)
        return context[func.__name__]

Example 23

Project: GoAtThrottleUp Source File: __init__.py
Function: expose
def expose(func=None, alias=None):
    """Expose the function, optionally providing an alias or set of aliases."""
    def expose_(func):
        func.exposed = True
        if alias is not None:
            if isinstance(alias, basestring):
                parents[alias.replace(".", "_")] = func
            else:
                for a in alias:
                    parents[a.replace(".", "_")] = func
        return func

    import sys, types
    if isinstance(func, (types.FunctionType, types.MethodType)):
        if alias is None:
            # @expose
            func.exposed = True
            return func
        else:
            # func = expose(func, alias)
            parents = sys._getframe(1).f_locals
            return expose_(func)
    elif func is None:
        if alias is None:
            # @expose()
            parents = sys._getframe(1).f_locals
            return expose_
        else:
            # @expose(alias="alias") or
            # @expose(alias=["alias1", "alias2"])
            parents = sys._getframe(1).f_locals
            return expose_
    else:
        # @expose("alias") or
        # @expose(["alias1", "alias2"])
        parents = sys._getframe(1).f_locals
        alias = func
        return expose_

Example 24

Project: WAPT Source File: script.py
Function: run
def run(namespace=None, action_prefix='action_', args=None):
    """Run the script.  Participating actions are looked up in the caller's
    namespace if no namespace is given, otherwise in the dict provided.
    Only items that start with action_prefix are processed as actions.  If
    you want to use all items in the namespace provided as actions set
    action_prefix to an empty string.

    :param namespace: An optional dict where the functions are looked up in.
                      By default the local namespace of the caller is used.
    :param action_prefix: The prefix for the functions.  Everything else
                          is ignored.
    :param args: the arguments for the function.  If not specified
                 :data:`sys.argv` without the first argument is used.
    """
    if namespace is None:
        namespace = sys._getframe(1).f_locals
    actions = find_actions(namespace, action_prefix)

    if args is None:
        args = sys.argv[1:]
    if not args or args[0] in ('-h', '--help'):
        return print_usage(actions)
    elif args[0] not in actions:
        fail('Unknown action \'%s\'' % args[0])

    arguments = {}
    types = {}
    key_to_arg = {}
    long_options = []
    formatstring = ''
    func, doc, arg_def = actions[args.pop(0)]
    for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
        real_arg = arg.replace('-', '_')
        if shortcut:
            formatstring += shortcut
            if not isinstance(default, bool):
                formatstring += ':'
            key_to_arg['-' + shortcut] = real_arg
        long_options.append(isinstance(default, bool) and arg or arg + '=')
        key_to_arg['--' + arg] = real_arg
        key_to_arg[idx] = real_arg
        types[real_arg] = option_type
        arguments[real_arg] = default

    try:
        optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
    except getopt.GetoptError as e:
        fail(str(e))

    specified_arguments = set()
    for key, value in enumerate(posargs):
        try:
            arg = key_to_arg[key]
        except IndexError:
            fail('Too many parameters')
        specified_arguments.add(arg)
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for argument %s (%s): %s' % (key, arg, value))

    for key, value in optlist:
        arg = key_to_arg[key]
        if arg in specified_arguments:
            fail('Argument \'%s\' is specified twice' % arg)
        if types[arg] == 'boolean':
            if arg.startswith('no_'):
                value = 'no'
            else:
                value = 'yes'
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for \'%s\': %s' % (key, value))

    newargs = {}
    for k, v in iteritems(arguments):
        newargs[k.startswith('no_') and k[3:] or k] = v
    arguments = newargs
    return func(**arguments)

Example 25

Project: cylc Source File: _helper.py
Function: expose
def expose(func=None, alias=None):
    """
    Expose the function or class, optionally providing an alias or set of aliases.
    """
    def expose_(func):
        func.exposed = True
        if alias is not None:
            if isinstance(alias, basestring):
                parents[alias.replace(".", "_")] = func
            else:
                for a in alias:
                    parents[a.replace(".", "_")] = func
        return func

    import sys
    import types
    decoratable_types = types.FunctionType, types.MethodType, type,
    if not IS_PY3:
        # Old-style classes are type types.ClassType.
        decoratable_types += types.ClassType,
    if isinstance(func, decoratable_types):
        if alias is None:
            # @expose
            func.exposed = True
            return func
        else:
            # func = expose(func, alias)
            parents = sys._getframe(1).f_locals
            return expose_(func)
    elif func is None:
        if alias is None:
            # @expose()
            parents = sys._getframe(1).f_locals
            return expose_
        else:
            # @expose(alias="alias") or
            # @expose(alias=["alias1", "alias2"])
            parents = sys._getframe(1).f_locals
            return expose_
    else:
        # @expose("alias") or
        # @expose(["alias1", "alias2"])
        parents = sys._getframe(1).f_locals
        alias = func
        return expose_

Example 26

Project: comtypes Source File: test_variant.py
Function: run_test
def run_test(rep, msg, func=None, previous={}, results={}):
##    items = [None] * rep
    if func is None:
        locals = sys._getframe(1).f_locals
        func = eval("lambda: %s" % msg, locals)
    items = xrange(rep)
    from time import clock
    start = clock()
    for i in items:
        func(); func(); func(); func(); func()
    stop = clock()
    duration = (stop-start)*1e6/5/rep
    try:
        prev = previous[msg]
    except KeyError:
        print >> sys.stderr, "%40s: %7.1f us" % (msg, duration)
        delta = 0.0
    else:
        delta = duration / prev * 100.0
        print >> sys.stderr, "%40s: %7.1f us, time = %5.1f%%" % (msg, duration, delta)
    results[msg] = duration
    return delta

Example 27

Project: music-player Source File: _descriptors.py
Function: synthesize
def synthesize(name, copy=False, readwrite=True, type=_C_ID, ivarName=None):
    """
    Use this in a class dictionary to syntheze simple setting/setter methods.

    Note: this is only necessary to get propper behaviour when Key-Value coding
    is used and special features (like copying) are needed

    usage::

        class MyClass (NSObject):
            objc.synthesize('someTitle', copy=True)

    """
    if not name:
        raise ValueError("Empty property name")

    if ivarName is None:
        ivarName = '_' + name

    classDict = sys._getframe(1).f_locals

    setterName = 'set%s%s_'%(name[0].upper(), name[1:])

    if copy:
        setter = textwrap.dedent('''
            def %(name)s(self, value):
                self.%(ivar)s = value.copy()
            ''' % dict(name=setterName, ivar=ivarName))

    else:
        setter = textwrap.dedent('''
            def %(name)s(self, value):
                self.%(ivar)s = value
            ''' % dict(name=setterName, ivar=ivarName))

    getter = textwrap.dedent('''
            def %(name)s(self):
                return self.%(ivar)s
            ''' % dict(name=name, ivar=ivarName))

    if readwrite:
        exec(setter, globals(), classDict)

    exec(getter, globals(), classDict)

    classDict[ivarName] = ivar(type=type)

Example 28

Project: flypy Source File: entrypoints.py
Function: jit
def jit(f=None, *args, **kwds):
    """
    @jit entry point:

        @jit
        def myfunc(a, b): return a + b

        @jit('a -> b')
        def myfunc(a, b): return a + b

        @jit
        class Foo(object): pass

        @jit('Foo[a]')
        class Foo(object): pass
    """
    kwds['scope'] = kwds.pop('scope', sys._getframe(1).f_locals)

    if isinstance(f, (type, types.FunctionType, types.ClassType)):
        return _jit(f, *args, **kwds)

    arg = f
    return lambda f: _jit(f, arg, *args, **kwds)

Example 29

Project: actuator Source File: utils.py
Function: call
    def __call__(self, *args, **kwargs):
        class_locals = sys._getframe(1).f_locals
        modifiers = class_locals.setdefault(MODIFIERS, [])
        modifiers.append((self, args, kwargs))

Example 30

Project: cyberflex-shell Source File: TLV_utils.py
Function: init
    def __init__(self,name):
        self.name = name
        sys._getframe(1).f_locals[name] = self

Example 31

Project: Camelot Source File: statements.py
Function: init
    def __init__( self, *args, **kwargs ):
        # jam this mutator into the class's mutator list
        class_locals = sys._getframe(1).f_locals
        mutators = class_locals.setdefault( MUTATORS, [] )
        mutators.append( (self, args, kwargs) )

Example 32

Project: Nuitka Source File: Inspection.py
Function: f
def f():
    print("Func locals", sys._getframe().f_locals)
    print("Func flags", sys._getframe().f_code.co_flags)

Example 33

Project: Nuitka Source File: Inspection.py
Function: g
def g():
    yield("Generator object locals", sys._getframe().f_locals)
    yield("Generator object flags", sys._getframe().f_code.co_flags)

Example 34

Project: badideas Source File: interfaces.py
Function: implements
def implements(*interfaces):
    cls_scope = sys._getframe(1).f_locals
    metacls = cls_scope.get('__metaclass__')
    metafactory = make_meta_factory(metacls, interfaces)
    cls_scope['__metaclass__'] = metafactory

Example 35

Project: rez Source File: scope.py
Function: enter
    def __enter__(self):
        locals_ = sys._getframe(1).f_locals
        self.__dict__["locals"] = locals_.copy()
        return self

Example 36

Project: rez Source File: scope.py
Function: exit
    def __exit__(self, *args):
        # find what's changed
        updates = {}
        d = self.__dict__
        locals_ = sys._getframe(1).f_locals
        self_locals = d["locals"]
        for k, v in locals_.iteritems():
            if not (k.startswith("__") and k.endswith("__")) \
                    and (k not in self_locals or v != self_locals[k]) \
                    and not isinstance(v, _Scope):
                updates[k] = v

        # merge updated local vars with attributes
        self.update(updates)

        # restore upper scope
        locals_.clear()
        locals_.update(self_locals)

        self_context = d["context"]
        if self_context:
            self_context._scope_exit(d["name"])

Example 37

Project: werkzeug Source File: script.py
Function: run
def run(namespace=None, action_prefix='action_', args=None):
    """Run the script.  Participating actions are looked up in the caller's
    namespace if no namespace is given, otherwise in the dict provided.
    Only items that start with action_prefix are processed as actions.  If
    you want to use all items in the namespace provided as actions set
    action_prefix to an empty string.

    :param namespace: An optional dict where the functions are looked up in.
                      By default the local namespace of the caller is used.
    :param action_prefix: The prefix for the functions.  Everything else
                          is ignored.
    :param args: the arguments for the function.  If not specified
                 :data:`sys.argv` without the first argument is used.
    """
    _deprecated()
    if namespace is None:
        namespace = sys._getframe(1).f_locals
    actions = find_actions(namespace, action_prefix)

    if args is None:
        args = sys.argv[1:]
    if not args or args[0] in ('-h', '--help'):
        return print_usage(actions)
    elif args[0] not in actions:
        fail('Unknown action \'%s\'' % args[0])

    arguments = {}
    types = {}
    key_to_arg = {}
    long_options = []
    formatstring = ''
    func, doc, arg_def = actions[args.pop(0)]
    for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
        real_arg = arg.replace('-', '_')
        if shortcut:
            formatstring += shortcut
            if not isinstance(default, bool):
                formatstring += ':'
            key_to_arg['-' + shortcut] = real_arg
        long_options.append(isinstance(default, bool) and arg or arg + '=')
        key_to_arg['--' + arg] = real_arg
        key_to_arg[idx] = real_arg
        types[real_arg] = option_type
        arguments[real_arg] = default

    try:
        optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
    except getopt.GetoptError as e:
        fail(str(e))

    specified_arguments = set()
    for key, value in enumerate(posargs):
        try:
            arg = key_to_arg[key]
        except IndexError:
            fail('Too many parameters')
        specified_arguments.add(arg)
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for argument %s (%s): %s' % (key, arg, value))

    for key, value in optlist:
        arg = key_to_arg[key]
        if arg in specified_arguments:
            fail('Argument \'%s\' is specified twice' % arg)
        if types[arg] == 'boolean':
            if arg.startswith('no_'):
                value = 'no'
            else:
                value = 'yes'
        try:
            arguments[arg] = converters[types[arg]](value)
        except ValueError:
            fail('Invalid value for \'%s\': %s' % (key, value))

    newargs = {}
    for k, v in iteritems(arguments):
        newargs[k.startswith('no_') and k[3:] or k] = v
    arguments = newargs
    return func(**arguments)