Repository: pydantic/pydantic

Issue:
Impl. of BaseModel with method crashes when Cythonized
# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.6.1
            pydantic compiled: True
                 install path: /Users/mordaren/Source/pydantic/pydantic
               python version: 3.7.7 (default, Mar 10 2020, 15:43:27)  [Clang 10.0.0 (clang-1000.11.45.5)]
                     platform: Darwin-17.2.0-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions', 'email-validator', 'devtools']
```


Here's a minimal example:

main.py:
```py
from pydantic import BaseModel

class MyModel(BaseModel):
    x: float = 123

    def x2(self):
        return self.x**2

def main():
    model = MyModel(x=10)
    print("x^2 = ", model.x2())
```

setup.py:
```
from setuptools import setup
from Cython.Build import cythonize

setup(
    name='testapp',
    ext_modules=cythonize("main.py"),
)
```

Cythonize the script using the following command (mac OS): 

``` python setup.py build_ext --inplace```


When trying to import main, the following crash occurs (ensure that you're importing the actual Cythonized file):
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 5, in init main
    class MyModel(BaseModel):
  File "pydantic/main.py", line 285, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 309, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 271, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 351, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 529, in pydantic.fields.ModelField.populate_validators
  File "pydantic/validators.py", line 593, in find_validators
RuntimeError: no validator found for <class 'cython_function_or_method'>, see `arbitrary_types_allowed` in Config
```




Discussion:

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -259,6 +259,11 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
 
         prepare_config(config, name)
 
+        untouched_types = ANNOTATED_FIELD_UNTOUCHED_TYPES
+
+        def is_untouched(v: Any) -> bool:
+            return isinstance(v, untouched_types) or v.__class__.__name__ == 'cython_function_or_method'
+
         if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'):
             annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None))
             # annotation only fields need to come first in fields
@@ -270,7 +275,7 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
                     value = namespace.get(ann_name, Undefined)
                     allowed_types = get_args(ann_type) if get_origin(ann_type) is Union else (ann_type,)
                     if (
-                        isinstance(value, ANNOTATED_FIELD_UNTOUCHED_TYPES)
+                        is_untouched(value)
                         and ann_type != PyObject
                         and not any(
                             lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types
@@ -289,7 +294,7 @@ def __new__(mcs, name, bases, namespace, **kwargs):  # noqa C901
 
             untouched_types = UNTOUCHED_TYPES + config.keep_untouched
             for var_name, value in namespace.items():
-                can_be_changed = var_name not in class_vars and not isinstance(value, untouched_types)
+                can_be_changed = var_name not in class_vars and not is_untouched(value)
                 if isinstance(value, ModelPrivateAttr):
                     if not is_valid_private_name(var_name):
                         raise NameError(


Test patch:
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py
--- a/tests/test_edge_cases.py
+++ b/tests/test_edge_cases.py
@@ -20,6 +20,11 @@
 )
 from pydantic.fields import Field, Schema
 
+try:
+    import cython
+except ImportError:
+    cython = None
+
 
 def test_str_bytes():
     class Model(BaseModel):
@@ -1745,3 +1750,26 @@ class Child(Parent):
         pass
 
     assert Child(foo=['a', 'b']).foo == ['a-1', 'b-1']
+
+
+@pytest.mark.skipif(cython is None, reason='cython not installed')
+def test_cython_function_untouched():
+    Model = cython.inline(
+        # language=Python
+        """
+from pydantic import BaseModel
+
+class Model(BaseModel):
+    a = 0.0
+    b = 10
+
+    def get_double_a(self) -> float:
+        return self.a + self.b
+
+return Model
+"""
+    )
+    model = Model(a=10.2)
+    assert model.a == 10.2
+    assert model.b == 10
+    return model.get_double_a() == 20.2