-1

I have two function

def func1():
  res = requests.get('https://goole.com')

def func2():
  print(res.text)

I want to access res in func2() but as it is local object of func1() it is not accessible in func2(). I tried making it global like " global res " but i am getting error

NameError: name 'res' is not defined

ThankYou

2 Answers2

2

Avoid global variables, instead return the value you want:

def func1():
   return requests.get('https://goole.com')

def func2(res):
    print(res.text)

res = func1()
func2(res)

Or use a class:

class MyClass:
    def func1():
       self.res = requests.get('https://goole.com')

   def func2():
       print(self.res.text)

myclass = MyClass()
myclass.func1()
myclass.func2()

If you really want to use them:

def func1():
   global res
   res = requests.get('https://goole.com')

def func2():
    print(res.text)
k4ppa
  • 4,122
  • 8
  • 26
  • 36
0

you may use the global keyword:

def func1():
  global res = requests.get('https://google.com')

def func2():
  print(res.text)

or alternatively (and hopefully) pass requests object as argument:

def func1():
  res = requests.get('https://google.com')
  func2(res)

def func2(res):
  print(res.text)

remember global variables are considered a bad programming practice

Community
  • 1
  • 1
Ayush
  • 3,695
  • 1
  • 32
  • 42