Luciogi

Python Modify Class Fields During Construction

Table of Contents



Published on

Introduction

I was working XML with python. I have to stored xml data in database(mdb). For that reason I opted to use DTO, for getting auto complete from language server. During this project, I ran into problems:

  1. XML scheme(xsd) was using custom date format month-day-year, and XML xs:date only supports day-month-year.
  2. Empty strings leaking into database

My approach

I immediately started with create two dto, one that maps to XML data, and other for database map (yaya ik i did not use orm). I used pydantic, because I was working with mdb(Microsoft access databases) which had poor error reporting. pydantic really saved my alot of time when data type mismatch occurs. while mdb just spits generic error message Expression has mismatched data type

This is sample XML file

<Project Name="hello-py" DateCreated="01-12-2026">
</Project>
import pydantic.dataclasses from dataclass
from datetime import date

@dataclass
class XMLProject:
    Name: str
    DateCreated: date

Now when xml attribute DateCreated was passed to DateCreated, it was str, as it was custom date format, I have to convert to python native date object

from datetime import datetime
xml_date_to_date(v: str):
    return datetime.strptime(v, "%m-%d-%Y").date()

Now modify class a bit, to convert str date to python date

@dataclass
class XMLProject:
    Name: str
    DateCreated: str # Initial make it string

    def __post_init__(self):
        DateCreated = xml_date_to_date(DateCreated) # Now override same object

This is it.

Overwrite class fields

Here is python vanilla class.

class A:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

I want to achive: When any field has value "" i.e empty string, then set it to None

class A:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

        # convert to dict
        for k,v self.__dict__.items():
            if v == "":
                setattr(self, k, None)

This is only solution worked for me.

You can access fields names self.__annotations__ or self.__class__.__annotations__, but did not working in this case, as I want to modify fields during object construction. Though __annotations__ do work after object construction.




Related Posts

Tags: