1

I'm trying to make convenient passing some set of arguments to a number of functions (say 20).

Consider the following MWE (of course I don't really consider doing additions in such way):

def function(a, b):
    return a + b


class summation:
    def __init__(self, a, b):
        self.a = a
        self.b = b


s = summation(1,2)

function(**s.__dict__)

The reason I'm trying to do it is I have a bunch of functions all receiving 4 same arguments and I need to process them in a pipeline, passing from one function to another.

Implying that s always has only relevant fields is it a good way to pass arguments?

Michael Pankov
  • 3,581
  • 2
  • 23
  • 31

3 Answers3

3

It's a bad idea in general to use obj.__dict__ because the object dictionary does not contain any descriptors or other "magic" attributes that may exist on the object. It will also include hidden attributes that, by convention, are hidden behind a _ prefix. Thus, the obj.__dict__ technique really only works for completely basic types, and is not future proof if you decide to update any attributes to be properties so that you can control their getters/setters, etc. vars(obj) has this same issue.

class Rectangle(object):
    x = 0
    y = 0
    _width = 0
    height = 0

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        if value < 0:
            value = -value
            self.x -= value
        self._width = value

>>> r = Rectangle()
>>> r.__dict__
{}
>>> # this is because everything is class-level properties so far
>>> r.width = 50
>>> r.__dict__
{'_width': 50}
Michael Merickel
  • 23,153
  • 3
  • 54
  • 70
  • Sorry, I don't understand your question in the context of my answer. Your question implies that you just wanted to know the pitfalls. – Michael Merickel Nov 09 '12 at 18:06
2

Namedtuple does this for you outright.

Here's a talk from PyCon US 2011 [11:35 - 26:00]

from collections import namedtuple
Add = namedtuple("Add", "a b c d")

one = Add(1, 2, 3, 4)

def addme(a, b, c, d):
    print a + b
    print c + d

>>> addme(*one)
... 3
... 7
kreativitea
  • 1,741
  • 12
  • 14
0
for attribute, attribute_value in obj.__dict__.items():  # or obj.__dict__.iteritems() 
    print attribute, attribute_value
user3085513
  • 89
  • 2
  • 7
  • 1
    In general, you should include some explanation of how your code addresses the question. In this particular case, considering what the question is, I don't see how a couple of lines of code without explanation can possibly be an answer. – Adi Inbar Mar 24 '14 at 04:20