We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Failure to override an inherited field with a computed field
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

It seems that overriding a regular field with a computed field doesn't behave as expected. Instead of a value being returned by accessing the property the property object itself is returned. And as for `@cached_property` causes an exception within `pydantic/_internal/_utils.py:smart_deepcopy`.

### Example Code

```Python
from pydantic import BaseModel, computed_field
from functools import cached_property

class Foo(BaseModel):
    name: str = "Foo"

class Bar(Foo):
    @computed_field
    @property
    def name(self) -> str:
        return "Bar"

print(Foo().name)  # Foo
print(Bar().name)  # <property object at 0x...>

# Upon definition:
# > TypeError: cannot pickle '_thread.RLock' object
class Baz(Foo):
    @computed_field
    @cached_property
    def name(self) -> str:
        return "Baz"
```

Edit: After some further playing around, removing the default `name = "Foo"` from `Foo` it's clear that `name` within `Bar` is in some kind of weird hybrid state.

```Python
class Foo(BaseModel):
    name: str

class Bar(Foo):
    @computed_field
    @property
    def name(self) -> str:
        print("from property")
        return "Bar"

# Pyright complains:
# 1. Pyright: Argument missing for parameter "name" [reportGeneralTypeIssues]
# But runs and I get the same result
print(Bar().name)  # <property object at 0x...>

# Prints name as inherited from Foo, and without the `"from property"`
print(Bar(name="Bar"))  # Bar
```


### Python, Pydantic & OS Version

```Text
pydantic version: 2.1.1
        pydantic-core version: 2.4.0
          pydantic-core build: profile=release pgo=false mimalloc=true
                 install path: /Users/.../.pyenv/versions/3.11.1/lib/python3.11/site-packages/pydantic
               python version: 3.11.1 (main, Jan 14 2023, 16:44:31) [Clang 13.1.6 (clang-1316.0.21.2.5)]
                     platform: macOS-13.4-arm64-arm-64bit
     optional deps. installed: ['email-validator', 'typing-extensions']
```


Selected Assignee: @hramezani

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pydantic/_internal/_fields.py`
Content:
```
1 """Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`."""
2 from __future__ import annotations as _annotations
3 
4 import dataclasses
5 import sys
6 import warnings
7 from copy import copy
8 from typing import TYPE_CHECKING, Any
9 
10 from annotated_types import BaseMetadata
11 from pydantic_core import PydanticUndefined
12 
13 from . import _typing_extra
14 from ._config import ConfigWrapper
15 from ._repr import Representation
16 from ._typing_extra import get_cls_type_hints_lenient, get_type_hints, is_classvar, is_finalvar
17 
18 if TYPE_CHECKING:
19     from ..fields import FieldInfo
20     from ..main import BaseModel
21     from ._dataclasses import StandardDataclass
22 
23 
24 def get_type_hints_infer_globalns(
25     obj: Any,
26     localns: dict[str, Any] | None = None,
27     include_extras: bool = False,
28 ) -> dict[str, Any]:
29     """Gets type hints for an object by inferring the global namespace.
30 
31     It uses the `typing.get_type_hints`, The only thing that we do here is fetching
32     global namespace from `obj.__module__` if it is not `None`.
33 
34     Args:
35         obj: The object to get its type hints.
36         localns: The local namespaces.
37         include_extras: Whether to recursively include annotation metadata.
38 
39     Returns:
40         The object type hints.
41     """
42     module_name = getattr(obj, '__module__', None)
43     globalns: dict[str, Any] | None = None
44     if module_name:
45         try:
46             globalns = sys.modules[module_name].__dict__
47         except KeyError:
48             # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363
49             pass
50     return get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras)
51 
52 
53 class PydanticMetadata(Representation):
54     """Base class for annotation markers like `Strict`."""
55 
56     __slots__ = ()
57 
58 
59 class PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):
60     """Pydantic general metada like `max_digits`."""
61 
62     def __init__(self, **metadata: Any):
63         self.__dict__ = metadata
64 
65 
66 def collect_model_fields(  # noqa: C901
67     cls: type[BaseModel],
68     bases: tuple[type[Any], ...],
69     config_wrapper: ConfigWrapper,
70     types_namespace: dict[str, Any] | None,
71     *,
72     typevars_map: dict[Any, Any] | None = None,
73 ) -> tuple[dict[str, FieldInfo], set[str]]:
74     """Collect the fields of a nascent pydantic model.
75 
76     Also collect the names of any ClassVars present in the type hints.
77 
78     The returned value is a tuple of two items: the fields dict, and the set of ClassVar names.
79 
80     Args:
81         cls: BaseModel or dataclass.
82         bases: Parents of the class, generally `cls.__bases__`.
83         config_wrapper: The config wrapper instance.
84         types_namespace: Optional extra namespace to look for types in.
85         typevars_map: A dictionary mapping type variables to their concrete types.
86 
87     Returns:
88         A tuple contains fields and class variables.
89 
90     Raises:
91         NameError:
92             - If there is a conflict between a field name and protected namespaces.
93             - If there is a field other than `root` in `RootModel`.
94             - If a field shadows an attribute in the parent model.
95     """
96     from ..fields import FieldInfo
97 
98     type_hints = get_cls_type_hints_lenient(cls, types_namespace)
99 
100     # https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
101     # annotations is only used for finding fields in parent classes
102     annotations = cls.__dict__.get('__annotations__', {})
103     fields: dict[str, FieldInfo] = {}
104 
105     class_vars: set[str] = set()
106     for ann_name, ann_type in type_hints.items():
107         if ann_name == 'model_config':
108             # We never want to treat `model_config` as a field
109             # Note: we may need to change this logic if/when we introduce a `BareModel` class with no
110             # protected namespaces (where `model_config` might be allowed as a field name)
111             continue
112         for protected_namespace in config_wrapper.protected_namespaces:
113             if ann_name.startswith(protected_namespace):
114                 for b in bases:
115                     if hasattr(b, ann_name):
116                         from ..main import BaseModel
117 
118                         if not (issubclass(b, BaseModel) and ann_name in b.model_fields):
119                             raise NameError(
120                                 f'Field "{ann_name}" conflicts with member {getattr(b, ann_name)}'
121                                 f' of protected namespace "{protected_namespace}".'
122                             )
123                 else:
124                     valid_namespaces = tuple(
125                         x for x in config_wrapper.protected_namespaces if not ann_name.startswith(x)
126                     )
127                     warnings.warn(
128                         f'Field "{ann_name}" has conflict with protected namespace "{protected_namespace}".'
129                         '\n\nYou may be able to resolve this warning by setting'
130                         f" `model_config['protected_namespaces'] = {valid_namespaces}`.",
131                         UserWarning,
132                     )
133         if is_classvar(ann_type):
134             class_vars.add(ann_name)
135             continue
136         if _is_finalvar_with_default_val(ann_type, getattr(cls, ann_name, PydanticUndefined)):
137             class_vars.add(ann_name)
138             continue
139         if not is_valid_field_name(ann_name):
140             continue
141         if cls.__pydantic_root_model__ and ann_name != 'root':
142             raise NameError(
143                 f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`"
144             )
145 
146         # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get
147         # "... shadows an attribute" errors
148         generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')
149         for base in bases:
150             dataclass_fields = {
151                 field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())
152             }
153             if hasattr(base, ann_name):
154                 if base is generic_origin:
155                     # Don't error when "shadowing" of attributes in parametrized generics
156                     continue
157 
158                 if ann_name in dataclass_fields:
159                     # Don't error when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set
160                     # on the class instance.
161                     continue
162                 warnings.warn(
163                     f'Field name "{ann_name}" shadows an attribute in parent "{base.__qualname__}"; ',
164                     UserWarning,
165                 )
166 
167         try:
168             default = getattr(cls, ann_name, PydanticUndefined)
169             if default is PydanticUndefined:
170                 raise AttributeError
171         except AttributeError:
172             if ann_name in annotations:
173                 field_info = FieldInfo.from_annotation(ann_type)
174             else:
175                 # if field has no default value and is not in __annotations__ this means that it is
176                 # defined in a base class and we can take it from there
177                 model_fields_lookup: dict[str, FieldInfo] = {}
178                 for x in cls.__bases__[::-1]:
179                     model_fields_lookup.update(getattr(x, 'model_fields', {}))
180                 if ann_name in model_fields_lookup:
181                     # The field was present on one of the (possibly multiple) base classes
182                     # copy the field to make sure typevar substitutions don't cause issues with the base classes
183                     field_info = copy(model_fields_lookup[ann_name])
184                 else:
185                     # The field was not found on any base classes; this seems to be caused by fields not getting
186                     # generated thanks to models not being fully defined while initializing recursive models.
187                     # Nothing stops us from just creating a new FieldInfo for this type hint, so we do this.
188                     field_info = FieldInfo.from_annotation(ann_type)
189         else:
190             field_info = FieldInfo.from_annotated_attribute(ann_type, default)
191             # attributes which are fields are removed from the class namespace:
192             # 1. To match the behaviour of annotation-only fields
193             # 2. To avoid false positives in the NameError check above
194             try:
195                 delattr(cls, ann_name)
196             except AttributeError:
197                 pass  # indicates the attribute was on a parent class
198 
199         fields[ann_name] = field_info
200 
201     if typevars_map:
202         for field in fields.values():
203             field.apply_typevars_map(typevars_map, types_namespace)
204 
205     return fields, class_vars
206 
207 
208 def _is_finalvar_with_default_val(type_: type[Any], val: Any) -> bool:
209     from ..fields import FieldInfo
210 
211     if not is_finalvar(type_):
212         return False
213     elif val is PydanticUndefined:
214         return False
215     elif isinstance(val, FieldInfo) and (val.default is PydanticUndefined and val.default_factory is None):
216         return False
217     else:
218         return True
219 
220 
221 def collect_dataclass_fields(
222     cls: type[StandardDataclass], types_namespace: dict[str, Any] | None, *, typevars_map: dict[Any, Any] | None = None
223 ) -> dict[str, FieldInfo]:
224     """Collect the fields of a dataclass.
225 
226     Args:
227         cls: dataclass.
228         types_namespace: Optional extra namespace to look for types in.
229         typevars_map: A dictionary mapping type variables to their concrete types.
230 
231     Returns:
232         The dataclass fields.
233     """
234     from ..fields import FieldInfo
235 
236     fields: dict[str, FieldInfo] = {}
237     dataclass_fields: dict[str, dataclasses.Field] = cls.__dataclass_fields__
238     cls_localns = dict(vars(cls))  # this matches get_cls_type_hints_lenient, but all tests pass with `= None` instead
239 
240     for ann_name, dataclass_field in dataclass_fields.items():
241         ann_type = _typing_extra.eval_type_lenient(dataclass_field.type, types_namespace, cls_localns)
242         if is_classvar(ann_type):
243             continue
244 
245         if not dataclass_field.init and dataclass_field.default_factory == dataclasses.MISSING:
246             # TODO: We should probably do something with this so that validate_assignment behaves properly
247             #   Issue: https://github.com/pydantic/pydantic/issues/5470
248             continue
249 
250         if isinstance(dataclass_field.default, FieldInfo):
251             if dataclass_field.default.init_var:
252                 # TODO: same note as above
253                 continue
254             field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field.default)
255         else:
256             field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field)
257         fields[ann_name] = field_info
258 
259         if field_info.default is not PydanticUndefined and isinstance(getattr(cls, ann_name, field_info), FieldInfo):
260             # We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo
261             setattr(cls, ann_name, field_info.default)
262 
263     if typevars_map:
264         for field in fields.values():
265             field.apply_typevars_map(typevars_map, types_namespace)
266 
267     return fields
268 
269 
270 def is_valid_field_name(name: str) -> bool:
271     return not name.startswith('_')
272 
273 
274 def is_valid_privateattr_name(name: str) -> bool:
275     return name.startswith('_') and not name.startswith('__')
276
```
--- 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/pydantic/_internal/_fields.py b/pydantic/_internal/_fields.py
--- a/pydantic/_internal/_fields.py
+++ b/pydantic/_internal/_fields.py
@@ -19,6 +19,7 @@
     from ..fields import FieldInfo
     from ..main import BaseModel
     from ._dataclasses import StandardDataclass
+    from ._decorators import DecoratorInfos
 
 
 def get_type_hints_infer_globalns(
@@ -196,6 +197,11 @@
             except AttributeError:
                 pass  # indicates the attribute was on a parent class
 
+        # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
+        # to make sure the decorators have already been built for this exact class
+        decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
+        if ann_name in decorators.computed_fields:
+            raise ValueError("you can't override a field with a computed field")
         fields[ann_name] = field_info
 
     if typevars_map:

{"golden_diff": "diff --git a/pydantic/_internal/_fields.py b/pydantic/_internal/_fields.py\n--- a/pydantic/_internal/_fields.py\n+++ b/pydantic/_internal/_fields.py\n@@ -19,6 +19,7 @@\n     from ..fields import FieldInfo\n     from ..main import BaseModel\n     from ._dataclasses import StandardDataclass\n+    from ._decorators import DecoratorInfos\n \n \n def get_type_hints_infer_globalns(\n@@ -196,6 +197,11 @@\n             except AttributeError:\n                 pass  # indicates the attribute was on a parent class\n \n+        # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__\n+        # to make sure the decorators have already been built for this exact class\n+        decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']\n+        if ann_name in decorators.computed_fields:\n+            raise ValueError(\"you can't override a field with a computed field\")\n         fields[ann_name] = field_info\n \n     if typevars_map:\n", "issue": "Failure to override an inherited field with a computed field\n### Initial Checks\r\n\r\n- [X] I confirm that I'm using Pydantic V2\r\n\r\n### Description\r\n\r\nIt seems that overriding a regular field with a computed field doesn't behave as expected. Instead of a value being returned by accessing the property the property object itself is returned. And as for `@cached_property` causes an exception within `pydantic/_internal/_utils.py:smart_deepcopy`.\r\n\r\n### Example Code\r\n\r\n```Python\r\nfrom pydantic import BaseModel, computed_field\r\nfrom functools import cached_property\r\n\r\nclass Foo(BaseModel):\r\n    name: str = \"Foo\"\r\n\r\nclass Bar(Foo):\r\n    @computed_field\r\n    @property\r\n    def name(self) -> str:\r\n        return \"Bar\"\r\n\r\nprint(Foo().name)  # Foo\r\nprint(Bar().name)  # <property object at 0x...>\r\n\r\n# Upon definition:\r\n# > TypeError: cannot pickle '_thread.RLock' object\r\nclass Baz(Foo):\r\n    @computed_field\r\n    @cached_property\r\n    def name(self) -> str:\r\n        return \"Baz\"\r\n```\r\n\r\nEdit: After some further playing around, removing the default `name = \"Foo\"` from `Foo` it's clear that `name` within `Bar` is in some kind of weird hybrid state.\r\n\r\n```Python\r\nclass Foo(BaseModel):\r\n    name: str\r\n\r\nclass Bar(Foo):\r\n    @computed_field\r\n    @property\r\n    def name(self) -> str:\r\n        print(\"from property\")\r\n        return \"Bar\"\r\n\r\n# Pyright complains:\r\n# 1. Pyright: Argument missing for parameter \"name\" [reportGeneralTypeIssues]\r\n# But runs and I get the same result\r\nprint(Bar().name)  # <property object at 0x...>\r\n\r\n# Prints name as inherited from Foo, and without the `\"from property\"`\r\nprint(Bar(name=\"Bar\"))  # Bar\r\n```\r\n\r\n\r\n### Python, Pydantic & OS Version\r\n\r\n```Text\r\npydantic version: 2.1.1\r\n        pydantic-core version: 2.4.0\r\n          pydantic-core build: profile=release pgo=false mimalloc=true\r\n                 install path: /Users/.../.pyenv/versions/3.11.1/lib/python3.11/site-packages/pydantic\r\n               python version: 3.11.1 (main, Jan 14 2023, 16:44:31) [Clang 13.1.6 (clang-1316.0.21.2.5)]\r\n                     platform: macOS-13.4-arm64-arm-64bit\r\n     optional deps. installed: ['email-validator', 'typing-extensions']\r\n```\r\n\r\n\r\nSelected Assignee: @hramezani\n", "before_files": [{"content": "\"\"\"Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`.\"\"\"\nfrom __future__ import annotations as _annotations\n\nimport dataclasses\nimport sys\nimport warnings\nfrom copy import copy\nfrom typing import TYPE_CHECKING, Any\n\nfrom annotated_types import BaseMetadata\nfrom pydantic_core import PydanticUndefined\n\nfrom . import _typing_extra\nfrom ._config import ConfigWrapper\nfrom ._repr import Representation\nfrom ._typing_extra import get_cls_type_hints_lenient, get_type_hints, is_classvar, is_finalvar\n\nif TYPE_CHECKING:\n    from ..fields import FieldInfo\n    from ..main import BaseModel\n    from ._dataclasses import StandardDataclass\n\n\ndef get_type_hints_infer_globalns(\n    obj: Any,\n    localns: dict[str, Any] | None = None,\n    include_extras: bool = False,\n) -> dict[str, Any]:\n    \"\"\"Gets type hints for an object by inferring the global namespace.\n\n    It uses the `typing.get_type_hints`, The only thing that we do here is fetching\n    global namespace from `obj.__module__` if it is not `None`.\n\n    Args:\n        obj: The object to get its type hints.\n        localns: The local namespaces.\n        include_extras: Whether to recursively include annotation metadata.\n\n    Returns:\n        The object type hints.\n    \"\"\"\n    module_name = getattr(obj, '__module__', None)\n    globalns: dict[str, Any] | None = None\n    if module_name:\n        try:\n            globalns = sys.modules[module_name].__dict__\n        except KeyError:\n            # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363\n            pass\n    return get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras)\n\n\nclass PydanticMetadata(Representation):\n    \"\"\"Base class for annotation markers like `Strict`.\"\"\"\n\n    __slots__ = ()\n\n\nclass PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):\n    \"\"\"Pydantic general metada like `max_digits`.\"\"\"\n\n    def __init__(self, **metadata: Any):\n        self.__dict__ = metadata\n\n\ndef collect_model_fields(  # noqa: C901\n    cls: type[BaseModel],\n    bases: tuple[type[Any], ...],\n    config_wrapper: ConfigWrapper,\n    types_namespace: dict[str, Any] | None,\n    *,\n    typevars_map: dict[Any, Any] | None = None,\n) -> tuple[dict[str, FieldInfo], set[str]]:\n    \"\"\"Collect the fields of a nascent pydantic model.\n\n    Also collect the names of any ClassVars present in the type hints.\n\n    The returned value is a tuple of two items: the fields dict, and the set of ClassVar names.\n\n    Args:\n        cls: BaseModel or dataclass.\n        bases: Parents of the class, generally `cls.__bases__`.\n        config_wrapper: The config wrapper instance.\n        types_namespace: Optional extra namespace to look for types in.\n        typevars_map: A dictionary mapping type variables to their concrete types.\n\n    Returns:\n        A tuple contains fields and class variables.\n\n    Raises:\n        NameError:\n            - If there is a conflict between a field name and protected namespaces.\n            - If there is a field other than `root` in `RootModel`.\n            - If a field shadows an attribute in the parent model.\n    \"\"\"\n    from ..fields import FieldInfo\n\n    type_hints = get_cls_type_hints_lenient(cls, types_namespace)\n\n    # https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older\n    # annotations is only used for finding fields in parent classes\n    annotations = cls.__dict__.get('__annotations__', {})\n    fields: dict[str, FieldInfo] = {}\n\n    class_vars: set[str] = set()\n    for ann_name, ann_type in type_hints.items():\n        if ann_name == 'model_config':\n            # We never want to treat `model_config` as a field\n            # Note: we may need to change this logic if/when we introduce a `BareModel` class with no\n            # protected namespaces (where `model_config` might be allowed as a field name)\n            continue\n        for protected_namespace in config_wrapper.protected_namespaces:\n            if ann_name.startswith(protected_namespace):\n                for b in bases:\n                    if hasattr(b, ann_name):\n                        from ..main import BaseModel\n\n                        if not (issubclass(b, BaseModel) and ann_name in b.model_fields):\n                            raise NameError(\n                                f'Field \"{ann_name}\" conflicts with member {getattr(b, ann_name)}'\n                                f' of protected namespace \"{protected_namespace}\".'\n                            )\n                else:\n                    valid_namespaces = tuple(\n                        x for x in config_wrapper.protected_namespaces if not ann_name.startswith(x)\n                    )\n                    warnings.warn(\n                        f'Field \"{ann_name}\" has conflict with protected namespace \"{protected_namespace}\".'\n                        '\\n\\nYou may be able to resolve this warning by setting'\n                        f\" `model_config['protected_namespaces'] = {valid_namespaces}`.\",\n                        UserWarning,\n                    )\n        if is_classvar(ann_type):\n            class_vars.add(ann_name)\n            continue\n        if _is_finalvar_with_default_val(ann_type, getattr(cls, ann_name, PydanticUndefined)):\n            class_vars.add(ann_name)\n            continue\n        if not is_valid_field_name(ann_name):\n            continue\n        if cls.__pydantic_root_model__ and ann_name != 'root':\n            raise NameError(\n                f\"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`\"\n            )\n\n        # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get\n        # \"... shadows an attribute\" errors\n        generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')\n        for base in bases:\n            dataclass_fields = {\n                field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())\n            }\n            if hasattr(base, ann_name):\n                if base is generic_origin:\n                    # Don't error when \"shadowing\" of attributes in parametrized generics\n                    continue\n\n                if ann_name in dataclass_fields:\n                    # Don't error when inheriting stdlib dataclasses whose fields are \"shadowed\" by defaults being set\n                    # on the class instance.\n                    continue\n                warnings.warn(\n                    f'Field name \"{ann_name}\" shadows an attribute in parent \"{base.__qualname__}\"; ',\n                    UserWarning,\n                )\n\n        try:\n            default = getattr(cls, ann_name, PydanticUndefined)\n            if default is PydanticUndefined:\n                raise AttributeError\n        except AttributeError:\n            if ann_name in annotations:\n                field_info = FieldInfo.from_annotation(ann_type)\n            else:\n                # if field has no default value and is not in __annotations__ this means that it is\n                # defined in a base class and we can take it from there\n                model_fields_lookup: dict[str, FieldInfo] = {}\n                for x in cls.__bases__[::-1]:\n                    model_fields_lookup.update(getattr(x, 'model_fields', {}))\n                if ann_name in model_fields_lookup:\n                    # The field was present on one of the (possibly multiple) base classes\n                    # copy the field to make sure typevar substitutions don't cause issues with the base classes\n                    field_info = copy(model_fields_lookup[ann_name])\n                else:\n                    # The field was not found on any base classes; this seems to be caused by fields not getting\n                    # generated thanks to models not being fully defined while initializing recursive models.\n                    # Nothing stops us from just creating a new FieldInfo for this type hint, so we do this.\n                    field_info = FieldInfo.from_annotation(ann_type)\n        else:\n            field_info = FieldInfo.from_annotated_attribute(ann_type, default)\n            # attributes which are fields are removed from the class namespace:\n            # 1. To match the behaviour of annotation-only fields\n            # 2. To avoid false positives in the NameError check above\n            try:\n                delattr(cls, ann_name)\n            except AttributeError:\n                pass  # indicates the attribute was on a parent class\n\n        fields[ann_name] = field_info\n\n    if typevars_map:\n        for field in fields.values():\n            field.apply_typevars_map(typevars_map, types_namespace)\n\n    return fields, class_vars\n\n\ndef _is_finalvar_with_default_val(type_: type[Any], val: Any) -> bool:\n    from ..fields import FieldInfo\n\n    if not is_finalvar(type_):\n        return False\n    elif val is PydanticUndefined:\n        return False\n    elif isinstance(val, FieldInfo) and (val.default is PydanticUndefined and val.default_factory is None):\n        return False\n    else:\n        return True\n\n\ndef collect_dataclass_fields(\n    cls: type[StandardDataclass], types_namespace: dict[str, Any] | None, *, typevars_map: dict[Any, Any] | None = None\n) -> dict[str, FieldInfo]:\n    \"\"\"Collect the fields of a dataclass.\n\n    Args:\n        cls: dataclass.\n        types_namespace: Optional extra namespace to look for types in.\n        typevars_map: A dictionary mapping type variables to their concrete types.\n\n    Returns:\n        The dataclass fields.\n    \"\"\"\n    from ..fields import FieldInfo\n\n    fields: dict[str, FieldInfo] = {}\n    dataclass_fields: dict[str, dataclasses.Field] = cls.__dataclass_fields__\n    cls_localns = dict(vars(cls))  # this matches get_cls_type_hints_lenient, but all tests pass with `= None` instead\n\n    for ann_name, dataclass_field in dataclass_fields.items():\n        ann_type = _typing_extra.eval_type_lenient(dataclass_field.type, types_namespace, cls_localns)\n        if is_classvar(ann_type):\n            continue\n\n        if not dataclass_field.init and dataclass_field.default_factory == dataclasses.MISSING:\n            # TODO: We should probably do something with this so that validate_assignment behaves properly\n            #   Issue: https://github.com/pydantic/pydantic/issues/5470\n            continue\n\n        if isinstance(dataclass_field.default, FieldInfo):\n            if dataclass_field.default.init_var:\n                # TODO: same note as above\n                continue\n            field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field.default)\n        else:\n            field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field)\n        fields[ann_name] = field_info\n\n        if field_info.default is not PydanticUndefined and isinstance(getattr(cls, ann_name, field_info), FieldInfo):\n            # We need this to fix the default when the \"default\" from __dataclass_fields__ is a pydantic.FieldInfo\n            setattr(cls, ann_name, field_info.default)\n\n    if typevars_map:\n        for field in fields.values():\n            field.apply_typevars_map(typevars_map, types_namespace)\n\n    return fields\n\n\ndef is_valid_field_name(name: str) -> bool:\n    return not name.startswith('_')\n\n\ndef is_valid_privateattr_name(name: str) -> bool:\n    return name.startswith('_') and not name.startswith('__')\n", "path": "pydantic/_internal/_fields.py"}], "after_files": [{"content": "\"\"\"Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`.\"\"\"\nfrom __future__ import annotations as _annotations\n\nimport dataclasses\nimport sys\nimport warnings\nfrom copy import copy\nfrom typing import TYPE_CHECKING, Any\n\nfrom annotated_types import BaseMetadata\nfrom pydantic_core import PydanticUndefined\n\nfrom . import _typing_extra\nfrom ._config import ConfigWrapper\nfrom ._repr import Representation\nfrom ._typing_extra import get_cls_type_hints_lenient, get_type_hints, is_classvar, is_finalvar\n\nif TYPE_CHECKING:\n    from ..fields import FieldInfo\n    from ..main import BaseModel\n    from ._dataclasses import StandardDataclass\n    from ._decorators import DecoratorInfos\n\n\ndef get_type_hints_infer_globalns(\n    obj: Any,\n    localns: dict[str, Any] | None = None,\n    include_extras: bool = False,\n) -> dict[str, Any]:\n    \"\"\"Gets type hints for an object by inferring the global namespace.\n\n    It uses the `typing.get_type_hints`, The only thing that we do here is fetching\n    global namespace from `obj.__module__` if it is not `None`.\n\n    Args:\n        obj: The object to get its type hints.\n        localns: The local namespaces.\n        include_extras: Whether to recursively include annotation metadata.\n\n    Returns:\n        The object type hints.\n    \"\"\"\n    module_name = getattr(obj, '__module__', None)\n    globalns: dict[str, Any] | None = None\n    if module_name:\n        try:\n            globalns = sys.modules[module_name].__dict__\n        except KeyError:\n            # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363\n            pass\n    return get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras)\n\n\nclass PydanticMetadata(Representation):\n    \"\"\"Base class for annotation markers like `Strict`.\"\"\"\n\n    __slots__ = ()\n\n\nclass PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):\n    \"\"\"Pydantic general metada like `max_digits`.\"\"\"\n\n    def __init__(self, **metadata: Any):\n        self.__dict__ = metadata\n\n\ndef collect_model_fields(  # noqa: C901\n    cls: type[BaseModel],\n    bases: tuple[type[Any], ...],\n    config_wrapper: ConfigWrapper,\n    types_namespace: dict[str, Any] | None,\n    *,\n    typevars_map: dict[Any, Any] | None = None,\n) -> tuple[dict[str, FieldInfo], set[str]]:\n    \"\"\"Collect the fields of a nascent pydantic model.\n\n    Also collect the names of any ClassVars present in the type hints.\n\n    The returned value is a tuple of two items: the fields dict, and the set of ClassVar names.\n\n    Args:\n        cls: BaseModel or dataclass.\n        bases: Parents of the class, generally `cls.__bases__`.\n        config_wrapper: The config wrapper instance.\n        types_namespace: Optional extra namespace to look for types in.\n        typevars_map: A dictionary mapping type variables to their concrete types.\n\n    Returns:\n        A tuple contains fields and class variables.\n\n    Raises:\n        NameError:\n            - If there is a conflict between a field name and protected namespaces.\n            - If there is a field other than `root` in `RootModel`.\n            - If a field shadows an attribute in the parent model.\n    \"\"\"\n    from ..fields import FieldInfo\n\n    type_hints = get_cls_type_hints_lenient(cls, types_namespace)\n\n    # https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older\n    # annotations is only used for finding fields in parent classes\n    annotations = cls.__dict__.get('__annotations__', {})\n    fields: dict[str, FieldInfo] = {}\n\n    class_vars: set[str] = set()\n    for ann_name, ann_type in type_hints.items():\n        if ann_name == 'model_config':\n            # We never want to treat `model_config` as a field\n            # Note: we may need to change this logic if/when we introduce a `BareModel` class with no\n            # protected namespaces (where `model_config` might be allowed as a field name)\n            continue\n        for protected_namespace in config_wrapper.protected_namespaces:\n            if ann_name.startswith(protected_namespace):\n                for b in bases:\n                    if hasattr(b, ann_name):\n                        from ..main import BaseModel\n\n                        if not (issubclass(b, BaseModel) and ann_name in b.model_fields):\n                            raise NameError(\n                                f'Field \"{ann_name}\" conflicts with member {getattr(b, ann_name)}'\n                                f' of protected namespace \"{protected_namespace}\".'\n                            )\n                else:\n                    valid_namespaces = tuple(\n                        x for x in config_wrapper.protected_namespaces if not ann_name.startswith(x)\n                    )\n                    warnings.warn(\n                        f'Field \"{ann_name}\" has conflict with protected namespace \"{protected_namespace}\".'\n                        '\\n\\nYou may be able to resolve this warning by setting'\n                        f\" `model_config['protected_namespaces'] = {valid_namespaces}`.\",\n                        UserWarning,\n                    )\n        if is_classvar(ann_type):\n            class_vars.add(ann_name)\n            continue\n        if _is_finalvar_with_default_val(ann_type, getattr(cls, ann_name, PydanticUndefined)):\n            class_vars.add(ann_name)\n            continue\n        if not is_valid_field_name(ann_name):\n            continue\n        if cls.__pydantic_root_model__ and ann_name != 'root':\n            raise NameError(\n                f\"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`\"\n            )\n\n        # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get\n        # \"... shadows an attribute\" errors\n        generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')\n        for base in bases:\n            dataclass_fields = {\n                field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())\n            }\n            if hasattr(base, ann_name):\n                if base is generic_origin:\n                    # Don't error when \"shadowing\" of attributes in parametrized generics\n                    continue\n\n                if ann_name in dataclass_fields:\n                    # Don't error when inheriting stdlib dataclasses whose fields are \"shadowed\" by defaults being set\n                    # on the class instance.\n                    continue\n                warnings.warn(\n                    f'Field name \"{ann_name}\" shadows an attribute in parent \"{base.__qualname__}\"; ',\n                    UserWarning,\n                )\n\n        try:\n            default = getattr(cls, ann_name, PydanticUndefined)\n            if default is PydanticUndefined:\n                raise AttributeError\n        except AttributeError:\n            if ann_name in annotations:\n                field_info = FieldInfo.from_annotation(ann_type)\n            else:\n                # if field has no default value and is not in __annotations__ this means that it is\n                # defined in a base class and we can take it from there\n                model_fields_lookup: dict[str, FieldInfo] = {}\n                for x in cls.__bases__[::-1]:\n                    model_fields_lookup.update(getattr(x, 'model_fields', {}))\n                if ann_name in model_fields_lookup:\n                    # The field was present on one of the (possibly multiple) base classes\n                    # copy the field to make sure typevar substitutions don't cause issues with the base classes\n                    field_info = copy(model_fields_lookup[ann_name])\n                else:\n                    # The field was not found on any base classes; this seems to be caused by fields not getting\n                    # generated thanks to models not being fully defined while initializing recursive models.\n                    # Nothing stops us from just creating a new FieldInfo for this type hint, so we do this.\n                    field_info = FieldInfo.from_annotation(ann_type)\n        else:\n            field_info = FieldInfo.from_annotated_attribute(ann_type, default)\n            # attributes which are fields are removed from the class namespace:\n            # 1. To match the behaviour of annotation-only fields\n            # 2. To avoid false positives in the NameError check above\n            try:\n                delattr(cls, ann_name)\n            except AttributeError:\n                pass  # indicates the attribute was on a parent class\n\n        # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__\n        # to make sure the decorators have already been built for this exact class\n        decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']\n        if ann_name in decorators.computed_fields:\n            raise ValueError(\"you can't override a field with a computed field\")\n        fields[ann_name] = field_info\n\n    if typevars_map:\n        for field in fields.values():\n            field.apply_typevars_map(typevars_map, types_namespace)\n\n    return fields, class_vars\n\n\ndef _is_finalvar_with_default_val(type_: type[Any], val: Any) -> bool:\n    from ..fields import FieldInfo\n\n    if not is_finalvar(type_):\n        return False\n    elif val is PydanticUndefined:\n        return False\n    elif isinstance(val, FieldInfo) and (val.default is PydanticUndefined and val.default_factory is None):\n        return False\n    else:\n        return True\n\n\ndef collect_dataclass_fields(\n    cls: type[StandardDataclass], types_namespace: dict[str, Any] | None, *, typevars_map: dict[Any, Any] | None = None\n) -> dict[str, FieldInfo]:\n    \"\"\"Collect the fields of a dataclass.\n\n    Args:\n        cls: dataclass.\n        types_namespace: Optional extra namespace to look for types in.\n        typevars_map: A dictionary mapping type variables to their concrete types.\n\n    Returns:\n        The dataclass fields.\n    \"\"\"\n    from ..fields import FieldInfo\n\n    fields: dict[str, FieldInfo] = {}\n    dataclass_fields: dict[str, dataclasses.Field] = cls.__dataclass_fields__\n    cls_localns = dict(vars(cls))  # this matches get_cls_type_hints_lenient, but all tests pass with `= None` instead\n\n    for ann_name, dataclass_field in dataclass_fields.items():\n        ann_type = _typing_extra.eval_type_lenient(dataclass_field.type, types_namespace, cls_localns)\n        if is_classvar(ann_type):\n            continue\n\n        if not dataclass_field.init and dataclass_field.default_factory == dataclasses.MISSING:\n            # TODO: We should probably do something with this so that validate_assignment behaves properly\n            #   Issue: https://github.com/pydantic/pydantic/issues/5470\n            continue\n\n        if isinstance(dataclass_field.default, FieldInfo):\n            if dataclass_field.default.init_var:\n                # TODO: same note as above\n                continue\n            field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field.default)\n        else:\n            field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field)\n        fields[ann_name] = field_info\n\n        if field_info.default is not PydanticUndefined and isinstance(getattr(cls, ann_name, field_info), FieldInfo):\n            # We need this to fix the default when the \"default\" from __dataclass_fields__ is a pydantic.FieldInfo\n            setattr(cls, ann_name, field_info.default)\n\n    if typevars_map:\n        for field in fields.values():\n            field.apply_typevars_map(typevars_map, types_namespace)\n\n    return fields\n\n\ndef is_valid_field_name(name: str) -> bool:\n    return not name.startswith('_')\n\n\ndef is_valid_privateattr_name(name: str) -> bool:\n    return name.startswith('_') and not name.startswith('__')\n", "path": "pydantic/_internal/_fields.py"}]}