Eswar February 2016

Issue with global variables in python

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'

Answers


Maxim Panfilov February 2016

You need use global operator

example:

global_var = list()

def somefunc():
    global global_var

    global_var.append(1)

somefunc()
print global_var

out: [1]

Post Status

Asked in February 2016
Viewed 2,955 times
Voted 8
Answered 1 times

Search




Leave an answer