3

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
asked Sep 24, 2018 at 17:40
2
  • 1
    Where is FOO defined in 2nd code?, and what error you are getting?? Commented Sep 24, 2018 at 17:42
  • 1
    Let me preempt the next question - You probably want to return the value (e.g. return nhcparams.FOO['Price']) because you won't be able to access my_price outside get_max_price(). Commented Sep 24, 2018 at 17:48

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Exactly what I needed. Thank you. Upvoted, but don't have 15 Rep yet.
3

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

3 Comments

Did you try this?
@chepner juss changes its typo
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.