Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Accessing imported module from file above

I am sure I am doing something embarrassing and daft, but is it possible to access the imported modules in one.py from the function in two.py (the files are in the same directory)?

one.py

import requests
import two
print(two.get_google())

two.py

def get_google():
   return requests.get('http://google.com')

Error i get...

python3 one.py

Traceback (most recent call last):
  File "one.py", line 3, in <module>
    print(two.get_google())
  File "/myfolder/two.py", line 2, in get_google
    return requests.get('http://google.com')
NameError: name 'requests' is not defined

Thanks and apologies in advance..

like image 968
display_name Avatar asked Dec 24 '22 03:12

display_name


1 Answers

Import statements bind a name within the importing module's namespace. You must put the requests import directly into the module that needs to use this name:

# one.py
import two

print(two.get_google())

^ removed from one, where it was unused, and added to two:

# two.py
import requests

def get_google():
   return requests.get('http://google.com')
like image 115
wim Avatar answered Jan 18 '23 16:01

wim