How to access args as a list?

Francesco Bochicchio bieffe62 at gmail.com
Sun Apr 4 06:11:59 EDT 2010


On 4 Apr, 00:58, kj <no.em... at please.post> wrote:
> Suppose I have a function with the following signature:
>
> def spam(x, y, z):
>     # etc.
>
> Is there a way to refer, within the function, to all its arguments
> as a single list?  (I.e. I'm looking for Python's equivalent of
> Perl's @_ variable.)
>
> I'm aware of locals(), but I want to preserve the order in which
> the arguments appear in the signature.
>
> My immediate aim is to set up a simple class that will allow me to
> iterate over the arguments passed to the constructor (plus let me
> refer to these individual arguments by their names using an
> instance.attribute syntax, as usual).
>
> The best I have managed looks like this:
>
> class _Spam(object):
>     def __init__(self, x, y, z):
>         self.__dict__ = OrderedDict(())
>         for p in inspect.getargspec(_Spam.__init__).args[1:]:
>             self.__dict__[p] = locals()[p]
>
>     def __iter__(self):
>         return iter(self.__dict__.values())
>
> but rolling out inspect.getargspec for this sort of thing looks to
> me like overkill.  Is there a more basic approach?
>
> P.S. this is just an example; the function I want to implement has
> more parameters in its signature, with longer, more informative
> names.

Hi, I once tried something to emulate in python the way Scala language
allows to automatically generate class attributes from constructor
parameter. I never tried in real code, but see if it fits your bill.
It uses class decorators though, so only works with python3. Here is
my code:

class FieldsDecorator:
    """It adds a generic scala-like constructor to a class.
     You can create as instance as c = MyClass(f1=3, f2=4)
     and have automatically c.f1=3, c.f2=4.
     Only parameter names listed in the decorator are allowed.
    """
    def __init__(self, *names):
        self.names = names

    def __call__(self, cls):
        def constructor(instance, **kwds):
            for n,v in kwds.items():
                if n in self.names:
                    setattr(instance, n, v)
                else: raise TypeError("%s is not a valid field" % s )
        setattr(cls, '__init__', constructor )
        return cls


@FieldsDecorator("uno", "due")
class Prova:
    pass

p = Prova(uno=12, due=9)
print (p.uno, p.due )

Ciao
----
FB



More information about the Python-list mailing list