Why are local variables made global?

If I create a function using blocks, any variables it uses are made into globals in the Python equivalent. Why is that? It’s setting a bad example - local variables should be local!

1 Like

Hi and welcome to the forums @quilkin!
I know the answer to your problem. “It’s not actually python, It’s just a translator.”
Hope it helps!

3 Likes

The only notion of local variables in the Blocks environment is function parameters; those are always local variables. All other variables in the Blocks environment are global variables, regardless of where they are used.

2 Likes

Yes, clearly what you say is true, as I have found. My question is - Why? It’s setting a bad example to anyone who ventures from block code to have a look at the generated Python - any text-based language (AFAIK) uses local variables in functions, for very good reasons.

1 Like

Thanks for your answer - but it doesn’t really matter if the ‘block’ code translates to Python or Javascript (or anything else!) - my question remains! Why not allow for local variables?

1 Like

The issue has been reported: https://github.com/microsoft/pxt-microbit/issues/3094 .

It’s possible that there’s a tradeoff between doing good support for locals and keeping the environment simple enough for novices to use. If so, maybe a simple environment was higher priority than support for locals.

My guess is that the behavior is a result of some compromises due to the typical uses of MakeCode, the need to support blocks+JavaScript+Python, and the evolution of MakeCode. Maybe a combination of:
a. Global variables are useful in many small, event-driven programs (they are used to communicate between functions), so it’s important to include support for them.
b. Block based languages don’t have a great way to designate local scope when variables are created and the drag-and-drop manipulation can easily undermine local scope. It also might be difficult to show scope to novices in block editors in a way they’d understand.
c. Due to the combination of (a) and (b), it makes some sense for block-based variables to default to being global.
d. Python support was added after JavaScript. Maybe there were some compromises to add in the Python support.
e. The translation process from blocks to Python could analyze variable scope and convert them to locals when possible, but that would actually be a slight change to the semantics of the block representation. In incomplete work, it may not even represent what the coder has in mind for how the variable will eventually be used! And when going back to blocks from Python, dragging a block could change the scope of a local to global. That could also lead to problems/confusion.

I’d suggest going to the non-MakeCode Python editor (https://python.microbit.org/v/3) when projects are complex enough for this to become important.

3 Likes