pythonpydantic

How to manipulate a model (Pydantic) which just is defined at runtime


I have a situation like this: I know there will be a Person object model. But I haven't know it's attribute yet, until run time. a Person object will be defined and write into a Python file in project directory. Another option is at runtime a yml or json file will be created to describe that Person object.

But I also have to use that Person oject in another function when pre-define function in workflow. this function will be invoked later after Person is defined

for example:

def my_func(person: Person): # But this Person isn't defined. 
   print(person)

I'm not sure if I can define a Person then overwrite it later. As I think Python already read that Person object and save into memory then there will be a confict.

Thank you.


Edit:

This is for @Anerdw 's concern:

Actually I'll use a LLM model to generate code. Depend on input data, different attribute will be created. the generated script will be saved. I don't know if this make sense. Or maybe contains in a dictionary variable where contains description of that Person object. Pydantic have a create_model function to create BaseModel object from json I guess


Solution

  • You can define Person later at runtime using pydantic.create_model() and still use it in a function defined earlier. Just use a string type hint (forward reference) like this:

    def my_func(person: 'Person'):
        print(person)
    
    # Later at runtime
    from pydantic import create_model
    Person = create_model('Person', name=(str, ...), age=(int, None))
    
    

    python will not error as long as the function isn’t called before Person is defined.