Note that there are some explanatory texts on larger screens.

plurals
  1. POPython - Cleanest way to override __init__ where an optional kwarg must be used after the super() call?
    primarykey
    data
    text
    <p>I love how beautiful python looks/feels and I'm hoping this can be cleaner (readability is awesome).</p> <p>What's a clean way to accept an optional keyword argument when overriding a subclassed <strong>init</strong> where the optional <code>kwarg</code> has to be used <strong>after</strong> the <code>super()</code> call? </p> <p>I have a django form where I'd like to accept an optional user argument, but if I define it as one of the arguments <code>user=None</code>, then the usual form call <code>form({})</code> assumes the positional argument refers to the keyword argument <code>user</code>.</p> <p>Code speaks better than (my) words:</p> <pre><code>def __init__(self, *args, **kwargs): user = None if 'user' in kwargs: user = kwargs.pop('user') super(BaseCheckoutForm, self).__init__(*args, **kwargs) if user: self.prefill_from_user(user) </code></pre> <p>I can make this the cleanest by looking into the actual <code>Form</code> class to see what arguments it's looking for, but one of the greatest things about subclassing anything in python is collecting all <code>args</code> and <code>kwargs</code> and passing it into whatever you subclassed. Also this doesn't hold up to any changes in the source.</p> <pre><code>def __init__(self, querydict=None, user=None): super(BaseCheckoutForm, self).__init__(querydict) if user: self.prefill_from_user(user) </code></pre> <p>But unfortunately I have:</p> <pre><code> def __init__(self, *args, **kwargs): # cannot define user=None as an argument because normal usage # of class expects a certain order of positional args user = None if 'user' in kwargs: # must pop now since super()__init__ isn't expecting a user kwarg user = kwargs.pop('user') super(BaseCheckoutForm, self).__init__(*args, **kwargs) if user: self.prefill_from_user(user) </code></pre> <p>Thanks for any input!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload