Skip to content

Proposal: Default class #3045

Open
Open

Description

@jni

This is inspired by some of the answers in this SO question.

I recently needed to specify a default value to a parameter where None was a possible value that people might want to pass, and further it was the default value that needed deprecating, so our usual pathway of "set the default to None and then change it to a real value in the future" didn't work. I needed to distinguish between "default None" and "user-given None".

The top answers in SO suggested the following:

DEFAULT = object()

def myfunc(param=DEFAULT):
    if param is DEFAULT:
        warn(...)   # etc
    # etc

This works, but it'll be messy in the documentation:

>>> DEFAULT=object()
>>> str(DEFAULT)
'<object object at 0x11dfc3370>'

This whole thing has been turning in my head since then and I think that we can actually make a Default class that (a) prints the right thing to the docs, so that function introspection works, and (b) greatly simplifies our deprecation procedures for default value changes.

Here's the proposal in brief:

class Default:
    def __init__(self, value, next_value=None,
                 change_version=None, param_name=None):
        self.value = value
        self.next_value = next_value
        self.change_version = change_version
        self.param_name = param_name
        if next_value is not None:
            self.message = (f'The default value of {param_name} will '
                            f'change to {next_value} in {change_version}.')
        else:
            self.message = ''

    def __str__(self):
        if self.next_value is None:
            return str(self.value)
        else:
            return (f'{self.value} ({self.next_value} after '
                    f'{self.change_version}')

    def __repr__(self):
        return (f'Default({repr(self.value)}, {repr(self.param_name}, '
                f'{repr(self.next_value)}, {repr(self.change_version)})')

    def warn(self):
        if self.next_value is not None:
            warn(self.message)

Use it like this. If we want to deprecate an argument default value from False to True, change:

def my_func(my_deprecated_arg=False):

to:

def my_func(my_deprecated_arg=Default(False, True, 'v0.16',
                                      'my_deprecated_arg')):
    if type(my_deprecated_arg) == Default:
        my_deprecated_arg.warn()

And that's it! No docstrings to update, with default information that may become stale, no inconsistent deprecation messages to write, and the docs write themselves. In fact, with the right Regex in the release docs, we don't even need to add an item to the to-do: the release manager can just search for Default...v0.whatever.

@scikit-image/core, if you like this pattern, 👍 and I'll write the PR. If not, then fire up the comments and we'll see if it is salvageable. =)

Activity

  1. soupault commented on May 6, 2018

    @soupault
    Member

    @jni Thank you for the detailed explanation!
    I like the proposal a lot, especially the part related to the maintenance of the docstrings.
    One question: do you think it makes sense to add also old_param_name argument to the Default class? This would help to keep the unified approach not only when we change the default values, but also in case of parameter renaming.

  2. jni commented on May 8, 2018

    @jni
    MemberAuthor

    @soupault yes, that makes a lot of sense! That would mean that the as_grey PR could use this class also. =)

  3. sciunto commented on May 8, 2018

    @sciunto
    Member

    this seems to be really helpful. I'm +1. :)

  4. stefanv commented on May 8, 2018

    @stefanv
    Member

    W.r.t. None not being available as a default value, you can use ... in those cases.

    This looks useful for deprecation, although I'd prefer an API that guided the user in its reading:

    def my_func(my_deprecated_arg=Default(False, will_be=True, starting='v0.16')):
    

    Then, how about adding a decorator, say warn_defaults, that uses inspect to automatically do what you suggest above? Another option is to only use such a decorator:

    @default('my_deprecated_arg', False, will_be=True, starting='v0.16')
    def my_func(image, my_deprecated_arg=...):
        pass
    
  5. hmaarrfk commented on Aug 7, 2018

    @hmaarrfk
    Member

    So I was thinking about this deprecation problem and got prettty far into making a deprecation decoration:

    commit showing a few examples:
    hmaarrfk@bde84f9
    Main file:
    https://github.com/hmaarrfk/scikit-image/blob/deprecations/skimage/_shared/deprecations.py

    It uses a decorator, introspection, and docstring rewriting to actually detect if the user passed in the argument. If they did, then it doesn't issue any warnings. If they didn't it issues a FutureWarning.

    It also writes the docstring message and the deprecation warning for you and points the user to their line of code that they should fix.

        If the software version is greater or equal to that of ``version``, this
        decorator returns the original function without any modifications.
        It will warn the user, pointing to the line of his code, in a single
        warning for all changes in the default parameters.
        This decorator does the following:
            - Adds a human readable message whenever the function is invoked
              without specifying the deprecated keyword argument.
            - It modifies the ``__signature__`` of the function so that signature
              reflects the current default parameters.
            - Modifies the docstring so as to include a warning about the
              deprecation information compatible numpydoc.
    

    I was going to put this in a little BSD package and show it to scikit-image and ask for help developing features.

    One other advantage of this kind of decorator is that the git commit history would be cleaned up quite a bit. The decorators can even be left in, and if they are, they only slow down loading time, and not execution time.

    We can play around with other decorators and kwargs introspection to basically get whatever behaviour we want (man python can do crazy things).

    A few other deprecation decorators I can think of:

    • args -> kw only deprecation
    • parameter renaming (as mentionned by @soupault)
    • coordinate swapping ;) @jni
  6. soupault commented on Aug 7, 2018

    @soupault
    Member

    @hmaarrfk Interesting results! Does your approach support deprecation of multiple function parameters, though?

  7. tacaswell commented on Aug 8, 2018

    @tacaswell
    Contributor

    @Carreau was working on a set of deprecation decorators / tools a while ago (but I am not sure what come of it).

    Matplotlib has some wrappers / helpers for handling deprecation as well https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/cbook/deprecation.py

  8. Carreau commented on Aug 8, 2018

    @Carreau
    Contributor

    @Carreau was working on a set of deprecation decorators / tools a while ago (but I am not sure what come of it).

    Ouch that's been a while, haven't moved much on that since last time. That would be useful, while many cases would not be covered. what if you want to remove an arg?

    There is also a risk as always to introduce a default mutable argument , which is not the case with object():

    In [1]: a = object()
       ...: a.b = 1
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-1-6bce53b7539a> in <module>
          1 a = object()
    ----> 2 a.b = 1
    
    AttributeError: 'object' object has no attribute 'b'
    
    In [2]:
    
    In [2]: class Default:pass
       ...: d = Default()
       ...: d.b = 1
    

    I actually have own undefined on PyPI, that basically try to avoid as much as possible to prevent any operation on it beyond printing it and testing identity. That forces handeling of undefined value in the body of functions.

  9. tacaswell commented on Aug 8, 2018

    @tacaswell
    Contributor

    @Carreau The danger of doing too many cool things!

  10. hmaarrfk commented on Aug 10, 2018

    @hmaarrfk
    Member

    @jni Here is the package with the first decorator, it allows you to deprecate things, and should handle the case the new default value is None

    https://github.com/hmaarrfk/deprecation_factory

    It hopefully should be up on conda-forge too:
    conda-forge/staged-recipes#6444

  11. locked and limited conversation to collaborators on Oct 18, 2021
  12. unlocked this conversation on Mar 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions