Skip to content

Commit 5d1e10d

Browse files
committed
Add example on ignoring warnings from the commnd line
1 parent 114a0f3 commit 5d1e10d

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

source-code/error-handling/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@ Illustrations of error handling.
88
ways ot handle errors.
99
1. `data.txt`: data file to use as input.
1010
1. `data_not_ok.txt`: incorrect data file to use as input.
11+
1. `warnings`: illustrations of using the `warmings` module
12+
for error handling.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Warnings
2+
3+
Python supports warnings and errors at runtime. This can provide
4+
a useful error handling mechanism for your code. You can use the
5+
`warnings` module to issue warnings and errors.
6+
7+
8+
## What is it?
9+
10+
1. `will_warn.py`: script that issues a DeprecationWarning, intended
11+
to illustrate how to suppress it at runtime.
12+
13+
14+
## How to use it?
15+
16+
You can suppress the warning from the command line in two ways:
17+
* using the `-W` option to the Python interpreter, and
18+
* setting the `PYTHONWARNINGS` environment variable.
19+
20+
```bash
21+
$ python -Wi::DeprecationWarning will_warn.py
22+
```
23+
24+
```bash
25+
$ export PYTHONWARNINGS="ignore::DeprecationWarning"
26+
$ python will_warn.py
27+
```
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python
2+
3+
import warnings
4+
5+
6+
class MyClass:
7+
8+
def __init__(self, value):
9+
self._value = value
10+
11+
@property
12+
def value(self):
13+
return self._value
14+
15+
def get_value(self):
16+
warnings.warn("get_value is deprecated. Use the value property",
17+
DeprecationWarning)
18+
return self._value
19+
20+
21+
if __name__ == '__main__':
22+
obj = MyClass(42)
23+
print(obj.get_value())
24+
print(obj.value)

0 commit comments

Comments
 (0)