Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable is not defined - Python

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()
like image 299
Milano Avatar asked Jan 30 '15 14:01

Milano


People also ask

Why global variable is not defined Python?

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.

Why is my global variable undefined?

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.

How do you declare a global variable in Python?

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.

How do you define a global variable?

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.


1 Answers

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
like image 174
Kevin Avatar answered Oct 05 '22 03:10

Kevin