I get this error "NameError: name 'destinataires' is not defined" when I call a function inside 2 level functions:
I get an error even if I declare it as a global variable in the function:
def PostToFaceBookWall(msg):
global destinataires
try:
....
except Exception as e:
subject = 'xxxxxxxxxxx'
error = str(e)
SendMail(destinataires,subject,error)
def get_prices_for_next_days():
....
subject = "xxxxx")
html = "xxxxxx"
SendMail(destinataires,subject,html) # NO PROBLEM WITH THIS INSTRUCTION : I GET MAIL
PostToFaceBookWall(Msg2FB) # PROBLEM WITH THIS INSTRUCTION : I GET ERROR
def SendMail(dest,sujet, msg):
"""Send a mail"""
if __name__ == '__main__':
destinataires = ['xxxxx#xxxx.xxx'] #a global variable
get_prices_for_next_days()
Is level inclusion function limited?
A global variable defined in a function is not known inside sub function called?
I think you have to pass destinataires to get_prices_for_next_days() function
You cant accesses the destinataires in get_price_for_next_day() function with out passing
Related
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 1 year ago.
Sorry for the beginner question. In the below code, the output I'm getting is "Original" and not "Function". Doesn't the value of name change after passing through the function? Thanks
global name
name = "Original"
def test():
name = "Function"
test()
print(name)
Use the global keyword in the function.
name = "Original" # define name
def test(): # define our function
global name # this function can now change name
name = "Function" # change the value
test() # run the function
print(name) # returns Function
I'd assume global needs to be in the function so you could do something like this, where a function can use text without effecting the text var:
text = "Original"
def test():
global text
text = "Function"
def printText(text):
textToPrint = text # use text var without any issues in this function
print(textToPrint)
test()
print(text)
global declarations go inside the function you want to apply them to, not at the top-level.
name = "Original"
def test():
global name
name = "Function"
test()
print(name)
name = "Original" #global variable
def test():
#to update the global value you have to declare it here
global name
name = "Function"
test()
print(name)
you can read more about it here, https://www.programiz.com/python-programming/global-keyword
I have declared global variable in function a
def a():
global my_var
my_var = 3
If I want to read this variable from function main, everything works
if __name__ == "__main__":
main()
def main():
print(my_var)
Output:
3
However I have another function b, where the var is not defined
def b():
try:
random_numbers = (random.sample(range(1, my_var), 2))
except Exception as e:
print(e)
Output:
NameError: name 'my_var' is not defined
Could someone explain me, why in function main I can access my_var, while in another it is not defined? How can I solve this problem?
I'm writing a program in selenium python. I pasted here part of the code from my program (I did not paste all the code because it has 800 lines) with the UnboundLocalError error: local variable 'i' referenced before assignment, the error occurs exactly at i += 1.
global i
i = 0
odpowiadanieobserwowaniestronfb0()
def odpowiadanieobserwowaniestronfb0():
if i > ileraz:
driver.quit
skonczono()
'''
try:
testt = driver.find_element_by_xpath('')
except Exception:
odpowiadanieobserwowaniestronfb1()
zleskonczono1()
'''
def odpowiadanieobserwowaniestronfb1():
i += 1
global keyword tells the function, not the whole module / file, what variables should be considered declared outside the scope of the said function. Try this:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
There are two options:
You can use your global variable:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
or you pass the i to the function:
def odpowiadanieobserwowaniestronfb1( i ):
return i += 1
Handling a NameError is raising a SyntaxError:
So I'm making a decorator function which associates a generator-function to a dictionary, with the intention of making the send() function less cumbersome to use.
The default behavior is to use a dictionary named global_registry_dict defined in (surprise!) the global-namespace.
If global_registry_dict does not exist and an alternative dictionary is not explicitly passed in, NameError is raised by python.
When I try to handle the error by creating the variable in the global namespace, I get a SyntaxError telling me that the variable is referenced before assignment. That makes sense...but...like...that's what I'm trying to fix!
Any help would be greatly appreciated!
Source for the Decorator:
def make_stateless_actor(func):
def wrapper(registry_dict=None, *args, **kwargs):
try:
if registry_dict is None:
internal_registry_dict = global_registry_dict
elif isinstance(registry_dict, dict) or issubclass(registry_dict, dict):
internal_registry_dict = registry_dict
else:
internal_registry_dict = global_registry_dict
except NameError: # <<== CATCHES IF `global_registry_dict` IS REF'D BUT NOT DEFINED.
global global_registry_dict # <<== SYNTAX ERROR HAPPENS HERE
global_registry_dict = {}
internal_registry_dict = global_registry_dict
gen = func(*args, **kwargs)
next(gen)
internal_registry_dict[func.__name__] = gen
return wrapper
Exception Returned:
File "C:/yall/dont/need/to/know/this/generator_pipeline_utils.py", line 74
global global_registry_dict
^
SyntaxError: name 'global_registry_dict' is used prior to global declaration
Source of the Entire Module:
# global_registry_dict = {}
def make_stateless_actor(func):
"""
DESCRIPTION:
===========
This DECORATOR FUNCTION simplifies & centralizes the use of `send()` on generators.
It does this by ASSOCIATING the decorated function to a dictionary:
- by default, a global variable named `global_registry_dict` will be used.
- by default, `global_registry_dict = {}` will be created in the GLOBAL-NAMESPACE if it does not exist.
IMPORTANT NOTE:
==============
Use the `registry_dict` kwarg to manually assign your generator-func to an alternate dictionary:
`foo_decorated_func(registry_dict=foo_alternative_dictionary)`
REQUIREMENTS:
============
You can apply `#make_stateless_actor` to any GENERATOR FUNCTION which:
- INCLUDES A `yield` expression to the RIGHT of an `=` sign.
- INCLUDES `**kwargs` as a function argument.
"""
def wrapper(registry_dict=None, *args, **kwargs):
try:
if registry_dict is None: # <<-- necessary to prevent the next elif from throwing an exception.
internal_registry_dict = global_registry_dict
elif isinstance(registry_dict, dict) or issubclass(registry_dict, dict):
internal_registry_dict = registry_dict
else:
internal_registry_dict = global_registry_dict
except NameError:
print('WARNING: global_registry_dict IS NOT DEFINED AND YOU DID NOT EXPLICITLY PASS registry_dict TO THE DECORATED FUNCTION.\n\
`global_registry_dict = {}` has been instantiated in the global-namespace.\n')
global global_registry_dict
global_registry_dict = {}
internal_registry_dict = global_registry_dict
gen = func(*args, **kwargs)
next(gen)
internal_registry_dict[func.__name__] = gen
return wrapper
#make_stateless_actor
def printer(*args, **kwargs):
while True:
item = yield
print("Got: ", item)
def send(name, msg, registry_dict=None):
if registry_dict is None:
global_registry_dict[name].send(msg)
else:
registry_dict[name].send(msg)
if __name__ == "__main__":
printer(registry_dict=None) #<<==BEGIN THE CRAZY.
# send('printer', 'HEY WHAT IS UP?')
# send('printer', 666)
# send('printer', [1, 'a', [], True])
You use the name global_registry_dict in the else clause a couple lines up. If it's to be global, you must declare it so before using it, just as the error message says. Generally, names are declared global at the beginning of the function.
I am getting issue with global variable declared in python file.
I do not have class declaration in the file.
i am just declaring some variables in the class with none type.
and modifying that variables in the function.
when i was calling those variables inside another class by importing them,
instead of modified value it is returning None type only.
Below is the code
from selenium import webdriver
from Pages.PageMethods.Google_Methods import Methods
browser = None
s = None
def before_feature(context, feature):
print("before feature")
def before_scenario(context, scenario):
print('before scenario', scenario.name)
context.driver = webdriver.Firefox()
#context.driver.maximize_window()
browser = context.driver
global s
s = Methods(browser)
s.samplemethod()
def after_scenario(context, scenario):
print("after scenario", scenario.name)
context.driver.quit()
def after_feature(context, feature):
print("after feature")
->Here i was calling that 's' variable inside another class,it is returning None type only instead of object for that assigned class
Please someone help
Here is the code that i am calling that variable
from features.environment import *
use_step_matcher("re")
fileConfig('logging.ini')
log = logging.getLogger('sLogger')
#given("i am on google page '(.*)'")
def navigate(context, url1):
context.url = url1
log.info("this is log statement")
context.driver.get(url1)
context.driver.implicitly_wait(10)
#then("I enter value into search box as '(.*)'")
def step_impl(context, text):
print("selector:=>", Google.search_box)
context.driver.find_element(*Google.search_box).send_keys(text)
print("url in second step is:=>", context.url)
time.sleep(1)
s.printtitle()
and i was getting this error:
AttributeError: 'NoneType' object has no attribute 'printtitle'
You need use global operator
example:
global_var = list()
def somefunc():
global global_var
global_var.append(1)
somefunc()
print global_var
out:
[1]