Home > Software engineering >  How to stop functions from giving errors when using variables not defined in the function?
How to stop functions from giving errors when using variables not defined in the function?

Time:12-01

I am creating several experiments in python and have various functions which will be common across these experiments. I thus wanted to create a script only containing these functions which I could import at the beginning of the experimental script to avoid half of the script being taken up with 'generic setup lines'.

So far, I have created the functions and the script and can import them and use them. For example, in the following, I have a function which shows a blank screen which takes the duration I want (e.g., 4 seconds) and displays it on the window defined in the experimental script.

import functions 
win = visual.Window([1440,900], color=[-1,-1,-1], fullscr=True)
dur = 4
functions.blank_screen(duration=dur)

This all works fine but in the script containing the functions, there are several 'errors' the function uses the variable 'win' which is not defined in the function:

def blank_screen(duration):
    blank = TextStim(win, text='')
    blank.draw()
    win.flip()

But when I run the experimental script, as it is defined in the script, it all works. How can I get around this? I have this problem with several functions as a large majority uses variables which are defined in the experimental script and not in the functions. As I say, it all works but just annoys me that the script is covered in 'errors'!

I'd be greatly appreciative of any help, thank you!

CodePudding user response:

You can pass on the win you want blanked out as an argument to the blank_screen function:

import functions 
win = visual.Window([1440,900], color=[-1,-1,-1], fullscr=True)
dur = 4
functions.blank_screen(duration=dur, win=win)

and

def blank_screen(duration, win):
    blank = TextStim(win, text='')
    blank.draw()
    win.flip()
  • Related