We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] Inspecting a NamedTuple defined int the REPL throws an error
I suspect this is not exclusive to NamedTuples

<img width="1452" alt="Screenshot 2022-03-07 at 15 08 46" src="https://user-images.githubusercontent.com/554369/157060930-7e517028-f587-4c48-906a-a807108a1687.png">



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rich/_inspect.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import inspect
4 from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
5 from typing import Any, Iterable, Optional, Tuple
6 
7 from .console import Group, RenderableType
8 from .highlighter import ReprHighlighter
9 from .jupyter import JupyterMixin
10 from .panel import Panel
11 from .pretty import Pretty
12 from .table import Table
13 from .text import Text, TextType
14 
15 
16 def _first_paragraph(doc: str) -> str:
17     """Get the first paragraph from a docstring."""
18     paragraph, _, _ = doc.partition("\n\n")
19     return paragraph
20 
21 
22 def _reformat_doc(doc: str) -> str:
23     """Reformat docstring."""
24     doc = cleandoc(doc).strip()
25     return doc
26 
27 
28 class Inspect(JupyterMixin):
29     """A renderable to inspect any Python Object.
30 
31     Args:
32         obj (Any): An object to inspect.
33         title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
34         help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
35         methods (bool, optional): Enable inspection of callables. Defaults to False.
36         docs (bool, optional): Also render doc strings. Defaults to True.
37         private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
38         dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
39         sort (bool, optional): Sort attributes alphabetically. Defaults to True.
40         all (bool, optional): Show all attributes. Defaults to False.
41         value (bool, optional): Pretty print value of object. Defaults to True.
42     """
43 
44     def __init__(
45         self,
46         obj: Any,
47         *,
48         title: Optional[TextType] = None,
49         help: bool = False,
50         methods: bool = False,
51         docs: bool = True,
52         private: bool = False,
53         dunder: bool = False,
54         sort: bool = True,
55         all: bool = True,
56         value: bool = True,
57     ) -> None:
58         self.highlighter = ReprHighlighter()
59         self.obj = obj
60         self.title = title or self._make_title(obj)
61         if all:
62             methods = private = dunder = True
63         self.help = help
64         self.methods = methods
65         self.docs = docs or help
66         self.private = private or dunder
67         self.dunder = dunder
68         self.sort = sort
69         self.value = value
70 
71     def _make_title(self, obj: Any) -> Text:
72         """Make a default title."""
73         title_str = (
74             str(obj)
75             if (isclass(obj) or callable(obj) or ismodule(obj))
76             else str(type(obj))
77         )
78         title_text = self.highlighter(title_str)
79         return title_text
80 
81     def __rich__(self) -> Panel:
82         return Panel.fit(
83             Group(*self._render()),
84             title=self.title,
85             border_style="scope.border",
86             padding=(0, 1),
87         )
88 
89     def _get_signature(self, name: str, obj: Any) -> Optional[Text]:
90         """Get a signature for a callable."""
91         try:
92             _signature = str(signature(obj)) + ":"
93         except ValueError:
94             _signature = "(...)"
95         except TypeError:
96             return None
97 
98         source_filename: Optional[str] = None
99         try:
100             source_filename = getfile(obj)
101         except TypeError:
102             pass
103 
104         callable_name = Text(name, style="inspect.callable")
105         if source_filename:
106             callable_name.stylize(f"link file://{source_filename}")
107         signature_text = self.highlighter(_signature)
108 
109         qualname = name or getattr(obj, "__qualname__", name)
110 
111         # If obj is a module, there may be classes (which are callable) to display
112         if inspect.isclass(obj):
113             prefix = "class"
114         else:
115             prefix = "def"
116 
117         qual_signature = Text.assemble(
118             (f"{prefix} ", f"inspect.{prefix}"),
119             (qualname, "inspect.callable"),
120             signature_text,
121         )
122 
123         return qual_signature
124 
125     def _render(self) -> Iterable[RenderableType]:
126         """Render object."""
127 
128         def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
129             key, (_error, value) = item
130             return (callable(value), key.strip("_").lower())
131 
132         def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
133             """Get attribute or any exception."""
134             try:
135                 return (None, getattr(obj, attr_name))
136             except Exception as error:
137                 return (error, None)
138 
139         obj = self.obj
140         keys = dir(obj)
141         total_items = len(keys)
142         if not self.dunder:
143             keys = [key for key in keys if not key.startswith("__")]
144         if not self.private:
145             keys = [key for key in keys if not key.startswith("_")]
146         not_shown_count = total_items - len(keys)
147         items = [(key, safe_getattr(key)) for key in keys]
148         if self.sort:
149             items.sort(key=sort_items)
150 
151         items_table = Table.grid(padding=(0, 1), expand=False)
152         items_table.add_column(justify="right")
153         add_row = items_table.add_row
154         highlighter = self.highlighter
155 
156         if callable(obj):
157             signature = self._get_signature("", obj)
158             if signature is not None:
159                 yield signature
160                 yield ""
161 
162         if self.docs:
163             _doc = getdoc(obj)
164             if _doc is not None:
165                 if not self.help:
166                     _doc = _first_paragraph(_doc)
167                 doc_text = Text(_reformat_doc(_doc), style="inspect.help")
168                 doc_text = highlighter(doc_text)
169                 yield doc_text
170                 yield ""
171 
172         if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):
173             yield Panel(
174                 Pretty(obj, indent_guides=True, max_length=10, max_string=60),
175                 border_style="inspect.value.border",
176             )
177             yield ""
178 
179         for key, (error, value) in items:
180             key_text = Text.assemble(
181                 (
182                     key,
183                     "inspect.attr.dunder" if key.startswith("__") else "inspect.attr",
184                 ),
185                 (" =", "inspect.equals"),
186             )
187             if error is not None:
188                 warning = key_text.copy()
189                 warning.stylize("inspect.error")
190                 add_row(warning, highlighter(repr(error)))
191                 continue
192 
193             if callable(value):
194                 if not self.methods:
195                     continue
196 
197                 _signature_text = self._get_signature(key, value)
198                 if _signature_text is None:
199                     add_row(key_text, Pretty(value, highlighter=highlighter))
200                 else:
201                     if self.docs:
202                         docs = getdoc(value)
203                         if docs is not None:
204                             _doc = _reformat_doc(str(docs))
205                             if not self.help:
206                                 _doc = _first_paragraph(_doc)
207                             _signature_text.append("\n" if "\n" in _doc else " ")
208                             doc = highlighter(_doc)
209                             doc.stylize("inspect.doc")
210                             _signature_text.append(doc)
211 
212                     add_row(key_text, _signature_text)
213             else:
214                 add_row(key_text, Pretty(value, highlighter=highlighter))
215         if items_table.row_count:
216             yield items_table
217         elif not_shown_count:
218             yield Text.from_markup(
219                 f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] "
220                 f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options."
221             )
222
```
--- 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/rich/_inspect.py b/rich/_inspect.py
--- a/rich/_inspect.py
+++ b/rich/_inspect.py
@@ -98,7 +98,8 @@
         source_filename: Optional[str] = None
         try:
             source_filename = getfile(obj)
-        except TypeError:
+        except (OSError, TypeError):
+            # OSError is raised if obj has no source file, e.g. when defined in REPL.
             pass
 
         callable_name = Text(name, style="inspect.callable")

{"golden_diff": "diff --git a/rich/_inspect.py b/rich/_inspect.py\n--- a/rich/_inspect.py\n+++ b/rich/_inspect.py\n@@ -98,7 +98,8 @@\n         source_filename: Optional[str] = None\n         try:\n             source_filename = getfile(obj)\n-        except TypeError:\n+        except (OSError, TypeError):\n+            # OSError is raised if obj has no source file, e.g. when defined in REPL.\n             pass\n \n         callable_name = Text(name, style=\"inspect.callable\")\n", "issue": "[BUG] Inspecting a NamedTuple defined int the REPL throws an error\nI suspect this is not exclusive to NamedTuples\r\n\r\n<img width=\"1452\" alt=\"Screenshot 2022-03-07 at 15 08 46\" src=\"https://user-images.githubusercontent.com/554369/157060930-7e517028-f587-4c48-906a-a807108a1687.png\">\r\n\r\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport inspect\nfrom inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature\nfrom typing import Any, Iterable, Optional, Tuple\n\nfrom .console import Group, RenderableType\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\n\ndef _first_paragraph(doc: str) -> str:\n    \"\"\"Get the first paragraph from a docstring.\"\"\"\n    paragraph, _, _ = doc.partition(\"\\n\\n\")\n    return paragraph\n\n\ndef _reformat_doc(doc: str) -> str:\n    \"\"\"Reformat docstring.\"\"\"\n    doc = cleandoc(doc).strip()\n    return doc\n\n\nclass Inspect(JupyterMixin):\n    \"\"\"A renderable to inspect any Python Object.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value of object. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        obj: Any,\n        *,\n        title: Optional[TextType] = None,\n        help: bool = False,\n        methods: bool = False,\n        docs: bool = True,\n        private: bool = False,\n        dunder: bool = False,\n        sort: bool = True,\n        all: bool = True,\n        value: bool = True,\n    ) -> None:\n        self.highlighter = ReprHighlighter()\n        self.obj = obj\n        self.title = title or self._make_title(obj)\n        if all:\n            methods = private = dunder = True\n        self.help = help\n        self.methods = methods\n        self.docs = docs or help\n        self.private = private or dunder\n        self.dunder = dunder\n        self.sort = sort\n        self.value = value\n\n    def _make_title(self, obj: Any) -> Text:\n        \"\"\"Make a default title.\"\"\"\n        title_str = (\n            str(obj)\n            if (isclass(obj) or callable(obj) or ismodule(obj))\n            else str(type(obj))\n        )\n        title_text = self.highlighter(title_str)\n        return title_text\n\n    def __rich__(self) -> Panel:\n        return Panel.fit(\n            Group(*self._render()),\n            title=self.title,\n            border_style=\"scope.border\",\n            padding=(0, 1),\n        )\n\n    def _get_signature(self, name: str, obj: Any) -> Optional[Text]:\n        \"\"\"Get a signature for a callable.\"\"\"\n        try:\n            _signature = str(signature(obj)) + \":\"\n        except ValueError:\n            _signature = \"(...)\"\n        except TypeError:\n            return None\n\n        source_filename: Optional[str] = None\n        try:\n            source_filename = getfile(obj)\n        except TypeError:\n            pass\n\n        callable_name = Text(name, style=\"inspect.callable\")\n        if source_filename:\n            callable_name.stylize(f\"link file://{source_filename}\")\n        signature_text = self.highlighter(_signature)\n\n        qualname = name or getattr(obj, \"__qualname__\", name)\n\n        # If obj is a module, there may be classes (which are callable) to display\n        if inspect.isclass(obj):\n            prefix = \"class\"\n        else:\n            prefix = \"def\"\n\n        qual_signature = Text.assemble(\n            (f\"{prefix} \", f\"inspect.{prefix}\"),\n            (qualname, \"inspect.callable\"),\n            signature_text,\n        )\n\n        return qual_signature\n\n    def _render(self) -> Iterable[RenderableType]:\n        \"\"\"Render object.\"\"\"\n\n        def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n            key, (_error, value) = item\n            return (callable(value), key.strip(\"_\").lower())\n\n        def safe_getattr(attr_name: str) -> Tuple[Any, Any]:\n            \"\"\"Get attribute or any exception.\"\"\"\n            try:\n                return (None, getattr(obj, attr_name))\n            except Exception as error:\n                return (error, None)\n\n        obj = self.obj\n        keys = dir(obj)\n        total_items = len(keys)\n        if not self.dunder:\n            keys = [key for key in keys if not key.startswith(\"__\")]\n        if not self.private:\n            keys = [key for key in keys if not key.startswith(\"_\")]\n        not_shown_count = total_items - len(keys)\n        items = [(key, safe_getattr(key)) for key in keys]\n        if self.sort:\n            items.sort(key=sort_items)\n\n        items_table = Table.grid(padding=(0, 1), expand=False)\n        items_table.add_column(justify=\"right\")\n        add_row = items_table.add_row\n        highlighter = self.highlighter\n\n        if callable(obj):\n            signature = self._get_signature(\"\", obj)\n            if signature is not None:\n                yield signature\n                yield \"\"\n\n        if self.docs:\n            _doc = getdoc(obj)\n            if _doc is not None:\n                if not self.help:\n                    _doc = _first_paragraph(_doc)\n                doc_text = Text(_reformat_doc(_doc), style=\"inspect.help\")\n                doc_text = highlighter(doc_text)\n                yield doc_text\n                yield \"\"\n\n        if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):\n            yield Panel(\n                Pretty(obj, indent_guides=True, max_length=10, max_string=60),\n                border_style=\"inspect.value.border\",\n            )\n            yield \"\"\n\n        for key, (error, value) in items:\n            key_text = Text.assemble(\n                (\n                    key,\n                    \"inspect.attr.dunder\" if key.startswith(\"__\") else \"inspect.attr\",\n                ),\n                (\" =\", \"inspect.equals\"),\n            )\n            if error is not None:\n                warning = key_text.copy()\n                warning.stylize(\"inspect.error\")\n                add_row(warning, highlighter(repr(error)))\n                continue\n\n            if callable(value):\n                if not self.methods:\n                    continue\n\n                _signature_text = self._get_signature(key, value)\n                if _signature_text is None:\n                    add_row(key_text, Pretty(value, highlighter=highlighter))\n                else:\n                    if self.docs:\n                        docs = getdoc(value)\n                        if docs is not None:\n                            _doc = _reformat_doc(str(docs))\n                            if not self.help:\n                                _doc = _first_paragraph(_doc)\n                            _signature_text.append(\"\\n\" if \"\\n\" in _doc else \" \")\n                            doc = highlighter(_doc)\n                            doc.stylize(\"inspect.doc\")\n                            _signature_text.append(doc)\n\n                    add_row(key_text, _signature_text)\n            else:\n                add_row(key_text, Pretty(value, highlighter=highlighter))\n        if items_table.row_count:\n            yield items_table\n        elif not_shown_count:\n            yield Text.from_markup(\n                f\"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] \"\n                f\"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options.\"\n            )\n", "path": "rich/_inspect.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport inspect\nfrom inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature\nfrom typing import Any, Iterable, Optional, Tuple\n\nfrom .console import Group, RenderableType\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\n\ndef _first_paragraph(doc: str) -> str:\n    \"\"\"Get the first paragraph from a docstring.\"\"\"\n    paragraph, _, _ = doc.partition(\"\\n\\n\")\n    return paragraph\n\n\ndef _reformat_doc(doc: str) -> str:\n    \"\"\"Reformat docstring.\"\"\"\n    doc = cleandoc(doc).strip()\n    return doc\n\n\nclass Inspect(JupyterMixin):\n    \"\"\"A renderable to inspect any Python Object.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value of object. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        obj: Any,\n        *,\n        title: Optional[TextType] = None,\n        help: bool = False,\n        methods: bool = False,\n        docs: bool = True,\n        private: bool = False,\n        dunder: bool = False,\n        sort: bool = True,\n        all: bool = True,\n        value: bool = True,\n    ) -> None:\n        self.highlighter = ReprHighlighter()\n        self.obj = obj\n        self.title = title or self._make_title(obj)\n        if all:\n            methods = private = dunder = True\n        self.help = help\n        self.methods = methods\n        self.docs = docs or help\n        self.private = private or dunder\n        self.dunder = dunder\n        self.sort = sort\n        self.value = value\n\n    def _make_title(self, obj: Any) -> Text:\n        \"\"\"Make a default title.\"\"\"\n        title_str = (\n            str(obj)\n            if (isclass(obj) or callable(obj) or ismodule(obj))\n            else str(type(obj))\n        )\n        title_text = self.highlighter(title_str)\n        return title_text\n\n    def __rich__(self) -> Panel:\n        return Panel.fit(\n            Group(*self._render()),\n            title=self.title,\n            border_style=\"scope.border\",\n            padding=(0, 1),\n        )\n\n    def _get_signature(self, name: str, obj: Any) -> Optional[Text]:\n        \"\"\"Get a signature for a callable.\"\"\"\n        try:\n            _signature = str(signature(obj)) + \":\"\n        except ValueError:\n            _signature = \"(...)\"\n        except TypeError:\n            return None\n\n        source_filename: Optional[str] = None\n        try:\n            source_filename = getfile(obj)\n        except (OSError, TypeError):\n            # OSError is raised if obj has no source file, e.g. when defined in REPL.\n            pass\n\n        callable_name = Text(name, style=\"inspect.callable\")\n        if source_filename:\n            callable_name.stylize(f\"link file://{source_filename}\")\n        signature_text = self.highlighter(_signature)\n\n        qualname = name or getattr(obj, \"__qualname__\", name)\n\n        # If obj is a module, there may be classes (which are callable) to display\n        if inspect.isclass(obj):\n            prefix = \"class\"\n        else:\n            prefix = \"def\"\n\n        qual_signature = Text.assemble(\n            (f\"{prefix} \", f\"inspect.{prefix}\"),\n            (qualname, \"inspect.callable\"),\n            signature_text,\n        )\n\n        return qual_signature\n\n    def _render(self) -> Iterable[RenderableType]:\n        \"\"\"Render object.\"\"\"\n\n        def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n            key, (_error, value) = item\n            return (callable(value), key.strip(\"_\").lower())\n\n        def safe_getattr(attr_name: str) -> Tuple[Any, Any]:\n            \"\"\"Get attribute or any exception.\"\"\"\n            try:\n                return (None, getattr(obj, attr_name))\n            except Exception as error:\n                return (error, None)\n\n        obj = self.obj\n        keys = dir(obj)\n        total_items = len(keys)\n        if not self.dunder:\n            keys = [key for key in keys if not key.startswith(\"__\")]\n        if not self.private:\n            keys = [key for key in keys if not key.startswith(\"_\")]\n        not_shown_count = total_items - len(keys)\n        items = [(key, safe_getattr(key)) for key in keys]\n        if self.sort:\n            items.sort(key=sort_items)\n\n        items_table = Table.grid(padding=(0, 1), expand=False)\n        items_table.add_column(justify=\"right\")\n        add_row = items_table.add_row\n        highlighter = self.highlighter\n\n        if callable(obj):\n            signature = self._get_signature(\"\", obj)\n            if signature is not None:\n                yield signature\n                yield \"\"\n\n        if self.docs:\n            _doc = getdoc(obj)\n            if _doc is not None:\n                if not self.help:\n                    _doc = _first_paragraph(_doc)\n                doc_text = Text(_reformat_doc(_doc), style=\"inspect.help\")\n                doc_text = highlighter(doc_text)\n                yield doc_text\n                yield \"\"\n\n        if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):\n            yield Panel(\n                Pretty(obj, indent_guides=True, max_length=10, max_string=60),\n                border_style=\"inspect.value.border\",\n            )\n            yield \"\"\n\n        for key, (error, value) in items:\n            key_text = Text.assemble(\n                (\n                    key,\n                    \"inspect.attr.dunder\" if key.startswith(\"__\") else \"inspect.attr\",\n                ),\n                (\" =\", \"inspect.equals\"),\n            )\n            if error is not None:\n                warning = key_text.copy()\n                warning.stylize(\"inspect.error\")\n                add_row(warning, highlighter(repr(error)))\n                continue\n\n            if callable(value):\n                if not self.methods:\n                    continue\n\n                _signature_text = self._get_signature(key, value)\n                if _signature_text is None:\n                    add_row(key_text, Pretty(value, highlighter=highlighter))\n                else:\n                    if self.docs:\n                        docs = getdoc(value)\n                        if docs is not None:\n                            _doc = _reformat_doc(str(docs))\n                            if not self.help:\n                                _doc = _first_paragraph(_doc)\n                            _signature_text.append(\"\\n\" if \"\\n\" in _doc else \" \")\n                            doc = highlighter(_doc)\n                            doc.stylize(\"inspect.doc\")\n                            _signature_text.append(doc)\n\n                    add_row(key_text, _signature_text)\n            else:\n                add_row(key_text, Pretty(value, highlighter=highlighter))\n        if items_table.row_count:\n            yield items_table\n        elif not_shown_count:\n            yield Text.from_markup(\n                f\"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] \"\n                f\"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options.\"\n            )\n", "path": "rich/_inspect.py"}]}