1import sys 2 3PY2 = sys.version_info[0] == 2 # type: bool 4 5if PY2: 6 from StringIO import StringIO # noqa 7else: 8 from io import StringIO # noqa 9 10 11def is_type_checking(): 12 # type: () -> bool 13 try: 14 from typing import TYPE_CHECKING 15 except ImportError: 16 return False 17 return TYPE_CHECKING 18 19 20IS_TYPE_CHECKING = is_type_checking() 21 22 23if IS_TYPE_CHECKING: 24 from typing import Text 25 26 27def to_env(text): 28 # type: (Text) -> str 29 """ 30 Encode a string the same way whether it comes from the environment or a `.env` file. 31 """ 32 if PY2: 33 return text.encode(sys.getfilesystemencoding() or "utf-8") 34 else: 35 return text 36 37 38def to_text(string): 39 # type: (str) -> Text 40 """ 41 Make a string Unicode if it isn't already. 42 43 This is useful for defining raw unicode strings because `ur"foo"` isn't valid in 44 Python 3. 45 """ 46 if PY2: 47 return string.decode("utf-8") 48 else: 49 return string 50