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 654869
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:32:29+00:00 2026-05-13T22:32:29+00:00

Question How do you procedurally create a function in Python which takes specific named

  • 0

Question

How do you procedurally create a function in Python which takes specific named arguments but allow those argument names to be data-driven?

Example

Say, you want to create a class decorator, with_init, which adds an __init__ method with specific named arguments such that the following two classes are equivalent.

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

@with_init('x y z')
class C2(object):
    pass

My first attempt cheats by making a function which accepts *args instead of the specific named parameters:

class with_init(object):
    def __init__(self, params):
        self.params = params.split()

    def __call__(self, cls):
        def init(cls_self, *args):
            for param, value in zip(self.params, args):
                setattr(cls_self, param, value)
        cls.__init__ = init
        return cls

It works in some situations:

>>> C1(1,2,3)
<__main__.C1 object at 0x100c410>
>>> C2(1,2,3)
<__main__.C2 object at 0x100ca70>

But not so much in others:

>>> C2(1,2,3,4) # Should fail, but doesn't.
<__main__.C2 object at 0x100cc90>

>>> C2(x=1, y=2, z=3) # Should succeed, but doesn't.
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
TypeError: init() got an unexpected keyword argument 'y'

Of course I can add code to the nested init function to try and check for every possible situation, but it seems like there should be an easier way.

I’ve noticed that collections.namedtuple avoids these issues by making a string to pass to exec. That seems very round-about to me, but perhaps that’s the solution.

What is the correct implementation of with_init.__call__?

Note: I’d like a Python 2.x solution please.

  • 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-13T22:32:29+00:00Added an answer on May 13, 2026 at 10:32 pm

    Very roughly. This accepts kw args and checks to see that the number of args is correct

    def __call__(self, cls):
        def init(cls_self, *args, **kw):
            if len(args)+len(kw) != len(self.params):
                raise RuntimeError("Wrong number of arguments")
            for param, value in zip(self.params, args):
                setattr(cls_self, param, value)
            vars(cls_self).update(kw)
        cls.__init__ = init
        return cls
    

    This version has a few improvements

    def __call__(self, cls):
        def init(cls_self, *args, **kw):
            for param, value in zip(self.params, args):
                if param in kw:
                    raise TypeError("Multiple values for %s"%param)
                kw[param]=value
            if len(args) > len(self.params) or set(kw) != set(self.params):
                raise TypeError("Wrong number of arguments")
            vars(cls_self).update(kw)
        cls.__init__ = init
        return cls
    

    This version also tells you about unexpected keyword args

    def __call__(self, cls):
        def init(cls_self, *args, **kw):
            for param, value in zip(self.params, args):
                if param in kw:
                    raise TypeError("Multiple values for %s"%param)
                kw[param]=value
            unexpected_args = list(set(kw)-set(self.params))
            if unexpected_args:
                raise TypeError("Unexpected args %s"%unexpected_args)
            missing_args = list(set(self.params)-set(kw))
            if missing_args:
                raise TypeError("Expected args %s"%missing_args)
            vars(cls_self).update(kw)
        cls.__init__ = init
        return cls
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Question is already been asked in title. Here is a code: (function($){ var filter
I know this sort of question has been asked before , but I still
As a learning project I'm attempting to re-create the procedurally generated hills from Tiny
Sorry for the rather subjective question, but I was hoping to get an opinion
This may seem like a dumb question, but still I don't know the answer.
This is a very standard newbie question, but I am looking for an expert
I have asked a related question , but I did not get a satisfactory
I'm developing a procedurally-generated game world in Python. The structure of the world will
Earlier today I asked this question which arose from A- My poor planning and
Not sure if I phrased the question correctly but let me explain. In a

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.