Fix NameError when using validate_call with PEP 695 on a class#10380
Fix NameError when using validate_call with PEP 695 on a class#10380sydney-runkle merged 9 commits intopydantic:mainfrom
NameError when using validate_call with PEP 695 on a class#10380Conversation
CodSpeed Performance ReportMerging #10380 will not alter performanceComparing Summary
|
sydney-runkle
left a comment
There was a problem hiding this comment.
LGTM overall, just a few change requests :).
sydney-runkle
left a comment
There was a problem hiding this comment.
Nice work, thanks!!
|
@sydney-runkle I think the nested scope issues here are different from the case of from __future__ import annotations
class A[T: int](BaseModel):
def g1(self):
return TypeAdapter(list[T])
def g2(self):
@validate_call
def f() -> T: ...When calling On the other hand, the So currently I guess the best we could do is to make sure things work without |
|
Gotcha. My suggestion was that we could add a |
import inspect
import sys
from pydantic._internal import _typing_extra
# analogy to `validate_call`, we want to access `a` in this function
def api():
# ! `f` is NOT in stack
# print([f.function for f in inspect.stack()]) # ['api', 'g', '<module>']
# print(sys._getframe(1).f_code.co_name) # 'g'
# print(sys._getframe(2).f_code.co_name) # '<module>'
# parent_depth should add 1 because `parent_frame_namespace` is pushed to call stack
print('ns of g:', _typing_extra.parent_frame_namespace(parent_depth=2))
def f():
a = 1
def g1():
api()
def g2():
a
api()
return g1, g2
g1, g2 = f()
g1() # ns of g: {}
g2() # ns of g: {'a': 1}Here is a simple demo. My point is that by the time |
Change Summary
This PR fixes the
NameErrorwhenfrom __future__ import annotationsand we callvalidate_callinside a class definition with PEP 695:However, calling
validate_callin nested scopes will still throwNameError. This is probably due toparent_frame_namespace. Example:Related issue number
fix #10150
Checklist