0

Hi I am kinda new to using locals(), I did research that locals() means treat a variable within a function as a dictionary. We have a bunch if this function with the same function of locals() below. I am man of DRY principle but in this area its not. How will I simplify this or any alternative way?

def home_creation(self, property, item):
    def date(data):
        return data
    def rate(data):          
        return data

    if property in locals():
        return locals()[property](item)
    else:
        return None
Bry
  • 21
  • 1
  • 2

1 Answers1

0

You can define your own dictionary to limit the permitted methods for use:

def home_creation(self, property, item):
    def date(data):
        return data
    def rate(data):          
        return data

    functions = {
        'date': date,
        'rate': rate
    }

    return functions.get(property, lambda: None)(item)
Uriel
  • 15,579
  • 6
  • 25
  • 46