On 6/12/2015 7:12 AM, Thomas Güttler wrote:
Here is a snippet from the argparse module:

{{{
     def parse_known_args(self, args=None, namespace=None):
         ...
         # default Namespace built from parser defaults
         if namespace is None:
             namespace = Namespace() # < ======= my issue
}}}

I subclass from the class of the above snippet.

I would like to use a different Namespace class.

if the above could would use

     namespace = self.Namespace()

it would be very easy for me to inject a different Namespace class.

The default arg (None) for the namespace parameter of the parse_known_args is an attribute of the function, not of the class or instance thereof. Unless the default Namespace is used elsewhere, this seems sensible.

In CPython, at least, and probably in pypy, you can change this attribute. (But AFAIK, this is not guaranteed in all implementations.)

>>> def f(n = 1): pass

>>> f.__defaults__
(1,)
>>> f.__defaults__ = (2,)
>>> f.__defaults__
(2,)

So the following works

>>> class C():
        def f(n=1): print(n)
        
>>> class D(C):
        C.f.__defaults__ = (2,)
        
>>> D.f()
2

Of course, this may or may not do more than you want.

>>> C.f()
2

--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to