I have the following code with multiple cases:
def _extract_property_value(selector: Selector) -> str:
raw_value = selector.xpath("span[2]")
default_value = raw_value.xpath("./text()").get().strip()
value_with_a = ', '.join([value.strip() for value in raw_value.xpath("./a /text()").getall()])
value_with_div_and_a = ', '.join([value.strip() for value in raw_value.xpath("./div /a /text()").getall()])
if value_with_a:
return value_with_a
elif value_with_div_and_a:
return value_with_div_and_a
elif default_value:
return default_value
I want to get rid of if-statements and simplify this code as much as it is possible. I am not good Pyton dev. I know there is pattern "strategy" and below I was trying to implement that:
def _extract_property_value(selector: Selector) -> str:
raw_value = selector.xpath("span[2]")
values_dict = {
'default value': raw_value.xpath("./text()").get().strip(),
'value with a': ', '.join([value.strip() for value in raw_value.xpath("./a /text()").getall()]),
'value with div and a': ', '.join([value.strip() for value in raw_value.xpath("./div /a /text()").getall()])
}
return [item for item in values_dict.values() if item != ''][0]
but... Now when I think of this - that was bad idea to use strategy there. I am not sure. Can someone help me to simplify that code? Or those if-statements are just necessary.
dict
can be used to replace anif/elif/else
structure that is used for dispatch - i.e., depending on multiple possibilities for one value, choose a course of action. But you want to use the structure for fallback - depending on whether one course of action was productive, possibly try the next etc. For this, you want to iterate over a sequence (such as a list) of strategies. – Circosta