1

I'm trying to refactor some code to be DRY

I have an importer that imports from an API that has keys that are different than the destination.

Working code looks like this:

this_event = AnEvent()
wp_event = Requests.get('someurl').json()
if 'title' in wp_event.keys():
    this_event.name = wp_event['title']
if 'description' in wp_event.keys():
    this_event.description = wp_event['description']
... and so on

What I am trying to do is this:

scrape_fields  = [
    {
        'wp' : 'description',
        'django' : 'description'
    },
    {
        'wp' : 'title',
        'django' : 'name'
    }
    ... etc
]
for field in scrape_fields:
    if field['wp'] in wp_event.keys():
        # I knew this would not work when I wrote it but not sure what to do
        this_event[field['django']] = wp_event[field['wp']]

But Django throws an exception:

'AnEvent' object does not support item assignment

Is anyone able to advise on how to assign to a field dynamically like this?

1
  • Are there any duplicated 'wp's or 'django's values? If not we can boost performance of this. Commented Jul 1, 2018 at 20:03

2 Answers 2

2

To dynamically assign any Python object's member values using str type values to reference the field name you need to use Python's built-in function setattr. Essentially, this line:

this_event[field['django']] = wp_event[field['wp']]

Can be rewritten to this, using setattr:

setattr(this_event, field['django'], wp_event[field['wp']])

Read: Python docs.

Sign up to request clarification or add additional context in comments.

Comments

1

You want setattr():

setattr(this_event, field['django'], wp_event[field['wp'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.