Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible get a dictionary of passed in parameters similar to kwargs(python)?

I'm currently creating an object like this:

class Obj(object):
    def __init__(self,**kwargs):
        params = ['val1','val2','val3','val4',...]
        for p in params:
            setattr(self,p,kwargs.get(p,None))

I'm doing this so I don't have to do this:

class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None,...):
        self.val1=val1
        self.val2=val2
        self.val3=val3
        self.val4=val4
        ...

My question is, can you do a mix of the two? Where I can define the expected parameters yet still loop the parameters to set the attributes? I like the idea of defining the expected parameters because it is self documenting and other developers don't have to search for what kwargs are used.

I know it seems pretty petty but I'm creating an object from some XML so I'll be passing in many parameters, it just clutters the code and bugs me.

I did google this but couldn't find anything, probably because dictionary and kwargs together point to kwarg examples.

UPDATE: To be more specific, is it possible to get a dictionary of passed in parameters so I don't have to use kwargs at all?

Sudo code:

class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None,...):
        for k,v in dictionary_of_paramters.iteritems():
            setattr(self,k,v)
like image 471
rjbez Avatar asked Jan 25 '26 09:01

rjbez


1 Answers

You can use the inspect module:

import inspect

def myargs(val1, val2, val3=None, val4=5):
        print inspect.currentframe().f_locals

it shows all the locals available on the current stack frame.

myargs('a','b')
==>  {'val3': None, 'val2': 'b', 'val1': 'a', 'val4': 5}

(note: it's not guaranteed to be implemented on all Python interpreters)

edit: i concur that it's not a pretty solution. what i would do is more like:

def _yourargs(*names):
        "returns a dict with your named local vars"
        alllocs = inspect.stack()[1][0].f_locals
        return {n:alllocs[n] for n in names}

def askformine(val1, val2, val3=None, val4=5):
        "example to show just those args i'm interested in"
        print _yourargs('val1','val2','val3','val4')

class Obj(object):
        "example inserting some named args as instance attributes"
        def __init__(self, arg1, arg2=4):
                 self.__dict__.update(_yourargs('arg1','arg2'))

edit2 slightly better:

def pickdict(d,*names):
    "picks some values from a dict"
    return {n:d[n] for n in names}

class Obj(object):
    "example inserting some named args as instance attributes"
    def __init__(self, arg1, arg2=4):
        self.__dict__.update(pickdict(locals(),'arg1','arg2'))
like image 69
Javier Avatar answered Jan 27 '26 21:01

Javier