Finding the source code for built-in Python functions?

前端 未结 8 1821
一向
一向 2020-11-22 02:40

Is there a way to see how built in functions work in python? I don\'t mean just how to use them, but also how were they built, what is the code behind sorted

8条回答
  •  情歌与酒
    2020-11-22 02:52

    2 methods,

    1. You can check usage about snippet using help()
    2. you can check hidden code for those modules using inspect

    1) inspect:

    use inpsect module to explore code you want... NOTE: you can able to explore code only for modules (aka) packages you have imported

    for eg:

      >>> import randint  
      >>> from inspect import getsource
      >>> getsource(randint) # here i am going to explore code for package called `randint`
    

    2) help():

    you can simply use help() command to get help about builtin functions as well its code.

    for eg: if you want to see the code for str() , simply type - help(str)

    it will return like this,

    >>> help(str)
    Help on class str in module __builtin__:
    
    class str(basestring)
     |  str(object='') -> string
     |
     |  Return a nice string representation of the object.
     |  If the argument is a string, the return value is the same object.
     |
     |  Method resolution order:
     |      str
     |      basestring
     |      object
     |
     |  Methods defined here:
     |
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     |
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x
     |
     |  __eq__(...)
     |      x.__eq__(y) <==> x==y
     |
     |  __format__(...)
     |      S.__format__(format_spec) -> string
     |
     |      Return a formatted version of S as described by format_spec.
     |
     |  __ge__(...)
     |      x.__ge__(y) <==> x>=y
     |
     |  __getattribute__(...)
    -- More  --
    

提交回复
热议问题