0

I have a Python question that is more syntax related than anything else. I know that you can access variables dynamically with evaluate, like so, which is useful in a function:

def price_checker(coin):
    if float(eval(coin + 'price')) >= 5:
         do_something

This logic has been working very well for me. I have hundreds of variable names, updated constantly through API requests in hundreds of threads. My main loop compares prices with my trading strategy to see what fits the criteria through the usage of functions. An example of the code that would be accessed is:

BTCUSDTprice = 7000
ETHUSDTprice = 500

I would then call the function and input whatever coin matched a previous criteria to then check its price, along with some other variables named like so. I am now trying to accomplish the same thing with arrays. I would have an array, like so:

BTCUSDTclosingpricearray = [7000, 7010, 10, 5000000]
ETHUSDTclosingpricearray = [500, 600, 1000, 600]

I need to be able to access these arrays dynamically in the very same way that I access variables, and changing my method to do so is not an option, as all of the functions are already created and must stay as they are. With the usage of functions, how can I dynamically access these variables based on function parameters in a way similar to how I access variables with function parameters? Thank you all in advance. This is very much appreciated.

2
  • 2
    you should use a dictionary not loads of variables Commented Jun 9, 2018 at 16:20
  • 1
    You almost never should use dynamic variable names. There are dict for that. If you want to ever use this code again and maybe even in production, rewrite it. Commented Jun 9, 2018 at 16:20

1 Answer 1

2

What you have is a name-to-value- or name-to-values-mapping. The solution for that is a dictionary:

prices = {
    "BTC": 7,
    "EDT": 10.5,
}
price_array = {
    "Something": [1, 2, 3, 4],
}

and then you can use prices[coin], or with lists price_array[coin][index].

If you really want to access variables, you can use globals():

a_price = 1
b_price = 2
globals()[coin + "_price"]

This is a bad idea in an API, since you give the API-caller access to your internal variables. May end badly.

And you should definitely not use the abomination with eval(), since that actually executes that user-supplied string as code. Will end badly. If you insist, adding "[index]" to the end of youreval`ed string is not that hard. Just a bad idea.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.