How to override a parent class property attribute in Pydantic

I want to override a parent class property decorated attribute like this:

from pydantic import BaseModel

class Parent(BaseModel):
  name: str="foo bar"
  
  @property
  def name_new(self):
    return f"{'_'.join(self.name.split(' '))}"
  

class Child(Parent):
  name_new = 'foo_bar_foo'

but I always got this error:
NameError: Field name "name_new" shadows a BaseModel attribute; use a different field name with "alias="name_new"".

I tried this:

from pydantic import BaseModel, Field

class Parent(BaseModel):
  name: str="foo bar"
  
  @property
  def name_new(self):
    return f"{'_'.join(self.name.split(' '))}"
  

class Child(Parent):
  name_new_new = Field('foo_bar_foo', alias="name_new")

c = Child()

However, c.name_new still has a value of foo_bar instead of foo_bar_foo. How can I override in the Child class so that the name_new attribute has a value of foo_bar_foo? Thanks!

  • Don’t you need to include a setter in the parent class? Or directly do name = 'foo bar'? Or am I misunderstanding you?

    – 

You cannot override property of pydantic BaseModel.

consider using init method.

from pydantic import BaseModel

class Parent(BaseModel):
  name: str="foo bar"
  name_new: str=""
  
  def __init__(self):
      super().__init__()
      if not self.name_new:
        self.name_new = f"{'_'.join(self.name.split(' '))}"

  

class Child(Parent):
  name_new: str="foo_bar_foo"

print(Parent().name_new)
# foo_bar
print(Child().name_new)
# foo_bar_foo

Leave a Comment