Simple NOOB question, but after an hour of searching I still can't find it. In Python 3.6 I've got a working module nhcparams with a dictionary, FOO. The following code is tested and works:
import nhcparams
def get_max_price():
my_price = nhcparams.FOO['Price']
I'd like to change it to:
import nhcparams
def get_max_price(ARG):
my_price = nhcparams.ARG['Price']
get_max_price(FOO)
That doesn't work, which I am hoping is just a syntax problem on my end. Any help getting me past my idiocy would be appreciated :)
Aran-Fey
44.1k13 gold badges113 silver badges161 bronze badges
2 Answers 2
You can use the getattr function to dynamically access attributes in your module:
import nhcparams
def get_max_price(ARG):
my_price = getattr(nhcparams, ARG)['Price']
get_max_price('FOO')
Notice that 'FOO' needs to be passed as a string. And the attribute is returned from the getattr function call
answered Sep 24, 2018 at 17:43
Kevin K.
1,4272 gold badges15 silver badges19 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Graham Porter
Perfect. Exactly what I needed. Thank you. Upvoted, but don't have 15 Rep yet.
Try this
import nhcparams
def get_max_price(ARG):
my_price = ARG['Price']
# Do stuff
get_max_price(nhcparams.FOO)
answered Sep 24, 2018 at 17:43
kartheek
6,7343 gold badges44 silver badges42 bronze badges
3 Comments
chepner
Did you try this?
kartheek
@chepner juss changes its typo
SethMMorton
With the edit this is much better. Depending on whether the OP always wants to get the value from
nhcparams or wants to be flexible about the module then this may or may not be better than the getattr method.lang-py
returnthe value (e.g.return nhcparams.FOO['Price']) because you won't be able to accessmy_priceoutsideget_max_price().