Unpacking object variables in python
Asked Answered
M

4

10

I'm thinking if there is some way to unpack object attributes. Usually doing this involves series of:

self.x = x
self.y = y
... #etc.

However it should be possible to do it better.

I'm thinking about something like:

def __init__(self,x,y,z):
  self.(x,y,z) = x,y,z

or maybe:

with x,y,z unpack(self)

or even function like:

def __init__(self,x,y,z):
  unpack(self,x,y,z)

Any ideas? Or is there some more pythonic way to do this?

Millennium answered 24/9, 2013 at 4:16 Comment(4)
for name in ('x','y','z'): setattr(self, name, locals()[name])Approver
What is the problem with doing it the normal way?Whiffler
if you have a predictable pattern in your attributes of an object, it implies you should have created a dict to collect those values, and a getter method to access them. Writing non-predictable attribute is what human should be doing.Bevins
And you can unpack any dict.Bevins
L
6

You might want to use namedtuple, which does exactly the thing you want:

Code example from Official Python Documentation:

Point = namedtuple('Point', ['x', 'y'], verbose=True)

The above code is equivalent to:

class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create a new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Point(x=%r, y=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.   Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')

Here's how to use it:

>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

Source: http://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

One thing worth mentioning is that namedtuple is nothing but a regular class, and you could create a class that inherit from it.

Long answered 24/9, 2013 at 4:30 Comment(1)
This is copied and pasted from here: docs.python.org/2/library/…Bevins
G
2

I am pretty sure that you can do this: self.x, self.y, self.z = x, y, z

Goldfinch answered 24/9, 2013 at 5:4 Comment(0)
V
0

defining a function like unpack(self,x,y,z) may not be a good idea as the function is not generic enough (the object's composition is defined at runtime)

a more generic recipe to instantiate variables based on attribute names is explained here http://code.activestate.com/recipes/286185-automatically-initializing-instance-variables-from/

Vitovitoria answered 24/9, 2013 at 4:30 Comment(0)
W
-1
class Blahblah:
def __init__(self, *args, **kwargs):
    def unpack(vars_name, args, kwargs): #Cant be acceded for some instance in this place
        nonlocal self
        for i, var in enumerate(vars_name):
            exec(f"self.{var}={args[i]}")
        for key, value in kwargs.items():
            exec(f"self.{key}={value}")
    
    #You must add some validator for de length of args before the next code in this place
    
    vars_for_self = ["a","b","c"]
    unpack(vars_for_self, args, kwargs)
    
    del vars_for_self, args, kwargs, unpack #For clean vars in the class instance
            
    

    #First ways to check de self vars creation
    #print(self.__dict__)

    #Second way to check
    #print(locals()["self"].__dict__)

#Your other methods go here

Checkin results

if __name__== "__main__":
#And the last way
  c = Blahblah(3,4,5, x=6,y=7,z=0)
  #print(c.a)
  #print(c.x)

  print(c.__dict__)
  print(vars(Blahblah.__dict__["__init__"]))
Wergild answered 24/8, 2021 at 16:10 Comment(1)
This code is vulnerable to arbitrary code execution when values are untrusted and should never be used. x = "someVar"; y="1; import os; os.system('/bin/bash')"; exec(f"{x}={y}") exec() and eval() are dangerous functions and should never be used. getattr() and setattr() are better options, but should probably be avoided for similar reasons.Darren

© 2022 - 2024 — McMap. All rights reserved.