I got a code from the internet for my project, and there is a function with parameter that i need to make change of global variable value
it is a flask request json app, i use the ifttt to send json to this project. i've tried to change by this code but it won't change, the X always in 1
X=1
#app.route('/',methods=['POST'])
def index():
req = request.get_json(silent=True, force=True)
val = processRequest(req)
#print(val)
r = make_response(json.dumps(val))
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
device = req['device']
state = json.loads(req['state'])
#print(state)
if (device=='bedlamp'):
global()['X']=int(30)
i want it when the ifttt send device bedlamp, the value of global variable turn to 30, can anybody help me?
To change a global variable called X inside a function you have to do:
1) bring the variable into the function scope
global X
2) change its value
X = 30
so:
def abc():
global x
x = 30
You need to use the global keyword, like this:
def processRequest(req):
device = req['device']
state = json.loads(req['state'])
if (device=='bedlamp'):
global X
X = 30
Related
I have a file myfunctions.py in directory mypythonlib
from requests_html import HTMLSession
import requests
def champs_info(champname:str, tier_str:int):
url = f"https://auntm.ai/champions/{champname}/tier/{tier_str}"
session = HTMLSession()
r = session.get(url)
r.html.render(sleep=1, keep_page=True, scrolldown=1)
information = r.html.find("div.sc-hiSbYr.XqbgT")
sig = r.html.find('div.sc-fbNXWD.iFMyOV')
tier_access = information[0]
tier = tier_access.text
I want to access the variable tier through another file- test_myfunctions.py
but the thing is I also have to give parameters to the function champs_info so that it could access the url accordingly.
from mypythonlib import myfunctions
def test_champs_info():
return myfunctions.champs_info("abomination",6).tier
But while running this code, I am getting the error-
./tests/test_myfunctions.py::test_champs_info Failed: [undefined]AttributeError: 'NoneType' object has no attribute 'tier'
def test_champs_info():
> return myfunctions.champs_info("abomination",6).tier
E AttributeError: 'NoneType' object has no attribute 'tier'
tests/test_myfunctions.py:3: AttributeError
Any Solution for this and why is this code not able to access the variable?
I wrote myfunctions.champs_info("abomination",6).tier in hope for that it's gonna take the tier variable from the champs_info function while giving it the parameters required all from the myfunctions file :(
You can access the value of a variable in a function by 1) returning the value in the function, 2) use a global variable in the module, or 3) define a class.
If only want to access a single variable local to a function then the function should return that value. A benefit of the class definition is that you may define as many variables as you need to access.
1. Return value
def champs_info(champname:str, tier_str:int):
...
tier = tier_access.text
return tier
2. global
tier = None
def champs_info(champname:str, tier_str:int):
global tier
...
tier = tier_access.text
Global tier vairable is accessed.
from mypythonlib import myfunctions
def test_champs_info():
myfunctions.champs_info("abomination", 6)
return myfunctions.tier
print(test_champs_info())
3. class definition:
class Champ:
def __init__(self):
self.tier = None
def champs_info(self, champname:str, tier_str:int):
...
self.tier = tier_access.text
test_functions.py can call champs_info() in this manner.
from mypythonlib import myfunctions
def test_champs_info():
info = myfunctions.Champ()
info.champs_info("abomination", 6)
return info.tier
print(test_champs_info())
In myfunctions.champs_info() add a return tier
and in the script test_myfunctions.py remove .tier
You just have to return tier from champs_info() function
Just like this:
myfunctions.py
from requests_html import HTMLSession
import requests
def champs_info(champname:str, tier_str:int):
url = f"https://auntm.ai/champions/{champname}/tier/{tier_str}"
session = HTMLSession()
r = session.get(url)
r.html.render(sleep=1, keep_page=True, scrolldown=1)
information = r.html.find("div.sc-hiSbYr.XqbgT")
sig = r.html.find('div.sc-fbNXWD.iFMyOV')
tier_access = information[0]
tier = tier_access.text
return tier # <---- Focus Here
test_myfunctions.py
import myfunctions
print(temp.champs_info("americachavez", 6))
Just it. You're done.
I want to be able to establish a variable with no value in order to fill it in at a later point in my code, based upon the output of another function.
Ex:
variable = ""
...20 lines later...
if function() is 10:
variable = "10"
else:
variable = "5"
print(variable + 20)
Here's my code so far:
yahoo = "smtp.mail.yahoo.com"
hotmail = "smtp.live.com"
def smtpServer():
if "#yahoo.com" in username:
server = smtplib.SMTP(yahoo,587)
if "#hotmail.com" in username:
server = smtplib.SMTP(hotmail,587)
else:
pass
def check():
try:
server.connect(server)
server.login(username,password)
server.quit()
line = f.readline()
cnt = 1
while line:
#UserAndPass = str.split(':') #check login
UserAndPass = line.split(':')
username = str(UserAndPass[0])
password = str(UserAndPass[1])
cnt += 1
server = ""
smtpServer()
check()
With what I have now, I keep getting errors saying that it's undefined, so I'm just not sure how to define it for this purpose. Thank you!
If you want to refer a global variable from within a function, you need to declare it using global yahoo or global hotmail in your function. You also need to declare global server in the functions setting and using the server.
You don't need to initialize the variable to an empty value for this to work.
However, your approach of hardcoding the mail servers for mail addresses is completely broken. Use the MX records provided by the domain name system, they're there for a reason.
Use this for making an empty variable:
variable = None
For your code, you can use server = None.
I am writing a code for a project in particle physics (using pyroot).
In my first draft, I use the following line
for i in MyTree:
pion.SetXYZM(K_plus_PX, K_plus_PY, K_plus_PZ,K_plus_MM)
This basically assigns to the pion the values of variables in the parenthesis, ie momenta and inv. mass of the kaon.
Physics aside, I would like to write a function "of the form":
def myfunc(particle):
return %s_PX % particle
I know this is wrong. What I would like to achieve is to write a function that allows, for a given particle, to set particle_PX, particle_PY etc to be the arguments of SetXYZM.
Thank you for your help,
B
To access class attributes from string variables you can use python's getattr:
import ROOT
inputfile = ROOT.TFile.Open("somefile.root","read")
inputtree = inputfile.Get("NameOfTTree")
inputtree.Print()
# observe that there are branches
# K_plus_PX
# K_plus_PY
# K_plus_PZ
# K_plus_MM
# K_minus_PX
# K_minus_PY
# K_minus_PZ
# K_minus_MM
# pi_minus_PX
# pi_minus_PY
# pi_minus_PZ
# pi_minus_MM
def getx(ttree,particlename):
return getattr(ttree,particlename+"_PX")
def gety(ttree,particlename):
return getattr(ttree,particlename+"_PY")
def getz(ttree,particlename):
return getattr(ttree,particlename+"_PZ")
def getm(ttree,particlename):
return getattr(ttree,particlename+"_MM")
def getallfour(ttree,particlename):
x = getattr(ttree,particlename+"_PX")
y = getattr(ttree,particlename+"_PY")
z = getattr(ttree,particlename+"_PZ")
m = getattr(ttree,particlename+"_MM")
return x,y,z,m
for entry in xrange(inputtree.GetEntries()):
inputtree.GetEntry(entry)
pion1 = ROOT.TLorentzVector()
x = getx(inputtree,"K_plus")
y = gety(inputtree,"K_plus")
z = getz(inputtree,"K_plus")
m = getm(inputtree,"K_plus")
pion2.SetXYZM(x,y,z,m)
x,y,z,m = getallfour(inputtree,"pi_minus")
pion2 = ROOT.TLorentzVector()
pion2.SetXYZM(x,y,z,m)
As linked by Josh Caswell, you can similarly access variable names:
def getx(particlename):
x = globals()[partilcename+"_PX"]
though that might get nasty quickly as of whether your variables are global or local and for local, in which context.
Hi I'm a beginner programmer. I don't know how can I call a variable from function.
I have two def calcular() and guardar(). I get some variables from calcular() that I will call later, but when I call variables in guardar(), it tells me that variable is not defined. I tried making global var, but it doesn't work. Hope you can help me
This is a little of my code...
def calcular():
if nClient == "":
texto = ("Inserta Numero de cliente")
ventanaMensaje(texto)
else:
if cl1=="":
texto = ("Inserta Clave")
ventanaMensaje(texto)
else:
if aB1 == "":
texto = ("Inserta Cantidad")
ventanaMensaje(texto)
else:
try:
clt = open("preciosEsp.txt","r+")
lClt = clt.readlines()
rClt = lClt[0]
sClt = rClt.split("'")
nRClt = sClt[0]
if nClient == nRClt:
cReg=sClt[1]
if cl1== cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
else:
x = 0
while nClient != nRClt:
rClt = lClt[x]
sClt = rClt.split("'")
nRClt = sClt[0]
x=x+1
if nClient == nRClt:
cReg=sClt[1]
if cl1==cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
indice=int(prc)+3
pdcts = open("productos.txt","r+")
lPdcts = pdcts.readlines()
rPdcts = lPdcts[0]
sPdcts= rPdcts.split("'")
nPdcts = sPdcts[0]
t = 0
if cl1 == nPdcts:
precio1=sPdcts[indice]
global txtD1################## MAKE A GLOBAL VAR
txtD1=sPdcts[1] #### THIS IS THE VARIABLE ########
def guardar():
guardarDatos = (n+txtD1) ################# I CALL HERE, BUT TELL ME THAT VARIABLE IS NOT DEFINED
If you really want a global variable, you'd define it outside of any function
txtD1 = None
def calcular():
...
it will then exist at module level. However, globals are rarely (read: never) the solution you should be using, instead you should be returning information from functions rather than modifying global state. You'd then pass that information into another function to use.
The global keyword in python says that you are referencing a global variable, not creating a new one. However, in your code no such name exists, so you're not actually referencing anything.
first create your "database" somewhere global
clt = dict(map(lambda x:x.split(" ",1),open("preciosEsp.txt","r+"))
now you can acess it anywhere with
clt.get(nClient)
next calcular should return the values you want
def calcular():
...
precio = clt.get(nClient)
return [precio,nClient,...]
then you would store the returned values (or do something with them as soon as they are returned )
I am trying to store a value in a module level variable for later retrieval.
This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment
What am I doing wrong here?
ICS_CACHE = None
def ical_feed(request):
if request.method == "POST":
response = HttpResponse(request.POST['file_contents'], content_type='text/calendar')
response['Content-Disposition'] = 'attachment; filename=%s' % request.POST['file_name']
ICS_CACHE = response
return response
elif request.method == "GET":
return ICS_CACHE
raise Http404
I constructed a basic example to see if a function can read module constants and it works just fine:
x = 5
def f():
print x
f()
---> "5"
Add
global ISC_CACHE
as the first line of your function. You are assigning to it inside the function body, so python assumes that it is a local variable. As a local variable, though, you can't return it without assigning to it first.
The global statement lets the parser know that the variable comes from outside of the function scope, so that you can return its value.
In response to your second posted example, what you have shows how the parser deals with global variables when you don't try to assign to them.
This might make it more clear:
x = 5 # global scope
def f():
print x # This must be global, since it is never assigned in this function
>>> f()
5
def g():
x = 6 # This is a local variable, since we're assigning to it here
print x
>>> g()
6
def h():
print x # Python will parse this as a local variable, since it is assigned to below
x = 7
>>> h()
UnboundLocalError: local variable 'x' referenced before assignment
def i():
global x # Now we're making this a global variable, explicitly
print x
x = 8 # This is the global x, too
>>> x # Print the global x
5
>>> i()
5
>>> x # What is the global x now?
8