We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TypeError: Subscripted generics cannot be used with class and instance checks under python 3.9.0b1
#### Problem Description
Running mitmproxy 5.1.1 under python 3.9.0b1 fails with `TypeError: Subscripted generics cannot be used with class and instance checks`. The test suite fails as well with hundreds of ERROR and FAILED tests.

#### Steps to reproduce the behavior:
1. install mitmproxy 5.1.1 on Fedora rawhide
2. mitmproxy
3. pytest -v

There are:
```
=================== 303 failed, 994 passed, 2 xfailed, 115 warnings, 182 errors in 72.86s (0:01:12) ====================
```
Most of them throw a `TypeError: Subscripted generics cannot be used with class and instance checks` and have a stack trace similar to:
```
___________________________________ ERROR at setup of TestHTTPS.test_clientcert_dir ____________________________________

cls = <class 'test.mitmproxy.proxy.test_server.TestHTTPS'>

    @classmethod
    def setup_class(cls):
        cls.server = pathod.test.Daemon(
            ssl=cls.ssl,
            ssloptions=cls.ssloptions)
        cls.server2 = pathod.test.Daemon(
            ssl=cls.ssl,
            ssloptions=cls.ssloptions)
    
>       cls.options = cls.get_options()

test/mitmproxy/tservers.py:146: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
test/mitmproxy/tservers.py:179: in get_options
    return options.Options(
mitmproxy/options.py:50: in __init__
    self.add_option(
mitmproxy/optmanager.py:109: in add_option
    self._options[name] = _Option(name, typespec, default, help, choices)
mitmproxy/optmanager.py:34: in __init__
    typecheck.check_option_type(name, default, typespec)
mitmproxy/utils/typecheck.py:73: in check_option_type
    elif not isinstance(value, typeinfo):
/usr/lib64/python3.9/typing.py:649: in __instancecheck__
    return self.__subclasscheck__(type(obj))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = typing.Optional[str], cls = <class 'NoneType'>

    def __subclasscheck__(self, cls):
>       raise TypeError("Subscripted generics cannot be used with"
                        " class and instance checks")
E       TypeError: Subscripted generics cannot be used with class and instance checks

/usr/lib64/python3.9/typing.py:652: TypeError
```

#### System Information
```
Traceback (most recent call last):
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/bin/./mitmproxy", line 11, in <module>
    load_entry_point('mitmproxy==5.1.1', 'console_scripts', 'mitmproxy')()
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py", line 147, in mitmproxy
    run(console.master.ConsoleMaster, cmdline.mitmproxy, args)
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py", line 71, in run
    opts = options.Options()
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/options.py", line 50, in __init__
    self.add_option(
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py", line 109, in add_option
    self._options[name] = _Option(name, typespec, default, help, choices)
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py", line 34, in __init__
    typecheck.check_option_type(name, default, typespec)
  File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/utils/typecheck.py", line 73, in check_option_type
    elif not isinstance(value, typeinfo):
  File "/usr/lib64/python3.9/typing.py", line 649, in __instancecheck__
    return self.__subclasscheck__(type(obj))
  File "/usr/lib64/python3.9/typing.py", line 652, in __subclasscheck__
    raise TypeError("Subscripted generics cannot be used with"
TypeError: Subscripted generics cannot be used with class and instance checks
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mitmproxy/utils/typecheck.py`
Content:
```
1 import typing
2 
3 Type = typing.Union[
4     typing.Any  # anything more elaborate really fails with mypy at the moment.
5 ]
6 
7 
8 def sequence_type(typeinfo: typing.Type[typing.List]) -> Type:
9     """Return the type of a sequence, e.g. typing.List"""
10     return typeinfo.__args__[0]  # type: ignore
11 
12 
13 def tuple_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:
14     """Return the types of a typing.Tuple"""
15     return typeinfo.__args__  # type: ignore
16 
17 
18 def union_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:
19     """return the types of a typing.Union"""
20     return typeinfo.__args__  # type: ignore
21 
22 
23 def mapping_types(typeinfo: typing.Type[typing.Mapping]) -> typing.Tuple[Type, Type]:
24     """return the types of a mapping, e.g. typing.Dict"""
25     return typeinfo.__args__  # type: ignore
26 
27 
28 def check_option_type(name: str, value: typing.Any, typeinfo: Type) -> None:
29     """
30     Check if the provided value is an instance of typeinfo and raises a
31     TypeError otherwise. This function supports only those types required for
32     options.
33     """
34     e = TypeError("Expected {} for {}, but got {}.".format(
35         typeinfo,
36         name,
37         type(value)
38     ))
39 
40     typename = str(typeinfo)
41 
42     if typename.startswith("typing.Union"):
43         for T in union_types(typeinfo):
44             try:
45                 check_option_type(name, value, T)
46             except TypeError:
47                 pass
48             else:
49                 return
50         raise e
51     elif typename.startswith("typing.Tuple"):
52         types = tuple_types(typeinfo)
53         if not isinstance(value, (tuple, list)):
54             raise e
55         if len(types) != len(value):
56             raise e
57         for i, (x, T) in enumerate(zip(value, types)):
58             check_option_type("{}[{}]".format(name, i), x, T)
59         return
60     elif typename.startswith("typing.Sequence"):
61         T = sequence_type(typeinfo)
62         if not isinstance(value, (tuple, list)):
63             raise e
64         for v in value:
65             check_option_type(name, v, T)
66     elif typename.startswith("typing.IO"):
67         if hasattr(value, "read"):
68             return
69         else:
70             raise e
71     elif typename.startswith("typing.Any"):
72         return
73     elif not isinstance(value, typeinfo):
74         if typeinfo is float and isinstance(value, int):
75             return
76         raise e
77 
78 
79 def typespec_to_str(typespec: typing.Any) -> str:
80     if typespec in (str, int, bool):
81         t = typespec.__name__
82     elif typespec == typing.Optional[str]:
83         t = 'optional str'
84     elif typespec == typing.Sequence[str]:
85         t = 'sequence of str'
86     elif typespec == typing.Optional[int]:
87         t = 'optional int'
88     else:
89         raise NotImplementedError
90     return t
91
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mitmproxy/utils/typecheck.py b/mitmproxy/utils/typecheck.py
--- a/mitmproxy/utils/typecheck.py
+++ b/mitmproxy/utils/typecheck.py
@@ -39,7 +39,7 @@
 
     typename = str(typeinfo)
 
-    if typename.startswith("typing.Union"):
+    if typename.startswith("typing.Union") or typename.startswith("typing.Optional"):
         for T in union_types(typeinfo):
             try:
                 check_option_type(name, value, T)

{"golden_diff": "diff --git a/mitmproxy/utils/typecheck.py b/mitmproxy/utils/typecheck.py\n--- a/mitmproxy/utils/typecheck.py\n+++ b/mitmproxy/utils/typecheck.py\n@@ -39,7 +39,7 @@\n \n     typename = str(typeinfo)\n \n-    if typename.startswith(\"typing.Union\"):\n+    if typename.startswith(\"typing.Union\") or typename.startswith(\"typing.Optional\"):\n         for T in union_types(typeinfo):\n             try:\n                 check_option_type(name, value, T)\n", "issue": "TypeError: Subscripted generics cannot be used with class and instance checks under python 3.9.0b1\n#### Problem Description\r\nRunning mitmproxy 5.1.1 under python 3.9.0b1 fails with `TypeError: Subscripted generics cannot be used with class and instance checks`. The test suite fails as well with hundreds of ERROR and FAILED tests.\r\n\r\n#### Steps to reproduce the behavior:\r\n1. install mitmproxy 5.1.1 on Fedora rawhide\r\n2. mitmproxy\r\n3. pytest -v\r\n\r\nThere are:\r\n```\r\n=================== 303 failed, 994 passed, 2 xfailed, 115 warnings, 182 errors in 72.86s (0:01:12) ====================\r\n```\r\nMost of them throw a `TypeError: Subscripted generics cannot be used with class and instance checks` and have a stack trace similar to:\r\n```\r\n___________________________________ ERROR at setup of TestHTTPS.test_clientcert_dir ____________________________________\r\n\r\ncls = <class 'test.mitmproxy.proxy.test_server.TestHTTPS'>\r\n\r\n    @classmethod\r\n    def setup_class(cls):\r\n        cls.server = pathod.test.Daemon(\r\n            ssl=cls.ssl,\r\n            ssloptions=cls.ssloptions)\r\n        cls.server2 = pathod.test.Daemon(\r\n            ssl=cls.ssl,\r\n            ssloptions=cls.ssloptions)\r\n    \r\n>       cls.options = cls.get_options()\r\n\r\ntest/mitmproxy/tservers.py:146: \r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\ntest/mitmproxy/tservers.py:179: in get_options\r\n    return options.Options(\r\nmitmproxy/options.py:50: in __init__\r\n    self.add_option(\r\nmitmproxy/optmanager.py:109: in add_option\r\n    self._options[name] = _Option(name, typespec, default, help, choices)\r\nmitmproxy/optmanager.py:34: in __init__\r\n    typecheck.check_option_type(name, default, typespec)\r\nmitmproxy/utils/typecheck.py:73: in check_option_type\r\n    elif not isinstance(value, typeinfo):\r\n/usr/lib64/python3.9/typing.py:649: in __instancecheck__\r\n    return self.__subclasscheck__(type(obj))\r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n\r\nself = typing.Optional[str], cls = <class 'NoneType'>\r\n\r\n    def __subclasscheck__(self, cls):\r\n>       raise TypeError(\"Subscripted generics cannot be used with\"\r\n                        \" class and instance checks\")\r\nE       TypeError: Subscripted generics cannot be used with class and instance checks\r\n\r\n/usr/lib64/python3.9/typing.py:652: TypeError\r\n```\r\n\r\n#### System Information\r\n```\r\nTraceback (most recent call last):\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/bin/./mitmproxy\", line 11, in <module>\r\n    load_entry_point('mitmproxy==5.1.1', 'console_scripts', 'mitmproxy')()\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py\", line 147, in mitmproxy\r\n    run(console.master.ConsoleMaster, cmdline.mitmproxy, args)\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py\", line 71, in run\r\n    opts = options.Options()\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/options.py\", line 50, in __init__\r\n    self.add_option(\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py\", line 109, in add_option\r\n    self._options[name] = _Option(name, typespec, default, help, choices)\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py\", line 34, in __init__\r\n    typecheck.check_option_type(name, default, typespec)\r\n  File \"/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/utils/typecheck.py\", line 73, in check_option_type\r\n    elif not isinstance(value, typeinfo):\r\n  File \"/usr/lib64/python3.9/typing.py\", line 649, in __instancecheck__\r\n    return self.__subclasscheck__(type(obj))\r\n  File \"/usr/lib64/python3.9/typing.py\", line 652, in __subclasscheck__\r\n    raise TypeError(\"Subscripted generics cannot be used with\"\r\nTypeError: Subscripted generics cannot be used with class and instance checks\r\n```\n", "before_files": [{"content": "import typing\n\nType = typing.Union[\n    typing.Any  # anything more elaborate really fails with mypy at the moment.\n]\n\n\ndef sequence_type(typeinfo: typing.Type[typing.List]) -> Type:\n    \"\"\"Return the type of a sequence, e.g. typing.List\"\"\"\n    return typeinfo.__args__[0]  # type: ignore\n\n\ndef tuple_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:\n    \"\"\"Return the types of a typing.Tuple\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef union_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:\n    \"\"\"return the types of a typing.Union\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef mapping_types(typeinfo: typing.Type[typing.Mapping]) -> typing.Tuple[Type, Type]:\n    \"\"\"return the types of a mapping, e.g. typing.Dict\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef check_option_type(name: str, value: typing.Any, typeinfo: Type) -> None:\n    \"\"\"\n    Check if the provided value is an instance of typeinfo and raises a\n    TypeError otherwise. This function supports only those types required for\n    options.\n    \"\"\"\n    e = TypeError(\"Expected {} for {}, but got {}.\".format(\n        typeinfo,\n        name,\n        type(value)\n    ))\n\n    typename = str(typeinfo)\n\n    if typename.startswith(\"typing.Union\"):\n        for T in union_types(typeinfo):\n            try:\n                check_option_type(name, value, T)\n            except TypeError:\n                pass\n            else:\n                return\n        raise e\n    elif typename.startswith(\"typing.Tuple\"):\n        types = tuple_types(typeinfo)\n        if not isinstance(value, (tuple, list)):\n            raise e\n        if len(types) != len(value):\n            raise e\n        for i, (x, T) in enumerate(zip(value, types)):\n            check_option_type(\"{}[{}]\".format(name, i), x, T)\n        return\n    elif typename.startswith(\"typing.Sequence\"):\n        T = sequence_type(typeinfo)\n        if not isinstance(value, (tuple, list)):\n            raise e\n        for v in value:\n            check_option_type(name, v, T)\n    elif typename.startswith(\"typing.IO\"):\n        if hasattr(value, \"read\"):\n            return\n        else:\n            raise e\n    elif typename.startswith(\"typing.Any\"):\n        return\n    elif not isinstance(value, typeinfo):\n        if typeinfo is float and isinstance(value, int):\n            return\n        raise e\n\n\ndef typespec_to_str(typespec: typing.Any) -> str:\n    if typespec in (str, int, bool):\n        t = typespec.__name__\n    elif typespec == typing.Optional[str]:\n        t = 'optional str'\n    elif typespec == typing.Sequence[str]:\n        t = 'sequence of str'\n    elif typespec == typing.Optional[int]:\n        t = 'optional int'\n    else:\n        raise NotImplementedError\n    return t\n", "path": "mitmproxy/utils/typecheck.py"}], "after_files": [{"content": "import typing\n\nType = typing.Union[\n    typing.Any  # anything more elaborate really fails with mypy at the moment.\n]\n\n\ndef sequence_type(typeinfo: typing.Type[typing.List]) -> Type:\n    \"\"\"Return the type of a sequence, e.g. typing.List\"\"\"\n    return typeinfo.__args__[0]  # type: ignore\n\n\ndef tuple_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:\n    \"\"\"Return the types of a typing.Tuple\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef union_types(typeinfo: typing.Type[typing.Tuple]) -> typing.Sequence[Type]:\n    \"\"\"return the types of a typing.Union\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef mapping_types(typeinfo: typing.Type[typing.Mapping]) -> typing.Tuple[Type, Type]:\n    \"\"\"return the types of a mapping, e.g. typing.Dict\"\"\"\n    return typeinfo.__args__  # type: ignore\n\n\ndef check_option_type(name: str, value: typing.Any, typeinfo: Type) -> None:\n    \"\"\"\n    Check if the provided value is an instance of typeinfo and raises a\n    TypeError otherwise. This function supports only those types required for\n    options.\n    \"\"\"\n    e = TypeError(\"Expected {} for {}, but got {}.\".format(\n        typeinfo,\n        name,\n        type(value)\n    ))\n\n    typename = str(typeinfo)\n\n    if typename.startswith(\"typing.Union\") or typename.startswith(\"typing.Optional\"):\n        for T in union_types(typeinfo):\n            try:\n                check_option_type(name, value, T)\n            except TypeError:\n                pass\n            else:\n                return\n        raise e\n    elif typename.startswith(\"typing.Tuple\"):\n        types = tuple_types(typeinfo)\n        if not isinstance(value, (tuple, list)):\n            raise e\n        if len(types) != len(value):\n            raise e\n        for i, (x, T) in enumerate(zip(value, types)):\n            check_option_type(\"{}[{}]\".format(name, i), x, T)\n        return\n    elif typename.startswith(\"typing.Sequence\"):\n        T = sequence_type(typeinfo)\n        if not isinstance(value, (tuple, list)):\n            raise e\n        for v in value:\n            check_option_type(name, v, T)\n    elif typename.startswith(\"typing.IO\"):\n        if hasattr(value, \"read\"):\n            return\n        else:\n            raise e\n    elif typename.startswith(\"typing.Any\"):\n        return\n    elif not isinstance(value, typeinfo):\n        if typeinfo is float and isinstance(value, int):\n            return\n        raise e\n\n\ndef typespec_to_str(typespec: typing.Any) -> str:\n    if typespec in (str, int, bool):\n        t = typespec.__name__\n    elif typespec == typing.Optional[str]:\n        t = 'optional str'\n    elif typespec == typing.Sequence[str]:\n        t = 'sequence of str'\n    elif typespec == typing.Optional[int]:\n        t = 'optional int'\n    else:\n        raise NotImplementedError\n    return t\n", "path": "mitmproxy/utils/typecheck.py"}]}