Issue defining global variables within functions

Open
#629 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
javascript, python
Domain
compilers

Research direction

No repository files or tests are named. Start by reproducing the two global-variable examples and inspecting the JavaScript generated for each, then trace the compiler behavior for Python global assignments and the globals() form. Done means either supporting the requested behavior with regression coverage or clearly documenting the supported workaround.

Written by the indexing model from the issue text.

Description

IS: limitation IS: workaround STATE: under consideration

Hi! It's me again =]

I'm having an issue in my pyp5js project releated to not being able to create new global variables from inside a function. For example, the following pure Python code works:

def foo(): 
    global x 
    x = 30 
    print(x) 

foo()                                                                   
>>> 30

But if an equivalent version to be browser, such as the following example, doesn't:

def foo():
    global my_var
    my_var = 10
    console.log(my_var)

foo()

The error I get from the browser console is: ReferenceError: assignment to undeclared variable my_var at line 3. But, if I declare the global variable my_var outside the foo function, it works and prints "10" in the console:

my_var = None

def foo():
    global my_var
    my_var = 10
    console.log(my_var)

foo()

Studying transcrypt's docs, I got to this page about the use of globals function and then I tried the following example, which didn't work either:

# __pragma__ ('xglobs')

def foo():
    globals () ["my_var"] = 10
    console.log("inside function", my_var)

foo()
console.log("outside function", my_var)

This one raises a ReferenceError: my_var is not defined at line 3 as well.

So, I'd like to know if is there'a way to respect regular Python's usage of global or, given the restrictions of compiling the code to JS, to use global variables should I have to declare them at the beginning of the module, before assigning values?

Dominant language
Python
Stars
2.9k
Forks
218
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from TranscryptOrg/Transcrypt

All issues in TranscryptOrg/Transcrypt

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.