2

For example in requests library we have get method which is defined inside api.py file but i can directly call it with requests.get .

as per my understanding it should be called like this requests.api.get

How python modules handles this.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
R__raki__
  • 847
  • 4
  • 15
  • 30

2 Answers2

1

When you are doing import requests the file requests/__init__.py is imported and when you access its content with dot notation like requests.get you in fact are accessing requests.__init__.get. This contains the following line:

from .api import request, get, head, post, patch, put, delete, options

So this __init__ file has get name in its scope, thats all. More info about __init__.py file here: What is __init__.py for?.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
1

Your intuition is correct that the name should be requests.api.get. In fact, if you look at requests.get.__module__, you will find that it is requests.api. Similarly, requests.get.__globals__ is a reference to requests.api.__dict__.

Many libraries will export functions defined elsewhere through the top level namespace. This is usually done with an import like from .api import get in the __init__.py file of requests.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264