How to avoid magic string in class field_name in python, something like nameof() in c#

209 Views Asked by At

for example, in this python code.

from scrapy.loader import ItemLoader
from myproject.items import Product

def parse(self, response):
    l = ItemLoader(item=Product(), response=response)
    l.add_xpath('name', '//div[@class="product_name"]')
    l.add_xpath('name', '//div[@class="product_title"]')
    l.add_xpath('price', '//p[@id="price"]')
    l.add_css('stock', 'p#stock]')
    l.add_value('last_updated', 'today') # you can also use literal values
    return l.load_item()

How to avoid use 'name', 'price' as a string. there are any way to use, something like

 l.add_xpath(getname(Product.name), '//div[@class="product_title"]')
 l.add_xpath((getname(Product.price), '//p[@id="price"]')

Thanks

1

There are 1 best solutions below

4
On

By using getattr builtin function

 product = Product()
 l.add_xpath(getattr(product, 'name'), '//div[@class="product_title"]')