Global variable is not defined - Python

2020-02-07 03:02发布

问题:

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()

回答1:

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