How to declare a global variable in python

I am really looking into phase in python and I didn't get help from google either, so guys please help me about global variable on specific requirement.

I am using python 3.5 on ubuntu OS 16.04 and I have to declare a global variable in one file and initialize with default and import it in another python file in the same package, but when I declare this and import, I get the following error in that file, where the global variable is imported:

AttributeError: "App.views" module has no "request_dict" attribute

Don't worry, I have the code below:

views.py:

from collections import OrderedDict

request_dict = OrderedDict()

def hello():
    print("hello from views file")

      

task.py:

from . import views

def addQueueTask():
    print('from task.py: ', views.request_dict)

      

+3


source to share


3 answers


Have you tried making a file that is just a function file like: funtions.py:

p = print
i = input

      

then move that file to your python installation folder. Where are python shell and idle. Then, in any other file, you can:



from functions import p
p('hi')

      

then this code will return 'hi'

+1


source


You can declare a gloabl variable using the "global" keyword in front of the variable name



0


source


from views import *  

      

imports all objects and methods from views

. However, this is actually something you shouldn't do.

Please look

from views import request_dict

      

to only import the variables you need and avoid polluting your namespace.

-1


source







All Articles