-2

I'm having difficulty accessing a variable.

I'm working toward the following, calling python script from bash, with arguments, which then imports a function defined in a second python script, executes it and thereby creates a variable which will be used later in the first python script.

At the moment,to test I'm copying and pasting directly into a Python terminal some commands like this:

from script2 import *
foofunction(arg)
print(newlist)

The foo function defined in script2 is executing, I can see files have been written but when I try to print the list supposedly created while executing the imported function, I get a message telling me it's undefined.

Inside my script2.py, i made sure to enter a statement global newlist before defining its length and populating it.

I'm scratching my head at this stage.

Tamara Koliada
  • 1,200
  • 2
  • 14
  • 31
curly
  • 43
  • 1
  • 7
  • 3
    Please include the relevant code from script2.py :) – KuboMD Jan 18 '19 at 16:08
  • 2
    Why don't you `return newlist` in that function and assign it to a variable? – Graipher Jan 18 '19 at 16:08
  • 1
    The `global` keyword does not work that way in python. Have a look [here](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Valentino Jan 18 '19 at 16:11
  • I don't know why that didn't work when I tried it last night, but Graipher's solution is exactly correct. IF you want to throw that into an answer I'll gladly accept it. – curly Jan 18 '19 at 16:18
  • 2
    `from some_module import *` is rarely a good practice as it mangles up your namespace. This is a prime example - without the knowledge of `script2.py` we have no idea whether `foofunction` and `newlist` would be a `NameError` or an object that was defined in `script2.py`. It's best to be *explicit*. – r.ook Jan 18 '19 at 16:19

1 Answers1

-2

You should refer to newlist and the module where it is defined like this:

from script2 import *
foofunction(arg)
print(script2.newlist)
nacho
  • 5,280
  • 2
  • 25
  • 34