pythonfunctionargumentsarcgisesri

How do I pass in a parameter name into a function as an argument in python?


How do I pass in a parameter name into a function as an argument?

def edit_features_retry(editType,data):
    AGOLlayer.edit_features(editType=data)

edit_features_retry("adds", datalayer)

error:

TypeError: edit_features() got an unexpected keyword argument 'editType'

If I do it this way as a string:

def edit_features_retry(editType,data):
    AGOLlayer.edit_features(editType=data)

edit_features_retry(adds, datalayer)

error:

NameError: name 'adds' is not defined

Solution

  • You can use dictionary unpacking.

    Here's a simple example:

    def f(a = 1, b = 2):
      print(f"{a = }, {b = }")
    
    f(b=5)  # output: "a = 1, b = 5"
    
    kwargs = {"b": 5}
    f(**kwargs)  # output: "a = 1, b = 5"
    

    Which can be applied to your scenario:

    def edit_features_retry(editType, data):
        AGOLlayer.edit_features(**{editType: data})
    
    edit_features_retry("adds", datalayer)