KugelBlitz
KugelBlitz

Reputation: 167

How to pass a string into a function such that it behaves as a variable/property inside?

I am writing a function such that it takes values from MongoDB into a dataframe. In the mongo dump, I have a lot of supplier names and they follow the format "db.suppliername_properties", where suppliername is variable such as taap, hotelbeds, ean etc. I then do further operations on each dataframe.

I have something like:

    client = MongoClient()
    db = client["supplier_static_database"]
    prop_1 = pd.DataFrame(list(db.taap_properties.find()))
    prop_2 = pd.DataFrame(list(db.hotelbeds_properties.find()))
    .
    .
    .
    prop_n = pd.DataFrame(list(db.<suppliername_n>_properties.find())

Here I want to write a function that will take a supplier name as a string (the user would input something like "taap" or "hotelbeds") and then do the necessary to extract the database and do some operations. Something such as:

def func(supplier_name, db, ...):
    prop = pd.DataFrame(list(db.supplier_name.find()))
    #do some operations
    return prop

Here supplier_name is a string provided by a user. How can I go from a users string input to using it as a variable/property? Is that possible in python? Or is there a workaround I can implement?

Upvotes: 0

Views: 46

Answers (1)

chepner
chepner

Reputation: 531345

Just use getattr to fetch a constructed attribute.

supplier = getattr(db, supplier_name + "_properties")
prop = pd.DataFrame(list(supplier.find()))

Upvotes: 2

Related Questions