I found a strange phenomenon that some methods in Python standard library can be called as functions.
For example, there is a method randint()
defined in class Random
in module random.py
.
As I understand, when we wanted to call it, we should import the module random
first, then declare a instance of class Random
so that method randint()
can be called such as
import random as rd
aaa = rd.Random()
aaa.randint()
But I just found that randint()
can be called as a function and it is unnecessary to do as above:
import random as rd
rd.randint()
So I wonder how does this illogical phenomenon happen?
Why can methods in Python standard library be called as functions?
Looking into random.py
, we see that in fact an instance is created and its methods exported as module-level functions. There's nothing magic about it.
The comment there describes it beautifully:
# Create one instance, seeded from current time, and export its methods
# as module-level functions. The functions share state across all uses
# (both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.
_inst = Random()
# .. SNIP ..
randint = _inst.randint
Other standard library modules take a different but similar approach to export module-level functions. E.g. the re
module uses an internal function _compile()
to create a local Pattern
instance and let it do the work (docstring omitted for brevity):
def search(pattern, string, flags=0):
return _compile(pattern, flags).search(string)
We can conclude that there's no general mechanism to elevate methods to module-level functions. It's just good interface design on the part of the individual modules.