0

Say I have category="foo" and a NoSQL query={"category"=category}. Whenever I refactor my variable name of category, I need to manually change it inside the query if I want to adopt it.

In Python 3.8+ I'm able to get the variable name as a string via the variable itself.

Now I could use query={f"{category=}".split("=")[0]=category}. Now refactoring changes the query too. This applies to any database queries or statements (SQL etc.).

Would this be bad practice? Not just concerning Python but any language where this is possible.

TheRuedi
  • 122
  • 1
  • 7

1 Answers1

1

Would this be bad practice?

Yes, the names of local variables do not need to correlate with the fields in data stores.

You should be able to retrieve a record and filter on its fields with any python variable, no matter its name or if its nested in a larger data structure.

In pseudocode:

connection = datastore.connect(...)

# passing a string directly
connection.fetch({"category": "fruit"})

# passing a string variable
category_to_fetch = "vegetable"
connection.fetch({"category": category_to_fetch})

# something more exotic like a previous list of records
r = [("fish",)]
connection.fetch({"category": r[0][0]})

# or even a premade filter dictionary
filter = {"category": "meat"}
connection.fetch(filter)
ljmc
  • 4,830
  • 2
  • 7
  • 26