Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Compatibility tools for differences between Python 2 and 3 

3""" 

4import sys 

5 

6PY37 = (sys.version_info[:2] == (3, 7)) 

7 

8asunicode = lambda x, _: str(x) # noqa:E731 

9 

10 

11def asbytes(s): 

12 if isinstance(s, bytes): 

13 return s 

14 return s.encode('latin1') 

15 

16 

17def asstr(s): 

18 if isinstance(s, str): 

19 return s 

20 return s.decode('latin1') 

21 

22 

23# list-producing versions of the major Python iterating functions 

24def lrange(*args, **kwargs): 

25 return list(range(*args, **kwargs)) 

26 

27 

28def lzip(*args, **kwargs): 

29 return list(zip(*args, **kwargs)) 

30 

31 

32def lmap(*args, **kwargs): 

33 return list(map(*args, **kwargs)) 

34 

35 

36def lfilter(*args, **kwargs): 

37 return list(filter(*args, **kwargs)) 

38 

39 

40def iteritems(obj, **kwargs): 

41 """replacement for six's iteritems for Python2/3 compat 

42 uses 'iteritems' if available and otherwise uses 'items'. 

43 

44 Passes kwargs to method. 

45 """ 

46 func = getattr(obj, "iteritems", None) 

47 if not func: 

48 func = obj.items 

49 return func(**kwargs) 

50 

51 

52def iterkeys(obj, **kwargs): 

53 func = getattr(obj, "iterkeys", None) 

54 if not func: 

55 func = obj.keys 

56 return func(**kwargs) 

57 

58 

59def itervalues(obj, **kwargs): 

60 func = getattr(obj, "itervalues", None) 

61 if not func: 

62 func = obj.values 

63 return func(**kwargs) 

64 

65 

66def with_metaclass(meta, *bases): 

67 """Create a base class with a metaclass.""" 

68 # This requires a bit of explanation: the basic idea is to make a dummy 

69 # metaclass for one level of class instantiation that replaces itself with 

70 # the actual metaclass. 

71 class metaclass(meta): 

72 def __new__(cls, name, this_bases, d): 

73 return meta(name, bases, d) 

74 return type.__new__(metaclass, 'temporary_class', (), {})