Pydantic: Is it possible to implement fields autogenerated?

Created on 4 Jun 2020  路  1Comment  路  Source: samuelcolvin/pydantic

Question

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.5.1
            pydantic compiled: True
                 install path: /home/vgonisanz/miniconda3/envs/foo3.7/lib/python3.7/site-packages/pydantic
               python version: 3.7.6 (default, Jan  8 2020, 19:59:22)  [GCC 7.3.0]
                     platform: Linux-5.3.0-53-generic-x86_64-with-debian-buster-sid
     optional deps. installed: []

I have a use case there I use pydantic with some fields, and also I want create a private field using another one. This is interesing, for example, to have some data and the hash of the data (autogenerated without call a funcion of the class)

I didn't found a way to do this, this is a simplified example that fail:

import pydantic 
import base64 

class Foo(pydantic.BaseModel):  
    value: str  
    _b64value: str = None  

    @property  
    def b64value(self): 
        if not self._b64value: 
            self._b64value = base64.b64encode(self.value.encode("utf-8"))  
        return self._b64value 

test = Foo(value="foo") 
test.b64value # ValueError: "Foo" object has no field "_b64value"

This approach works, but it is not optimal because it call the value each time you get it:

import pydantic
import base64

class Foo(pydantic.BaseModel): 
    value: str

    @property 
    def b64value(self): 
        return base64.b64encode(self.value.encode("utf-8"))

test = Foo(value="foo")
test.b64value # b'Zm9v'

Any tips of how do this?

question

Most helpful comment

This isn't currently possible in a clean way, it'll be supported in future via computed fields https://github.com/samuelcolvin/pydantic/issues/935#issuecomment-555036039

The best option for now is either what you have above or an extra field with a validator and always=True, pre=True.

>All comments

This isn't currently possible in a clean way, it'll be supported in future via computed fields https://github.com/samuelcolvin/pydantic/issues/935#issuecomment-555036039

The best option for now is either what you have above or an extra field with a validator and always=True, pre=True.

Was this page helpful?
0 / 5 - 0 ratings