I have a problem with global variable. It returns error
search = Search.Search(pattern,b)
NameError: global name 'b' is not defined
But I have already defined this global variable. I tried to put it even into the search function. I think that there was no problem with that on Windows. I'm trying to run this program on Linux/Unix.
Do you have any advice how to avoid this error?
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import render_template
import Search
import B
app = Flask(__name__)
global b
@app.route('/')
def my_form():
return render_template('my-form.html')
def setup():
global b
b = B.B()
@app.route('/', methods=['POST'])
def search():
global b
from time import time
pattern = request.form['text']
...
se = Search.Search(pattern,b)
...
...
...
app.debug=True
if __name__ == '__main__':
setup()
app.run()
You have to use global df inside the function that needs to modify the global variable. Otherwise (if writing to it), you are creating a local scoped variable of the same name inside the function and your changes won't be reflected in the global one.
The reason the first alert is undefined is because you re-declared global as a local variable below it in the function. And in javascript that means from the top of the function it is considered the local variable.
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
app = Flask(__name__)
global b
The global b
statement here does not actually create a variable for you. You need to assign something to it yourself.
app = Flask(__name__)
b = None #or whatever you want the starting value to be
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With