0

Let's say I have a python Dataclass:

@dataclass
class Person:
    name: str
    age: int  
    married: bool

And I add data to the fields say from an imaginary dictionary:

for row in something:
    ob = Person(
        name=row.name,
        age=row.age,
        married=row.married,
     )

How do I, for example, make name equal to None or an empty string if name is not given in the imaginary dictionary?

I tried something like:

name = row.name if row.name else None

but I got an Attribute error like: AttributeError: object has no attribute 'name'

Edit: I want to achieve this without necessarily setting the fields in the Person dataclass to None

PercySherlock
  • 371
  • 1
  • 2
  • 12
  • 3
    If it was an imaginary *dictionary*, you'd use `row['name']`, and if that key didn't exist, you'd use `row.get('name')` to get the desired effect. With any random object, the equivalent is `getattr(row, 'name', None)`. – deceze May 10 '21 at 15:26
  • The attribute error is the real problem. What is the type of `row` here? If it's a dictionary you could try `name = row['name'] if 'name' in row else None` – h0r53 May 10 '21 at 15:28
  • @h0r53 `row.get('name')` already encapsulates that pattern. – deceze May 10 '21 at 15:29
  • @deceze I solved it with `getattr(row, 'name', None)`. Thank you! – PercySherlock May 10 '21 at 15:41
  • @h0r53 @Rivers `row` is a namedTuple. – PercySherlock May 10 '21 at 15:55

0 Answers0