Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1085465
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T22:41:34+00:00 2026-05-16T22:41:34+00:00

Instead of writing code like this every time I define a class: class Foo(object):

  • 0

Instead of writing code like this every time I define a class:

class Foo(object): 
     def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.f = f
        self.g = g

I could use this recipe for automatic attribute assignment.

class Foo(object):
     @autoassign
     def __init__(self, a, b, c, d, e, f, g):
        pass

Two questions:

  1. Are there drawbacks or pitfalls associated with this shortcut?
  2. Is there a better way to achieve similar convenience?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T22:41:35+00:00Added an answer on May 16, 2026 at 10:41 pm

    There are some things about the autoassign code that bug me (mostly stylistic, but one more serious problem):

    1. autoassign does not assign an
      ‘args’ attribute:

      class Foo(object):
          @autoassign
          def __init__(self,a,b,c=False,*args):
              pass
      a=Foo('IBM','/tmp',True, 100, 101)
      print(a.args)
      # AttributeError: 'Foo' object has no attribute 'args'
      
    2. autoassign acts like a decorator.
      But autoassign(*argnames) calls a
      function which returns a decorator.
      To achieve this magic, autoassign
      needs to test the type of its first
      argument. If given a choice, I
      prefer functions not test
      the type of its arguments.

    3. There seems to be a considerable
      amount of code devoted to setting up
      sieve, lambdas within lambdas,
      ifilters, and lots of conditions.

      if kwargs:
          exclude, f = set(kwargs['exclude']), None
          sieve = lambda l:itertools.ifilter(lambda nv: nv[0] not in exclude, l)
      elif len(names) == 1 and inspect.isfunction(names[0]):
          f = names[0]
          sieve = lambda l:l
      else:
          names, f = set(names), None
          sieve = lambda l: itertools.ifilter(lambda nv: nv[0] in names, l)
      

      I think there might be a simpler way. (See
      below).

    4. for _ in
      itertools.starmap(assigned.setdefault,
      defaults): pass
      . I don’t think
      map or starmap was meant to call
      functions, whose only purpose is their
      side effects. It could have been
      written more clearly with the mundane:

      for key,value in defaults.iteritems():
          assigned.setdefault(key,value)
      

    Here is an alternative simpler implementation which has the same functionality as autoassign (e.g. can do includes and excludes), and which addresses the above points:

    import inspect
    import functools
    
    def autoargs(*include, **kwargs):
        def _autoargs(func):
            attrs, varargs, varkw, defaults = inspect.getargspec(func)
    
            def sieve(attr):
                if kwargs and attr in kwargs['exclude']:
                    return False
                if not include or attr in include:
                    return True
                else:
                    return False
    
            @functools.wraps(func)
            def wrapper(self, *args, **kwargs):
                # handle default values
                if defaults:
                    for attr, val in zip(reversed(attrs), reversed(defaults)):
                        if sieve(attr):
                            setattr(self, attr, val)
                # handle positional arguments
                positional_attrs = attrs[1:]
                for attr, val in zip(positional_attrs, args):
                    if sieve(attr):
                        setattr(self, attr, val)
                # handle varargs
                if varargs:
                    remaining_args = args[len(positional_attrs):]
                    if sieve(varargs):
                        setattr(self, varargs, remaining_args)
                # handle varkw
                if kwargs:
                    for attr, val in kwargs.items():
                        if sieve(attr):
                            setattr(self, attr, val)
                return func(self, *args, **kwargs)
            return wrapper
        return _autoargs
    

    And here is the unit test I used to check its behavior:

    import sys
    import unittest
    import utils_method as um
    
    class Test(unittest.TestCase):
        def test_autoargs(self):
            class A(object):
                @um.autoargs()
                def __init__(self,foo,path,debug=False):
                    pass
            a=A('rhubarb','pie',debug=True)
            self.assertTrue(a.foo=='rhubarb')
            self.assertTrue(a.path=='pie')
            self.assertTrue(a.debug==True)
    
            class B(object):
                @um.autoargs()
                def __init__(self,foo,path,debug=False,*args):
                    pass
            a=B('rhubarb','pie',True, 100, 101)
            self.assertTrue(a.foo=='rhubarb')
            self.assertTrue(a.path=='pie')
            self.assertTrue(a.debug==True)
            self.assertTrue(a.args==(100,101))        
    
            class C(object):
                @um.autoargs()
                def __init__(self,foo,path,debug=False,*args,**kw):
                    pass
            a=C('rhubarb','pie',True, 100, 101,verbose=True)
            self.assertTrue(a.foo=='rhubarb')
            self.assertTrue(a.path=='pie')
            self.assertTrue(a.debug==True)
            self.assertTrue(a.verbose==True)        
            self.assertTrue(a.args==(100,101))        
    
        def test_autoargs_names(self):
            class C(object):
                @um.autoargs('bar','baz','verbose')
                def __init__(self,foo,bar,baz,verbose=False):
                    pass
            a=C('rhubarb','pie',1)
            self.assertTrue(a.bar=='pie')
            self.assertTrue(a.baz==1)
            self.assertTrue(a.verbose==False)
            self.assertRaises(AttributeError,getattr,a,'foo')
    
        def test_autoargs_exclude(self):
            class C(object):
                @um.autoargs(exclude=('bar','baz','verbose'))
                def __init__(self,foo,bar,baz,verbose=False):
                    pass
            a=C('rhubarb','pie',1)
            self.assertTrue(a.foo=='rhubarb')
            self.assertRaises(AttributeError,getattr,a,'bar')
    
        def test_defaults_none(self):
            class A(object):
                @um.autoargs()
                def __init__(self,foo,path,debug):
                    pass
            a=A('rhubarb','pie',debug=True)
            self.assertTrue(a.foo=='rhubarb')
            self.assertTrue(a.path=='pie')
            self.assertTrue(a.debug==True)
    
    
    if __name__ == '__main__':
        unittest.main(argv = sys.argv + ['--verbose'])
    

    PS. Using autoassign or autoargs is compatible with IPython code completion.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been writing some pretty long SQL queries in notepad and then pasting them
What I am trying to do is really simple . I'd like to convert
I'm want to do a class with file extensions, I thought the extensions should
I recently inherited some code that someone else had written. I discovered that everywhere
I'm writing a Unicode library for C as a personal exercise. Without the actual
I'm writing test cases for a project which still uses the Acegi plugin (not
I am working on a client (Silverlight) interface to a collection of webmethod. And
I want to make '==' operator use approximate comparison in my program: float values
I'm a bit confused about when using the IRepository pattern, when actually to load

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.