Search code examples
python-3.xattributespython-dataclasses

How to use default value if None using attr


I have currently managed to find an issue where I am not able to solve. I am currently working with attr.ib where I am trying to figure out how I can use the default value if we send the value None to the dataclass.

This is what I have done

test.py

from test2 import Data

test = Data(image=None)
print(test)

# ---------------- #

test2 = Data()
print(test2)

>>> Data(image=None)
>>> Data(image='https://i.imgur.com/R7mqXKL.png')

test2.py

from typing import Optional

import attr


@attr.dataclass
class Data:
    image: Optional[str] = attr.ib(default="https://i.imgur.com/R7mqXKL.png")

I wonder how I can print out the default value instead if we pass in the value None to the dataclass?


Solution

  • After investigation. I was able to find attr documentation: https://www.attrs.org/en/stable/api.html#attrs.converters.default_if_none