6
votes

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
Have you tried working around this by passing 'b' into the functions? It's generally preferred over using global anyway. What is b anyway? Is it a class? - oxrock
Yes it is an object of a class. I can't do that, because function search is not visibly called. I don't know how to pass the b to the search function. - Milano

1 Answers

15
votes
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