Showing API changes with a warning

When we change the API for one of our modules, packages, or classes, we can provide a handy marker via the warnings module. This will raise a warning in the method that is deprecated or is pending deprecation, as follows:

import warnings


class Player:
"""version 2.1"""

def bet(self) -> None:
warnings.warn(
"bet is deprecated, use place_bet",
DeprecationWarning, stacklevel=2)
pass

When we do this, any part of the application that uses Player.bet() will receive DeprecationWarning. By default, this warning is silent. We can, however, adjust the warnings filter to see the message, as shown here:

>>> warnings.simplefilter("always", category=DeprecationWarning) 
>>> p2 = Player()
>>> p2.bet() __main__:4: DeprecationWarning: bet is deprecated, use
place_bet

This technique allows us to locate all of the places where our application must change because of an API change. If we have unit test cases with close to 100 percent code coverage, this simple technique is likely to reveal all the uses of deprecated methods.

Some integrated development environments (IDEs) can spot the use of warnings and highlight the deprecated code. PyCharm, for example, will draw a small line through any use of the deprecated bet() method.

Because this is so valuable for planning and managing software changes, we have the following three ways to make the warnings visible in our applications:

  • The command-line -Wd option will set the action to default for all warnings. This will enable the normally silent deprecation warnings. When we run python3.7 -Wd, we'll see all the deprecation warnings.
  • Using unittest, which always executes in the warnings.simplefilter('default') mode.
  • Including warnings.simplefilter('default') in our application program. This will also apply the default action to all warnings; it's equivalent to the -Wd command-line option.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset