Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Variable fail do detect global scope #3728

Closed
werlang opened this issue Mar 9, 2020 · 3 comments
Closed

Variable fail do detect global scope #3728

werlang opened this issue Mar 9, 2020 · 3 comments
Labels
component: generators issue: bug Describes why the code or behaviour is wrong

Comments

@werlang
Copy link

werlang commented Mar 9, 2020

In python, when updating a variable set in global scope, you need to use the global keyword, or it will give an error. In blockly, I see no way of updating a variable previously set in another scope, such as in the example.

image

The above blocks generate the following code:

bar = 0
def foo():
    bar = bar + 1
    print(bar)
foo()

Which give the following error when run:

Traceback:
File "answer.py", line 3, in foo
bar = bar + 1
File "answer.py", line 5
foo()
UnboundLocalError: UnboundLocalError: local variable "bar" referenced before assignment on line 3

The correct code generated to avoid this error and run according to the intent is:

bar = 0
def foo():
    global bar
    bar = bar + 1
    print(bar)
foo()
@werlang werlang added issue: triage Issues awaiting triage by a Blockly team member issue: bug Describes why the code or behaviour is wrong labels Mar 9, 2020
@NeilFraser NeilFraser added component: generators and removed issue: triage Issues awaiting triage by a Blockly team member labels Mar 9, 2020
@NeilFraser
Copy link
Contributor

I've never seen that 'define' block before. Where does that block come from? It's badly programed if it doesn't use "global".

For reference, the blocks that come with Blockly behave correctly:
https://blockly-demo.appspot.com/static/demos/code/index.html#mciwtq

bar = None

def foo():
  global bar
  bar = bar + 1
  print(bar)

bar = 0
foo()

@werlang
Copy link
Author

werlang commented Mar 9, 2020

Oh yes, my bad. The block was not correctly programmed.

Can you please direct me to a somewhere that shows how to program such a custom procedure blocks, while adding global keyword to variables?

@NeilFraser
Copy link
Contributor

No problem. Here's the code for the Python generator on the default procedure block:
https://github.com/google/blockly/blob/master/generators/python/procedures.js#L29

The first thing it does is handle global variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: generators issue: bug Describes why the code or behaviour is wrong
Projects
None yet
Development

No branches or pull requests

2 participants