File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+
3
+ '''Item 3 from Effective Python'''
4
+
5
+ import logging
6
+ from pprint import pprint
7
+ from sys import stdout as STDOUT
8
+
9
+
10
+ # Example 1
11
+ def to_str (bytes_or_str ):
12
+ '''In Python 3, you’ll need one method that takes a str or bytes and
13
+ always returns a str .'''
14
+ if isinstance (bytes_or_str , bytes ):
15
+ value = bytes_or_str .decode ('utf-8' )
16
+ else :
17
+ value = bytes_or_str
18
+ return value # Instance of str
19
+
20
+ print (repr (to_str (b'foo' )))
21
+ print (repr (to_str ('foo' )))
22
+
23
+
24
+ # Example 2
25
+ def to_bytes (bytes_or_str ):
26
+ '''You’ll need another method that takes a str or bytes and always
27
+ returns a bytes .'''
28
+ if isinstance (bytes_or_str , str ):
29
+ value = bytes_or_str .encode ('utf-8' )
30
+ else :
31
+ value = bytes_or_str
32
+ return value # Instance of bytes
33
+
34
+ print (repr (to_bytes (b'foo' )))
35
+ print (repr (to_bytes ('foo' )))
36
+
37
+
38
+ # Example 5
39
+ try :
40
+ import os
41
+ with open ('random.bin' , 'wb' ) as f :
42
+ f .write (os .urandom (10 ))
43
+ except :
44
+ logging .exception ('Expected' )
45
+ else :
46
+ exit ()
47
+
48
+
49
+ # Example 6
50
+ with open ('random1.bin' , 'wb' ) as f :
51
+ f .write (os .urandom (10 ))
You can’t perform that action at this time.
0 commit comments