spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

How to promulgate a list of arguments for a python function?


I'm going ahead with a variant on the approach I outlined in my original post, in which I attach an attribute to __init__. However, instead of making it a list, I am taking the more flexible approach of using a function. I define an unattached function argNames that takes one or more classes or functions as arguments and returns a set of argument names, using inspect and, recursively, calls to the argNames attribute of the functions. I can then attach this to VideoFileChoiceWidget.__init__ (for instance), using:

class
VideoFileChoiceWidget(ContainerWidget):
    ...<stuff>...
    def __init__(arg1, arg2, ..., **kwargs):
        ...<more stuff>...

    __init__.argNames = lambda:
(argNames(ContainerWidget) | 
                                 {'description',
'visible', 'children'})

Anyone who wants to pass arguments on to VideoFileChoiceWidget uses filterArgs as outlined in the question. I have implemented this and it seems to work.

Below, for reference, are my current definitions of argNames and filterArgs.

def argNames(*args):
    """
    Get the names of the argument for a function

    Returns:
    --------
    A set whose members are the argument names

    Parameters:
    -----------
    func1, func2, ... -- the functions to be
analyzed. The arguments
        are discovered by inspecting func. In
addition, if
        func.argNames is defined, it is called
(without arguments) to
        get a list of addition names. Any number
of functions may be
        listed. If func is a class, func.__init__
is used
        instead. 'self' is always removed from the
argument list.
    """
    names = set({})
    for a in args:
        try:
            func = a
            spec = inspect.getargspec(func)
        except TypeError:
            func = a.__init__
            spec = inspect.getargspec(func)
        names |= set(spec.args)
        try:
            names |= set(func.argNames())
        except AttributeError:
            pass
    names.discard('self')
    return(names)

def filterArgs(func, **kwargs):
    """
    Select keyword arguments for a function
    """
    args = argNames(func)
    ks = set(kwargs.keys())
    ks.discard('self')
    kinc = ks & args
    kexc = ks - args
    inc = {k: kwargs[k] for k in kinc}
    exc = {k: kwargs[k] for k in kexc}
    return(inc, exc)

Categories : Python

Related to : How to promulgate a list of arguments for a python function?
Kivy/Python - calling function with 3 arguments without giving any
UrlRequest(search_url, self.found_location) This passes UrlRequest the two parameters, the second of which is the function itself. UrlRequest automatically calls that function with two arguments, specifically itself and the data it has retrieved. Shoudn't the call in UrlRequest look more like: self.found_location(sth,sth) No. The point is that you don't want to call the function, only to p

Categories : Function
Python mock patch a function missing arguments
I don't know much about Mock, but I think the main issue is that you should pass the mock function in the new argument, not in new_callable, and use patch.object to actually overwrite a method within an object. This seems to work: from mock import patch class MyManager(object): def dowork(self, value1, value2): print value1, value2 class MyModel(object): objects = MyManager()

Categories : Python
Function with fewer arguments and optional arguments
You can use functools.partial to make this a lot easier: from functools import partial def myfunc_general(constant, a=1, b=2): return constant+a+b myfunct_specific1 = partial(myfunc_general, a=10) myfunct_specific2 = partial(myfunc_general, a=20) Below is a demonstration: >>> from functools import partial >>> >>> def myfunc_general(constant, a=1, b=2): ...

Categories : Python
why `arguments` is a Array-like in JS function?
Just try and you get it: $ js > !function(){console.log(arguments.length);}(1,2,3) 3 Also: >!function(){ console.log(Object.keys(arguments).length); }(1,2,3) 3

Categories : Javascript
Python: Using defined arguments with *args
You need to do this: def use_from(step_todo, *args): use_all(step_todo, *args) ...otherwise you are calling use_all with a single arg containing a list of values, instead of calling it with the multiple args also, don't put a space between your function and the parentheses, it's bad style :) to get around the problem of wait_complete taking value of your first arg you need to pass it exp

Categories : Python
Recently Add
Overriding save method vs Model Method?
function encrypt file - input & output to same file in python
urllib.error.URLError:
python if statement fails to compute compound logic
referencing sphinx generated Python docs from YAML file
Subclassing datetime64
filter view from url parameter with an intermediate model?
How to stream twitter mentions with tweepy?
How to space out rows and columns in Python Tkinter
Python: Using BeautifulSoup to save content to CSV
Python - Take parts of a txt file and put them in another txt
Python socket send doesn't send the whole string
Python: prime test
How to import one day old logs
Appending filters to django models
Python: parsing .xls file failed with both xlrd and pandas
writing pandas dataframe columns to csv rows staggered
parse_args doesn't seem to understand json arguments
Django ORM, get data
Pygame, keep jumping and glitching through the "ground"
Is it possible to import a class defined inside a function?
How to handle a variable number of nested for loops?
Boolean expression with strings
Object duplicated when using processing.Manager?
What is the syntax of PBS job limit directive
python 3.x overwrite previous terminal line
Deploying django app. on heroku (gunicorn, wsgi issue)
How can I create an "ID" column in one dataframe based on the index of another dataframe?
PIL Module Error
pandas.read_html returns only one table
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.