Igor K.
Igor K.

Reputation: 877

Lua-style in Python

Variable a doesn't exist

I can write in Lua language:

a = (a or 0) + 1

Now a = 1

this allows me not to declare the variable "a" in advance. This is analog of

a = 0
a = a + 1

How can I do the same in Python?

a = (a or 0) + 1

P.S. Why is it important? To avoid assign zero to variables:

python (4 lines of code):

for ticker in ticker_list:
    total_volume[ticker] = 0

for a in range (1,10):
    total_volume[ticker] = total_volume[ticker] + a

lua (2 lines of code):

for a=1,9 do:
    total_volume[ticker] = (total_volume[ticker] or 0) + a

Upvotes: 2

Views: 210

Answers (2)

Nifim
Nifim

Reputation: 5031

Python does have a ternary operator, like Lua and many other languages

But unlike Lua, Python does not handle an undefined variable as a "false" value, it will throw an error if you attempt to evaluate an undefined variable. Specifically in your case you will get a key error for the key ticker not being present.

Lua Ternary:

    total_volume[ticker] = (total_volume[ticker] or 0) + a

Python Equivalent:

    total_volume[ticker] = (total_volume[ticker] if ticker in total_volume else 0) + a

Where Lua will pass you the value before the or if it is truthy, python will pass you the value before the if when the statement that follows is true, and the value after the else when it is false.

To safely evaluate if the key was in the dictionary we can use in.

This is mostly to demonstrate the ternary operation you were using in Lua and how to do it in Python, but that doesn't mean it is the right tool for this problem.


A cleaner solution I would suggest:

   total_volume[ticker] = total_volume.get(ticker, 0) + 1

It is less code and easier to reason about. get will return total_volume[ticker] or if the key is not present in the dictionary it will return the default value, 0.

Upvotes: 1

Gabio
Gabio

Reputation: 9494

For your use case, I would suggest to use defaultdict:

from collections import defaultdict

d = defaultdict(int)
d["counter"] += 5
print(d.items()) # output: dict_items([('counter', 5)])

BUT -

I don't think it's a good practice but you can use locals() or globals() to access variables dynamically in the desired scope:

a = 1
print(locals().get("a")) # ouput:1

c = locals().get("c", 2) + 1 
print(c) # output 3

Upvotes: 1

Related Questions