[compat] correct OptionGroup invocation for Python 3 (fixes #4243)
[youtube-dl] / youtube_dl / compat.py
index 3e35e2b84625cf55f41ee7a572417b54bca14478..adf81e7ab4f9bf8d3a8c5365d3c9f9c65b67c7da 100644 (file)
@@ -1,4 +1,7 @@
+from __future__ import unicode_literals
+
 import getpass
+import optparse
 import os
 import subprocess
 import sys
@@ -286,6 +289,36 @@ if sys.version_info < (3, 0) and sys.platform == 'win32':
 else:
     compat_getpass = getpass.getpass
 
+# Old 2.6 and 2.7 releases require kwargs to be bytes
+try:
+    (lambda x: x)(**{'x': 0})
+except TypeError:
+    def compat_kwargs(kwargs):
+        return dict((bytes(k), v) for k, v in kwargs.items())
+else:
+    compat_kwargs = lambda kwargs: kwargs
+
+
+# Fix https://github.com/rg3/youtube-dl/issues/4223
+# See http://bugs.python.org/issue9161 for what is broken
+def workaround_optparse_bug9161():
+    op = optparse.OptionParser()
+    og = optparse.OptionGroup(op, 'foo')
+    try:
+        og.add_option('-t')
+    except TypeError as te:
+        real_add_option = optparse.OptionGroup.add_option
+
+        def _compat_add_option(self, *args, **kwargs):
+            enc = lambda v: (
+                v.encode('ascii', 'replace') if isinstance(v, compat_str)
+                else v)
+            bargs = [enc(a) for a in args]
+            bkwargs = dict(
+                (k, enc(v)) for k, v in kwargs.items())
+            return real_add_option(self, *bargs, **bkwargs)
+        optparse.OptionGroup.add_option = _compat_add_option
+
 
 __all__ = [
     'compat_HTTPError',
@@ -297,6 +330,7 @@ __all__ = [
     'compat_html_entities',
     'compat_html_parser',
     'compat_http_client',
+    'compat_kwargs',
     'compat_ord',
     'compat_parse_qs',
     'compat_print',
@@ -312,4 +346,5 @@ __all__ = [
     'compat_xml_parse_error',
     'shlex_quote',
     'subprocess_check_output',
+    'workaround_optparse_bug9161',
 ]