0

I've run into a similar problem as referenced here - Dynamic Method Call In Python 2.7 using strings of method names

Here's an example of what my working method call looks like, the method at the end is based on a given data type, in this case .string_value:

tag.fields[field["key"]].string_value = field["value"]

However I won't always be assigning just strings as there are methods for other data types. I attempted a solution similar to the one referenced in the linked thread:

typer = getattr(datacatalog_v1.types.TagField, f"{field['type']}_value")
tag.fields[field["key"]].typer = field["value"]

With typer being my new dynamic method call, but it's not working. I'm receiving this as an error - 'TagField' object has no attribute 'typer'.

Any suggestions?

knoll
  • 295
  • 6
  • 18

1 Answers1

1

This is quite interesting. I'm not sure what package/datatype ur working on, however it looks like you have 2 issues.

First, getattr returns a string, and you can't call a string, e.g. 'python'()

Second, if you remove the () after getattr(), typer will be a string data, and you cant use it like that. In

tag.fields[field["key"]].typer

typer must be a method/attribute of some sort rather than string. The best way is to build if statement or dict, combine different value of typer with different method/attribute calls.

type_methods = {'string_value': tag.fields[field["key"]].string_value, 
                'int_value': tag.fields[field["key"]].int_value, 
                'json_value': tag.fields[field["key"]].json_value} 
typer = getattr(datacatalog_v1.types.TagField, f"{field['type']}_value")
type_method[type] = field["value"]

update:

There is a setattr(object, name, value) function

typer = getattr(datacatalog_v1.types.TagField, f"{field['type']}_value")
setattr(tag.fields[field['key']], typer, field['value'])
Michael Hsi
  • 439
  • 2
  • 8
  • you modified ur question and removed () as I typed this XD, however second part should explain the 'TagField' object has no attribute 'typer' issue – Michael Hsi Apr 10 '20 at 21:17
  • Thanks @Michael. I see how your first solution would work, but there's got to be a simpler way than redefining all of the data type-specific methods. For reference I'm working with the Google Cloud Data Catalog API - https://googleapis.dev/python/datacatalog/latest/index.html – knoll Apr 10 '20 at 21:24
  • you reminded me, there is a setattr you can try. keep the typer = getattr() and do setattr(tag.fields[field["key"]], typer, field["value"]). Try and see if it works – Michael Hsi Apr 10 '20 at 21:41
  • This worked! setattr(tag.fields[field["key"]], f"{field['type']}_value", field["value"]) – knoll Apr 10 '20 at 22:00