agronholm / agronholm/typeguard

`typechecked` in a Jupyter notebook / IPython always triggers `TypeError: <module '__main__'> is a built-in module`

オープン
#364 コメント 13 件 リアクション 2 件 担当者 0 名 GitHub で見る
bug
主要言語
Python
スター
1.8k
フォーク
145
平均マージ
8日 12時間
マージ済み PR(30日)
1

説明

### Things to check first

- [X] I have searched the existing issues and didn't find my bug already reported there

- [X] I have checked that my bug is still present in the latest release

### Typeguard version

4.0.0

### Python version

3.10.10

### What happened?

Using `typechecked` in a Jupyter notebook or in IPython results in the following exception, as of version 4:

```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 2
1 @typechecked
----> 2 def foo(bar: str):
3 print(bar)
5 foo('Hello world!')

File ~/conda/envs/gravitation/lib/python3.10/site-packages/typeguard/_decorators.py:213, in typechecked(target, forward_ref_policy, typecheck_fail_callback, collection_check_strategy, debug_instrumentation)
210 wrapper_class = target.__class__
211 target = target.__func__
--> 213 retval = instrument(target)
214 if isinstance(retval, str):
215 warn(
216 f"{retval} -- not typechecking {function_name(target)}",
217 InstrumentationWarning,
218 stacklevel=get_stacklevel(),
219 )

File ~/conda/envs/gravitation/lib/python3.10/site-packages/typeguard/_decorators.py:51, in instrument(f)
45 return (
46 "@typechecked only supports instrumenting functions wrapped with "
47 "@classmethod, @staticmethod or @property"
48 )
50 target_path = [item for item in f.__qualname__.split(".") if item != ""]
---> 51 module_source = inspect.getsource(sys.modules[f.__module__])
52 module_ast = ast.parse(module_source)
53 instrumentor = TypeguardTransformer(target_path)

File ~/conda/envs/gravitation/lib/python3.10/inspect.py:1139, in getsource(object)
1133 def getsource(object):
1134 """Return the text of the source code for an object.
1135
1136 The argument may be a module, class, method, function, traceback, frame,
1137 or code object. The source code is returned as a single string. An
1138 OSError is raised if the source code cannot be retrieved."""
-> 1139 lines, lnum = getsourcelines(object)
1140 return ''.join(lines)

File ~/conda/envs/gravitation/lib/python3.10/inspect.py:1121, in getsourcelines(object)
1113 """Return a list of source lines and starting line number for an object.
1114
1115 The argument may be a module, class, method, function, traceback, frame,
(...)
1118 original source file the first line of code was found. An OSError is
1119 raised if the source code cannot be retrieved."""
1120 object = unwrap(object)
-> 1121 lines, lnum = findsource(object)
1123 if istraceback(object):
1124 object = object.tb_frame

File ~/conda/envs/gravitation/lib/python3.10/inspect.py:940, in findsource(object)
932 def findsource(object):
933 """Return the entire source file and starting line number for an object.
934
935 The argument may be a module, class, method, function, traceback, frame,
936 or code object. The source code is returned as a list of all the lines
937 in the file and the line number indexes a line in that list. An OSError
938 is raised if the source code cannot be retrieved."""
--> 940 file = getsourcefile(object)
941 if file:
942 # Invalidate cache if needed.
943 linecache.checkcache(file)

File ~/conda/envs/gravitation/lib/python3.10/inspect.py:817, in getsourcefile(object)
813 def getsourcefile(object):
814 """Return the filename that can be used to locate an object's source.
815 Return None if no way can be identified to get the source.
816 """
--> 817 filename = getfile(object)
818 all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
819 all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]

File ~/conda/envs/gravitation/lib/python3.10/inspect.py:778, in getfile(object)
776 if getattr(object, '__file__', None):
777 return object.__file__
--> 778 raise TypeError('{!r} is a built-in module'.format(object))
779 if isclass(object):
780 if hasattr(object, '__module__'):

TypeError: is a built-in module
```

### How can we reproduce the bug?

Inside a Jupyter notebook or IPython, do:

```python
from typeguard import typechecked

@typechecked
def foo(bar: str):
print(bar)

foo('Hello world!')
```

Expected outcome: "Hello world" gets printed.

Actual outcome: Exception `TypeError: is a built-in module`

---

EDIT: Also happens in IPython.

コントリビューションガイド

コントリビューションガイドを開く

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。