samedi 3 avril 2021

How to use a dictionary when an object is required as a keyword argument but dictionary values need to be passed?

I have some class Person with first_name, last_name, age attributes (this is just a simplified example, the actual class has >30 attributes).

class Person:
    def __init__(self, first_name=None, last_name=None, age=None):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        ...

I create an instance of this class and assign values to its properties. Later I use this object to fill in the data on the site I test.

person = Person(first_name="Alex",last_name="Kennedy", age=33 ...)

Later I modify some fields on the site with the help of dictionary. I use it because only two fields are needed to be changed (Actual object has >30).

fields = {
    "first_name": "Greg",
    "last_name": "Austin"
}

In a different module I use person object to compare its first_name with is what is actually in UI (person_name[1] is the first value from the list which I get with Selenium).

def open_view(self, person):
    assert first_name[1].lower() == person.name.lower()

The problem

The goal is to verify the final result, and for this I need to use open_view function. It is imported with module.

If I assign like this person=fields, I get the error, because person.first_name from my object is string and it cannot be assigned to a dictionary value.

AttributeError: 'str' object has no attribute 'first_name'

def check_result(self, person, fields):
    open_view(person=fields)

Person object needs to be passed, not dictionary. I cannot pass is like this person=fields["first_name"] because it will the same error.

If passing like open_view(fields["first_name"]) as expected the error occurs: TypeError: only named arguments are allowed but ('Greg',) positional arguments were passed

The question

How can I use a dictionary, so its values could be used in `open_view()` function?

Both structures values are strings.

I searched for similar questions and found that I can usenamedtuple for comparing my dictionary with object. But I do not clearly understand how to use it in this context. What are approaches that can be used? I will very very grateful for any suggests.

Aucun commentaire:

Enregistrer un commentaire