compass
compass

Reputation: 347

How to print the calling method name and line number for Deprecation Warning message in python?

My deprecate warning message is in a function. I would like to print out the module name and line number of the calling function so that I can easily locate them. Take open() for example:

/path/to/file/group.py:180: DeprecationWarning: 'U' mode is deprecated 
with open(tmpName, 'rU') as csvfile

However, my own warning prints like this:

/path/to/file/models.py:735: DeprecationWarning: Deprecated. Use course_id instead! 
warnings.warn("Deprecated. Use course_id instead!", DeprecationWarning)

On line 735 of models.py is where the warnings.warn() call is located. Is there a way to make the warning output the parent caller's name and line number? Thanks.

Upvotes: 2

Views: 823

Answers (1)

tsroten
tsroten

Reputation: 2764

You can control which caller you want the warning to apply to by using the stacklevel argument.

For instance, the following code:

import warnings

def hello(s):
    if isinstance(s, int):
        deprecation('Use of integers is deprecated.')
    else:
        print(s)

def deprecation(msg):
    warnings.warn(msg, DeprecationWarning, stacklevel=3)

hello(1)

Will give the following warning:

warning_test.py:12: DeprecationWarning: Use of integers is deprecated.
  hello(1)

See: Python documentation on warnings.warn

Upvotes: 1

Related Questions