inspect.py 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192
  1. """Get useful information from live Python objects.
  2. This module encapsulates the interface provided by the internal special
  3. attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
  4. It also provides some help for examining source code and class layout.
  5. Here are some of the useful functions provided by this module:
  6. ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
  7. isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
  8. isroutine() - check object types
  9. getmembers() - get members of an object that satisfy a given condition
  10. getfile(), getsourcefile(), getsource() - find an object's source code
  11. getdoc(), getcomments() - get documentation on an object
  12. getmodule() - determine the module that an object came from
  13. getclasstree() - arrange classes so as to represent their hierarchy
  14. getargvalues(), getcallargs() - get info about function arguments
  15. getfullargspec() - same, with support for Python 3 features
  16. formatargvalues() - format an argument spec
  17. getouterframes(), getinnerframes() - get info about frames
  18. currentframe() - get the current stack frame
  19. stack(), trace() - get info about frames on the stack or in a traceback
  20. signature() - get a Signature object for the callable
  21. """
  22. # This module is in the public domain. No warranties.
  23. __author__ = ('Ka-Ping Yee <ping@lfw.org>',
  24. 'Yury Selivanov <yselivanov@sprymix.com>')
  25. import abc
  26. import ast
  27. import dis
  28. import collections.abc
  29. import enum
  30. import importlib.machinery
  31. import itertools
  32. import linecache
  33. import os
  34. import re
  35. import sys
  36. import tokenize
  37. import token
  38. import types
  39. import warnings
  40. import functools
  41. import builtins
  42. from operator import attrgetter
  43. from collections import namedtuple, OrderedDict
  44. # Create constants for the compiler flags in Include/code.h
  45. # We try to get them from dis to avoid duplication
  46. mod_dict = globals()
  47. for k, v in dis.COMPILER_FLAG_NAMES.items():
  48. mod_dict["CO_" + v] = k
  49. # See Include/object.h
  50. TPFLAGS_IS_ABSTRACT = 1 << 20
  51. # ----------------------------------------------------------- type-checking
  52. def ismodule(object):
  53. """Return true if the object is a module.
  54. Module objects provide these attributes:
  55. __cached__ pathname to byte compiled file
  56. __doc__ documentation string
  57. __file__ filename (missing for built-in modules)"""
  58. return isinstance(object, types.ModuleType)
  59. def isclass(object):
  60. """Return true if the object is a class.
  61. Class objects provide these attributes:
  62. __doc__ documentation string
  63. __module__ name of module in which this class was defined"""
  64. return isinstance(object, type)
  65. def ismethod(object):
  66. """Return true if the object is an instance method.
  67. Instance method objects provide these attributes:
  68. __doc__ documentation string
  69. __name__ name with which this method was defined
  70. __func__ function object containing implementation of method
  71. __self__ instance to which this method is bound"""
  72. return isinstance(object, types.MethodType)
  73. def ismethoddescriptor(object):
  74. """Return true if the object is a method descriptor.
  75. But not if ismethod() or isclass() or isfunction() are true.
  76. This is new in Python 2.2, and, for example, is true of int.__add__.
  77. An object passing this test has a __get__ attribute but not a __set__
  78. attribute, but beyond that the set of attributes varies. __name__ is
  79. usually sensible, and __doc__ often is.
  80. Methods implemented via descriptors that also pass one of the other
  81. tests return false from the ismethoddescriptor() test, simply because
  82. the other tests promise more -- you can, e.g., count on having the
  83. __func__ attribute (etc) when an object passes ismethod()."""
  84. if isclass(object) or ismethod(object) or isfunction(object):
  85. # mutual exclusion
  86. return False
  87. tp = type(object)
  88. return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
  89. def isdatadescriptor(object):
  90. """Return true if the object is a data descriptor.
  91. Data descriptors have a __set__ or a __delete__ attribute. Examples are
  92. properties (defined in Python) and getsets and members (defined in C).
  93. Typically, data descriptors will also have __name__ and __doc__ attributes
  94. (properties, getsets, and members have both of these attributes), but this
  95. is not guaranteed."""
  96. if isclass(object) or ismethod(object) or isfunction(object):
  97. # mutual exclusion
  98. return False
  99. tp = type(object)
  100. return hasattr(tp, "__set__") or hasattr(tp, "__delete__")
  101. if hasattr(types, 'MemberDescriptorType'):
  102. # CPython and equivalent
  103. def ismemberdescriptor(object):
  104. """Return true if the object is a member descriptor.
  105. Member descriptors are specialized descriptors defined in extension
  106. modules."""
  107. return isinstance(object, types.MemberDescriptorType)
  108. else:
  109. # Other implementations
  110. def ismemberdescriptor(object):
  111. """Return true if the object is a member descriptor.
  112. Member descriptors are specialized descriptors defined in extension
  113. modules."""
  114. return False
  115. if hasattr(types, 'GetSetDescriptorType'):
  116. # CPython and equivalent
  117. def isgetsetdescriptor(object):
  118. """Return true if the object is a getset descriptor.
  119. getset descriptors are specialized descriptors defined in extension
  120. modules."""
  121. return isinstance(object, types.GetSetDescriptorType)
  122. else:
  123. # Other implementations
  124. def isgetsetdescriptor(object):
  125. """Return true if the object is a getset descriptor.
  126. getset descriptors are specialized descriptors defined in extension
  127. modules."""
  128. return False
  129. def isfunction(object):
  130. """Return true if the object is a user-defined function.
  131. Function objects provide these attributes:
  132. __doc__ documentation string
  133. __name__ name with which this function was defined
  134. __code__ code object containing compiled function bytecode
  135. __defaults__ tuple of any default values for arguments
  136. __globals__ global namespace in which this function was defined
  137. __annotations__ dict of parameter annotations
  138. __kwdefaults__ dict of keyword only parameters with defaults"""
  139. return isinstance(object, types.FunctionType)
  140. def _has_code_flag(f, flag):
  141. """Return true if ``f`` is a function (or a method or functools.partial
  142. wrapper wrapping a function) whose code object has the given ``flag``
  143. set in its flags."""
  144. while ismethod(f):
  145. f = f.__func__
  146. f = functools._unwrap_partial(f)
  147. if not isfunction(f):
  148. return False
  149. return bool(f.__code__.co_flags & flag)
  150. def isgeneratorfunction(obj):
  151. """Return true if the object is a user-defined generator function.
  152. Generator function objects provide the same attributes as functions.
  153. See help(isfunction) for a list of attributes."""
  154. return _has_code_flag(obj, CO_GENERATOR)
  155. def iscoroutinefunction(obj):
  156. """Return true if the object is a coroutine function.
  157. Coroutine functions are defined with "async def" syntax.
  158. """
  159. return _has_code_flag(obj, CO_COROUTINE)
  160. def isasyncgenfunction(obj):
  161. """Return true if the object is an asynchronous generator function.
  162. Asynchronous generator functions are defined with "async def"
  163. syntax and have "yield" expressions in their body.
  164. """
  165. return _has_code_flag(obj, CO_ASYNC_GENERATOR)
  166. def isasyncgen(object):
  167. """Return true if the object is an asynchronous generator."""
  168. return isinstance(object, types.AsyncGeneratorType)
  169. def isgenerator(object):
  170. """Return true if the object is a generator.
  171. Generator objects provide these attributes:
  172. __iter__ defined to support iteration over container
  173. close raises a new GeneratorExit exception inside the
  174. generator to terminate the iteration
  175. gi_code code object
  176. gi_frame frame object or possibly None once the generator has
  177. been exhausted
  178. gi_running set to 1 when generator is executing, 0 otherwise
  179. next return the next item from the container
  180. send resumes the generator and "sends" a value that becomes
  181. the result of the current yield-expression
  182. throw used to raise an exception inside the generator"""
  183. return isinstance(object, types.GeneratorType)
  184. def iscoroutine(object):
  185. """Return true if the object is a coroutine."""
  186. return isinstance(object, types.CoroutineType)
  187. def isawaitable(object):
  188. """Return true if object can be passed to an ``await`` expression."""
  189. return (isinstance(object, types.CoroutineType) or
  190. isinstance(object, types.GeneratorType) and
  191. bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
  192. isinstance(object, collections.abc.Awaitable))
  193. def istraceback(object):
  194. """Return true if the object is a traceback.
  195. Traceback objects provide these attributes:
  196. tb_frame frame object at this level
  197. tb_lasti index of last attempted instruction in bytecode
  198. tb_lineno current line number in Python source code
  199. tb_next next inner traceback object (called by this level)"""
  200. return isinstance(object, types.TracebackType)
  201. def isframe(object):
  202. """Return true if the object is a frame object.
  203. Frame objects provide these attributes:
  204. f_back next outer frame object (this frame's caller)
  205. f_builtins built-in namespace seen by this frame
  206. f_code code object being executed in this frame
  207. f_globals global namespace seen by this frame
  208. f_lasti index of last attempted instruction in bytecode
  209. f_lineno current line number in Python source code
  210. f_locals local namespace seen by this frame
  211. f_trace tracing function for this frame, or None"""
  212. return isinstance(object, types.FrameType)
  213. def iscode(object):
  214. """Return true if the object is a code object.
  215. Code objects provide these attributes:
  216. co_argcount number of arguments (not including *, ** args
  217. or keyword only arguments)
  218. co_code string of raw compiled bytecode
  219. co_cellvars tuple of names of cell variables
  220. co_consts tuple of constants used in the bytecode
  221. co_filename name of file in which this code object was created
  222. co_firstlineno number of first line in Python source code
  223. co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  224. | 16=nested | 32=generator | 64=nofree | 128=coroutine
  225. | 256=iterable_coroutine | 512=async_generator
  226. co_freevars tuple of names of free variables
  227. co_posonlyargcount number of positional only arguments
  228. co_kwonlyargcount number of keyword only arguments (not including ** arg)
  229. co_lnotab encoded mapping of line numbers to bytecode indices
  230. co_name name with which this code object was defined
  231. co_names tuple of names of local variables
  232. co_nlocals number of local variables
  233. co_stacksize virtual machine stack space required
  234. co_varnames tuple of names of arguments and local variables"""
  235. return isinstance(object, types.CodeType)
  236. def isbuiltin(object):
  237. """Return true if the object is a built-in function or method.
  238. Built-in functions and methods provide these attributes:
  239. __doc__ documentation string
  240. __name__ original name of this function or method
  241. __self__ instance to which a method is bound, or None"""
  242. return isinstance(object, types.BuiltinFunctionType)
  243. def isroutine(object):
  244. """Return true if the object is any kind of function or method."""
  245. return (isbuiltin(object)
  246. or isfunction(object)
  247. or ismethod(object)
  248. or ismethoddescriptor(object))
  249. def isabstract(object):
  250. """Return true if the object is an abstract base class (ABC)."""
  251. if not isinstance(object, type):
  252. return False
  253. if object.__flags__ & TPFLAGS_IS_ABSTRACT:
  254. return True
  255. if not issubclass(type(object), abc.ABCMeta):
  256. return False
  257. if hasattr(object, '__abstractmethods__'):
  258. # It looks like ABCMeta.__new__ has finished running;
  259. # TPFLAGS_IS_ABSTRACT should have been accurate.
  260. return False
  261. # It looks like ABCMeta.__new__ has not finished running yet; we're
  262. # probably in __init_subclass__. We'll look for abstractmethods manually.
  263. for name, value in object.__dict__.items():
  264. if getattr(value, "__isabstractmethod__", False):
  265. return True
  266. for base in object.__bases__:
  267. for name in getattr(base, "__abstractmethods__", ()):
  268. value = getattr(object, name, None)
  269. if getattr(value, "__isabstractmethod__", False):
  270. return True
  271. return False
  272. def getmembers(object, predicate=None):
  273. """Return all members of an object as (name, value) pairs sorted by name.
  274. Optionally, only return members that satisfy a given predicate."""
  275. if isclass(object):
  276. mro = (object,) + getmro(object)
  277. else:
  278. mro = ()
  279. results = []
  280. processed = set()
  281. names = dir(object)
  282. # :dd any DynamicClassAttributes to the list of names if object is a class;
  283. # this may result in duplicate entries if, for example, a virtual
  284. # attribute with the same name as a DynamicClassAttribute exists
  285. try:
  286. for base in object.__bases__:
  287. for k, v in base.__dict__.items():
  288. if isinstance(v, types.DynamicClassAttribute):
  289. names.append(k)
  290. except AttributeError:
  291. pass
  292. for key in names:
  293. # First try to get the value via getattr. Some descriptors don't
  294. # like calling their __get__ (see bug #1785), so fall back to
  295. # looking in the __dict__.
  296. try:
  297. value = getattr(object, key)
  298. # handle the duplicate key
  299. if key in processed:
  300. raise AttributeError
  301. except AttributeError:
  302. for base in mro:
  303. if key in base.__dict__:
  304. value = base.__dict__[key]
  305. break
  306. else:
  307. # could be a (currently) missing slot member, or a buggy
  308. # __dir__; discard and move on
  309. continue
  310. if not predicate or predicate(value):
  311. results.append((key, value))
  312. processed.add(key)
  313. results.sort(key=lambda pair: pair[0])
  314. return results
  315. Attribute = namedtuple('Attribute', 'name kind defining_class object')
  316. def classify_class_attrs(cls):
  317. """Return list of attribute-descriptor tuples.
  318. For each name in dir(cls), the return list contains a 4-tuple
  319. with these elements:
  320. 0. The name (a string).
  321. 1. The kind of attribute this is, one of these strings:
  322. 'class method' created via classmethod()
  323. 'static method' created via staticmethod()
  324. 'property' created via property()
  325. 'method' any other flavor of method or descriptor
  326. 'data' not a method
  327. 2. The class which defined this attribute (a class).
  328. 3. The object as obtained by calling getattr; if this fails, or if the
  329. resulting object does not live anywhere in the class' mro (including
  330. metaclasses) then the object is looked up in the defining class's
  331. dict (found by walking the mro).
  332. If one of the items in dir(cls) is stored in the metaclass it will now
  333. be discovered and not have None be listed as the class in which it was
  334. defined. Any items whose home class cannot be discovered are skipped.
  335. """
  336. mro = getmro(cls)
  337. metamro = getmro(type(cls)) # for attributes stored in the metaclass
  338. metamro = tuple(cls for cls in metamro if cls not in (type, object))
  339. class_bases = (cls,) + mro
  340. all_bases = class_bases + metamro
  341. names = dir(cls)
  342. # :dd any DynamicClassAttributes to the list of names;
  343. # this may result in duplicate entries if, for example, a virtual
  344. # attribute with the same name as a DynamicClassAttribute exists.
  345. for base in mro:
  346. for k, v in base.__dict__.items():
  347. if isinstance(v, types.DynamicClassAttribute):
  348. names.append(k)
  349. result = []
  350. processed = set()
  351. for name in names:
  352. # Get the object associated with the name, and where it was defined.
  353. # Normal objects will be looked up with both getattr and directly in
  354. # its class' dict (in case getattr fails [bug #1785], and also to look
  355. # for a docstring).
  356. # For DynamicClassAttributes on the second pass we only look in the
  357. # class's dict.
  358. #
  359. # Getting an obj from the __dict__ sometimes reveals more than
  360. # using getattr. Static and class methods are dramatic examples.
  361. homecls = None
  362. get_obj = None
  363. dict_obj = None
  364. if name not in processed:
  365. try:
  366. if name == '__dict__':
  367. raise Exception("__dict__ is special, don't want the proxy")
  368. get_obj = getattr(cls, name)
  369. except Exception as exc:
  370. pass
  371. else:
  372. homecls = getattr(get_obj, "__objclass__", homecls)
  373. if homecls not in class_bases:
  374. # if the resulting object does not live somewhere in the
  375. # mro, drop it and search the mro manually
  376. homecls = None
  377. last_cls = None
  378. # first look in the classes
  379. for srch_cls in class_bases:
  380. srch_obj = getattr(srch_cls, name, None)
  381. if srch_obj is get_obj:
  382. last_cls = srch_cls
  383. # then check the metaclasses
  384. for srch_cls in metamro:
  385. try:
  386. srch_obj = srch_cls.__getattr__(cls, name)
  387. except AttributeError:
  388. continue
  389. if srch_obj is get_obj:
  390. last_cls = srch_cls
  391. if last_cls is not None:
  392. homecls = last_cls
  393. for base in all_bases:
  394. if name in base.__dict__:
  395. dict_obj = base.__dict__[name]
  396. if homecls not in metamro:
  397. homecls = base
  398. break
  399. if homecls is None:
  400. # unable to locate the attribute anywhere, most likely due to
  401. # buggy custom __dir__; discard and move on
  402. continue
  403. obj = get_obj if get_obj is not None else dict_obj
  404. # Classify the object or its descriptor.
  405. if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
  406. kind = "static method"
  407. obj = dict_obj
  408. elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
  409. kind = "class method"
  410. obj = dict_obj
  411. elif isinstance(dict_obj, property):
  412. kind = "property"
  413. obj = dict_obj
  414. elif isroutine(obj):
  415. kind = "method"
  416. else:
  417. kind = "data"
  418. result.append(Attribute(name, kind, homecls, obj))
  419. processed.add(name)
  420. return result
  421. # ----------------------------------------------------------- class helpers
  422. def getmro(cls):
  423. "Return tuple of base classes (including cls) in method resolution order."
  424. return cls.__mro__
  425. # -------------------------------------------------------- function helpers
  426. def unwrap(func, *, stop=None):
  427. """Get the object wrapped by *func*.
  428. Follows the chain of :attr:`__wrapped__` attributes returning the last
  429. object in the chain.
  430. *stop* is an optional callback accepting an object in the wrapper chain
  431. as its sole argument that allows the unwrapping to be terminated early if
  432. the callback returns a true value. If the callback never returns a true
  433. value, the last object in the chain is returned as usual. For example,
  434. :func:`signature` uses this to stop unwrapping if any object in the
  435. chain has a ``__signature__`` attribute defined.
  436. :exc:`ValueError` is raised if a cycle is encountered.
  437. """
  438. if stop is None:
  439. def _is_wrapper(f):
  440. return hasattr(f, '__wrapped__')
  441. else:
  442. def _is_wrapper(f):
  443. return hasattr(f, '__wrapped__') and not stop(f)
  444. f = func # remember the original func for error reporting
  445. # Memoise by id to tolerate non-hashable objects, but store objects to
  446. # ensure they aren't destroyed, which would allow their IDs to be reused.
  447. memo = {id(f): f}
  448. recursion_limit = sys.getrecursionlimit()
  449. while _is_wrapper(func):
  450. func = func.__wrapped__
  451. id_func = id(func)
  452. if (id_func in memo) or (len(memo) >= recursion_limit):
  453. raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
  454. memo[id_func] = func
  455. return func
  456. # -------------------------------------------------- source code extraction
  457. def indentsize(line):
  458. """Return the indent size, in spaces, at the start of a line of text."""
  459. expline = line.expandtabs()
  460. return len(expline) - len(expline.lstrip())
  461. def _findclass(func):
  462. cls = sys.modules.get(func.__module__)
  463. if cls is None:
  464. return None
  465. for name in func.__qualname__.split('.')[:-1]:
  466. cls = getattr(cls, name)
  467. if not isclass(cls):
  468. return None
  469. return cls
  470. def _finddoc(obj):
  471. if isclass(obj):
  472. for base in obj.__mro__:
  473. if base is not object:
  474. try:
  475. doc = base.__doc__
  476. except AttributeError:
  477. continue
  478. if doc is not None:
  479. return doc
  480. return None
  481. if ismethod(obj):
  482. name = obj.__func__.__name__
  483. self = obj.__self__
  484. if (isclass(self) and
  485. getattr(getattr(self, name, None), '__func__') is obj.__func__):
  486. # classmethod
  487. cls = self
  488. else:
  489. cls = self.__class__
  490. elif isfunction(obj):
  491. name = obj.__name__
  492. cls = _findclass(obj)
  493. if cls is None or getattr(cls, name) is not obj:
  494. return None
  495. elif isbuiltin(obj):
  496. name = obj.__name__
  497. self = obj.__self__
  498. if (isclass(self) and
  499. self.__qualname__ + '.' + name == obj.__qualname__):
  500. # classmethod
  501. cls = self
  502. else:
  503. cls = self.__class__
  504. # Should be tested before isdatadescriptor().
  505. elif isinstance(obj, property):
  506. func = obj.fget
  507. name = func.__name__
  508. cls = _findclass(func)
  509. if cls is None or getattr(cls, name) is not obj:
  510. return None
  511. elif ismethoddescriptor(obj) or isdatadescriptor(obj):
  512. name = obj.__name__
  513. cls = obj.__objclass__
  514. if getattr(cls, name) is not obj:
  515. return None
  516. if ismemberdescriptor(obj):
  517. slots = getattr(cls, '__slots__', None)
  518. if isinstance(slots, dict) and name in slots:
  519. return slots[name]
  520. else:
  521. return None
  522. for base in cls.__mro__:
  523. try:
  524. doc = getattr(base, name).__doc__
  525. except AttributeError:
  526. continue
  527. if doc is not None:
  528. return doc
  529. return None
  530. def getdoc(object):
  531. """Get the documentation string for an object.
  532. All tabs are expanded to spaces. To clean up docstrings that are
  533. indented to line up with blocks of code, any whitespace than can be
  534. uniformly removed from the second line onwards is removed."""
  535. try:
  536. doc = object.__doc__
  537. except AttributeError:
  538. return None
  539. if doc is None:
  540. try:
  541. doc = _finddoc(object)
  542. except (AttributeError, TypeError):
  543. return None
  544. if not isinstance(doc, str):
  545. return None
  546. return cleandoc(doc)
  547. def cleandoc(doc):
  548. """Clean up indentation from docstrings.
  549. Any whitespace that can be uniformly removed from the second line
  550. onwards is removed."""
  551. try:
  552. lines = doc.expandtabs().split('\n')
  553. except UnicodeError:
  554. return None
  555. else:
  556. # Find minimum indentation of any non-blank lines after first line.
  557. margin = sys.maxsize
  558. for line in lines[1:]:
  559. content = len(line.lstrip())
  560. if content:
  561. indent = len(line) - content
  562. margin = min(margin, indent)
  563. # Remove indentation.
  564. if lines:
  565. lines[0] = lines[0].lstrip()
  566. if margin < sys.maxsize:
  567. for i in range(1, len(lines)): lines[i] = lines[i][margin:]
  568. # Remove any trailing or leading blank lines.
  569. while lines and not lines[-1]:
  570. lines.pop()
  571. while lines and not lines[0]:
  572. lines.pop(0)
  573. return '\n'.join(lines)
  574. def getfile(object):
  575. """Work out which source or compiled file an object was defined in."""
  576. if ismodule(object):
  577. if getattr(object, '__file__', None):
  578. return object.__file__
  579. raise TypeError('{!r} is a built-in module'.format(object))
  580. if isclass(object):
  581. if hasattr(object, '__module__'):
  582. module = sys.modules.get(object.__module__)
  583. if getattr(module, '__file__', None):
  584. return module.__file__
  585. raise TypeError('{!r} is a built-in class'.format(object))
  586. if ismethod(object):
  587. object = object.__func__
  588. if isfunction(object):
  589. object = object.__code__
  590. if istraceback(object):
  591. object = object.tb_frame
  592. if isframe(object):
  593. object = object.f_code
  594. if iscode(object):
  595. return object.co_filename
  596. raise TypeError('module, class, method, function, traceback, frame, or '
  597. 'code object was expected, got {}'.format(
  598. type(object).__name__))
  599. def getmodulename(path):
  600. """Return the module name for a given file, or None."""
  601. fname = os.path.basename(path)
  602. # Check for paths that look like an actual module file
  603. suffixes = [(-len(suffix), suffix)
  604. for suffix in importlib.machinery.all_suffixes()]
  605. suffixes.sort() # try longest suffixes first, in case they overlap
  606. for neglen, suffix in suffixes:
  607. if fname.endswith(suffix):
  608. return fname[:neglen]
  609. return None
  610. def getsourcefile(object):
  611. """Return the filename that can be used to locate an object's source.
  612. Return None if no way can be identified to get the source.
  613. """
  614. filename = getfile(object)
  615. all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
  616. all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
  617. if any(filename.endswith(s) for s in all_bytecode_suffixes):
  618. filename = (os.path.splitext(filename)[0] +
  619. importlib.machinery.SOURCE_SUFFIXES[0])
  620. elif any(filename.endswith(s) for s in
  621. importlib.machinery.EXTENSION_SUFFIXES):
  622. return None
  623. if os.path.exists(filename):
  624. return filename
  625. # only return a non-existent filename if the module has a PEP 302 loader
  626. if getattr(getmodule(object, filename), '__loader__', None) is not None:
  627. return filename
  628. # or it is in the linecache
  629. if filename in linecache.cache:
  630. return filename
  631. def getabsfile(object, _filename=None):
  632. """Return an absolute path to the source or compiled file for an object.
  633. The idea is for each object to have a unique origin, so this routine
  634. normalizes the result as much as possible."""
  635. if _filename is None:
  636. _filename = getsourcefile(object) or getfile(object)
  637. return os.path.normcase(os.path.abspath(_filename))
  638. modulesbyfile = {}
  639. _filesbymodname = {}
  640. def getmodule(object, _filename=None):
  641. """Return the module an object was defined in, or None if not found."""
  642. if ismodule(object):
  643. return object
  644. if hasattr(object, '__module__'):
  645. return sys.modules.get(object.__module__)
  646. # Try the filename to modulename cache
  647. if _filename is not None and _filename in modulesbyfile:
  648. return sys.modules.get(modulesbyfile[_filename])
  649. # Try the cache again with the absolute file name
  650. try:
  651. file = getabsfile(object, _filename)
  652. except TypeError:
  653. return None
  654. if file in modulesbyfile:
  655. return sys.modules.get(modulesbyfile[file])
  656. # Update the filename to module name cache and check yet again
  657. # Copy sys.modules in order to cope with changes while iterating
  658. for modname, module in sys.modules.copy().items():
  659. if ismodule(module) and hasattr(module, '__file__'):
  660. f = module.__file__
  661. if f == _filesbymodname.get(modname, None):
  662. # Have already mapped this module, so skip it
  663. continue
  664. _filesbymodname[modname] = f
  665. f = getabsfile(module)
  666. # Always map to the name the module knows itself by
  667. modulesbyfile[f] = modulesbyfile[
  668. os.path.realpath(f)] = module.__name__
  669. if file in modulesbyfile:
  670. return sys.modules.get(modulesbyfile[file])
  671. # Check the main module
  672. main = sys.modules['__main__']
  673. if not hasattr(object, '__name__'):
  674. return None
  675. if hasattr(main, object.__name__):
  676. mainobject = getattr(main, object.__name__)
  677. if mainobject is object:
  678. return main
  679. # Check builtins
  680. builtin = sys.modules['builtins']
  681. if hasattr(builtin, object.__name__):
  682. builtinobject = getattr(builtin, object.__name__)
  683. if builtinobject is object:
  684. return builtin
  685. class ClassFoundException(Exception):
  686. pass
  687. class _ClassFinder(ast.NodeVisitor):
  688. def __init__(self, qualname):
  689. self.stack = []
  690. self.qualname = qualname
  691. def visit_FunctionDef(self, node):
  692. self.stack.append(node.name)
  693. self.stack.append('<locals>')
  694. self.generic_visit(node)
  695. self.stack.pop()
  696. self.stack.pop()
  697. visit_AsyncFunctionDef = visit_FunctionDef
  698. def visit_ClassDef(self, node):
  699. self.stack.append(node.name)
  700. if self.qualname == '.'.join(self.stack):
  701. # Return the decorator for the class if present
  702. if node.decorator_list:
  703. line_number = node.decorator_list[0].lineno
  704. else:
  705. line_number = node.lineno
  706. # decrement by one since lines starts with indexing by zero
  707. line_number -= 1
  708. raise ClassFoundException(line_number)
  709. self.generic_visit(node)
  710. self.stack.pop()
  711. def findsource(object):
  712. """Return the entire source file and starting line number for an object.
  713. The argument may be a module, class, method, function, traceback, frame,
  714. or code object. The source code is returned as a list of all the lines
  715. in the file and the line number indexes a line in that list. An OSError
  716. is raised if the source code cannot be retrieved."""
  717. file = getsourcefile(object)
  718. if file:
  719. # Invalidate cache if needed.
  720. linecache.checkcache(file)
  721. else:
  722. file = getfile(object)
  723. # Allow filenames in form of "<something>" to pass through.
  724. # `doctest` monkeypatches `linecache` module to enable
  725. # inspection, so let `linecache.getlines` to be called.
  726. if not (file.startswith('<') and file.endswith('>')):
  727. raise OSError('source code not available')
  728. module = getmodule(object, file)
  729. if module:
  730. lines = linecache.getlines(file, module.__dict__)
  731. else:
  732. lines = linecache.getlines(file)
  733. if not lines:
  734. raise OSError('could not get source code')
  735. if ismodule(object):
  736. return lines, 0
  737. if isclass(object):
  738. qualname = object.__qualname__
  739. source = ''.join(lines)
  740. tree = ast.parse(source)
  741. class_finder = _ClassFinder(qualname)
  742. try:
  743. class_finder.visit(tree)
  744. except ClassFoundException as e:
  745. line_number = e.args[0]
  746. return lines, line_number
  747. else:
  748. raise OSError('could not find class definition')
  749. if ismethod(object):
  750. object = object.__func__
  751. if isfunction(object):
  752. object = object.__code__
  753. if istraceback(object):
  754. object = object.tb_frame
  755. if isframe(object):
  756. object = object.f_code
  757. if iscode(object):
  758. if not hasattr(object, 'co_firstlineno'):
  759. raise OSError('could not find function definition')
  760. lnum = object.co_firstlineno - 1
  761. pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
  762. while lnum > 0:
  763. try:
  764. line = lines[lnum]
  765. except IndexError:
  766. raise OSError('lineno is out of bounds')
  767. if pat.match(line):
  768. break
  769. lnum = lnum - 1
  770. return lines, lnum
  771. raise OSError('could not find code object')
  772. def getcomments(object):
  773. """Get lines of comments immediately preceding an object's source code.
  774. Returns None when source can't be found.
  775. """
  776. try:
  777. lines, lnum = findsource(object)
  778. except (OSError, TypeError):
  779. return None
  780. if ismodule(object):
  781. # Look for a comment block at the top of the file.
  782. start = 0
  783. if lines and lines[0][:2] == '#!': start = 1
  784. while start < len(lines) and lines[start].strip() in ('', '#'):
  785. start = start + 1
  786. if start < len(lines) and lines[start][:1] == '#':
  787. comments = []
  788. end = start
  789. while end < len(lines) and lines[end][:1] == '#':
  790. comments.append(lines[end].expandtabs())
  791. end = end + 1
  792. return ''.join(comments)
  793. # Look for a preceding block of comments at the same indentation.
  794. elif lnum > 0:
  795. indent = indentsize(lines[lnum])
  796. end = lnum - 1
  797. if end >= 0 and lines[end].lstrip()[:1] == '#' and \
  798. indentsize(lines[end]) == indent:
  799. comments = [lines[end].expandtabs().lstrip()]
  800. if end > 0:
  801. end = end - 1
  802. comment = lines[end].expandtabs().lstrip()
  803. while comment[:1] == '#' and indentsize(lines[end]) == indent:
  804. comments[:0] = [comment]
  805. end = end - 1
  806. if end < 0: break
  807. comment = lines[end].expandtabs().lstrip()
  808. while comments and comments[0].strip() == '#':
  809. comments[:1] = []
  810. while comments and comments[-1].strip() == '#':
  811. comments[-1:] = []
  812. return ''.join(comments)
  813. class EndOfBlock(Exception): pass
  814. class BlockFinder:
  815. """Provide a tokeneater() method to detect the end of a code block."""
  816. def __init__(self):
  817. self.indent = 0
  818. self.islambda = False
  819. self.started = False
  820. self.passline = False
  821. self.indecorator = False
  822. self.decoratorhasargs = False
  823. self.last = 1
  824. self.body_col0 = None
  825. def tokeneater(self, type, token, srowcol, erowcol, line):
  826. if not self.started and not self.indecorator:
  827. # skip any decorators
  828. if token == "@":
  829. self.indecorator = True
  830. # look for the first "def", "class" or "lambda"
  831. elif token in ("def", "class", "lambda"):
  832. if token == "lambda":
  833. self.islambda = True
  834. self.started = True
  835. self.passline = True # skip to the end of the line
  836. elif token == "(":
  837. if self.indecorator:
  838. self.decoratorhasargs = True
  839. elif token == ")":
  840. if self.indecorator:
  841. self.indecorator = False
  842. self.decoratorhasargs = False
  843. elif type == tokenize.NEWLINE:
  844. self.passline = False # stop skipping when a NEWLINE is seen
  845. self.last = srowcol[0]
  846. if self.islambda: # lambdas always end at the first NEWLINE
  847. raise EndOfBlock
  848. # hitting a NEWLINE when in a decorator without args
  849. # ends the decorator
  850. if self.indecorator and not self.decoratorhasargs:
  851. self.indecorator = False
  852. elif self.passline:
  853. pass
  854. elif type == tokenize.INDENT:
  855. if self.body_col0 is None and self.started:
  856. self.body_col0 = erowcol[1]
  857. self.indent = self.indent + 1
  858. self.passline = True
  859. elif type == tokenize.DEDENT:
  860. self.indent = self.indent - 1
  861. # the end of matching indent/dedent pairs end a block
  862. # (note that this only works for "def"/"class" blocks,
  863. # not e.g. for "if: else:" or "try: finally:" blocks)
  864. if self.indent <= 0:
  865. raise EndOfBlock
  866. elif type == tokenize.COMMENT:
  867. if self.body_col0 is not None and srowcol[1] >= self.body_col0:
  868. # Include comments if indented at least as much as the block
  869. self.last = srowcol[0]
  870. elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
  871. # any other token on the same indentation level end the previous
  872. # block as well, except the pseudo-tokens COMMENT and NL.
  873. raise EndOfBlock
  874. def getblock(lines):
  875. """Extract the block of code at the top of the given list of lines."""
  876. blockfinder = BlockFinder()
  877. try:
  878. tokens = tokenize.generate_tokens(iter(lines).__next__)
  879. for _token in tokens:
  880. blockfinder.tokeneater(*_token)
  881. except (EndOfBlock, IndentationError):
  882. pass
  883. return lines[:blockfinder.last]
  884. def getsourcelines(object):
  885. """Return a list of source lines and starting line number for an object.
  886. The argument may be a module, class, method, function, traceback, frame,
  887. or code object. The source code is returned as a list of the lines
  888. corresponding to the object and the line number indicates where in the
  889. original source file the first line of code was found. An OSError is
  890. raised if the source code cannot be retrieved."""
  891. object = unwrap(object)
  892. lines, lnum = findsource(object)
  893. if istraceback(object):
  894. object = object.tb_frame
  895. # for module or frame that corresponds to module, return all source lines
  896. if (ismodule(object) or
  897. (isframe(object) and object.f_code.co_name == "<module>")):
  898. return lines, 0
  899. else:
  900. return getblock(lines[lnum:]), lnum + 1
  901. def getsource(object):
  902. """Return the text of the source code for an object.
  903. The argument may be a module, class, method, function, traceback, frame,
  904. or code object. The source code is returned as a single string. An
  905. OSError is raised if the source code cannot be retrieved."""
  906. lines, lnum = getsourcelines(object)
  907. return ''.join(lines)
  908. # --------------------------------------------------- class tree extraction
  909. def walktree(classes, children, parent):
  910. """Recursive helper function for getclasstree()."""
  911. results = []
  912. classes.sort(key=attrgetter('__module__', '__name__'))
  913. for c in classes:
  914. results.append((c, c.__bases__))
  915. if c in children:
  916. results.append(walktree(children[c], children, c))
  917. return results
  918. def getclasstree(classes, unique=False):
  919. """Arrange the given list of classes into a hierarchy of nested lists.
  920. Where a nested list appears, it contains classes derived from the class
  921. whose entry immediately precedes the list. Each entry is a 2-tuple
  922. containing a class and a tuple of its base classes. If the 'unique'
  923. argument is true, exactly one entry appears in the returned structure
  924. for each class in the given list. Otherwise, classes using multiple
  925. inheritance and their descendants will appear multiple times."""
  926. children = {}
  927. roots = []
  928. for c in classes:
  929. if c.__bases__:
  930. for parent in c.__bases__:
  931. if parent not in children:
  932. children[parent] = []
  933. if c not in children[parent]:
  934. children[parent].append(c)
  935. if unique and parent in classes: break
  936. elif c not in roots:
  937. roots.append(c)
  938. for parent in children:
  939. if parent not in classes:
  940. roots.append(parent)
  941. return walktree(roots, children, None)
  942. # ------------------------------------------------ argument list extraction
  943. Arguments = namedtuple('Arguments', 'args, varargs, varkw')
  944. def getargs(co):
  945. """Get information about the arguments accepted by a code object.
  946. Three things are returned: (args, varargs, varkw), where
  947. 'args' is the list of argument names. Keyword-only arguments are
  948. appended. 'varargs' and 'varkw' are the names of the * and **
  949. arguments or None."""
  950. if not iscode(co):
  951. raise TypeError('{!r} is not a code object'.format(co))
  952. names = co.co_varnames
  953. nargs = co.co_argcount
  954. nkwargs = co.co_kwonlyargcount
  955. args = list(names[:nargs])
  956. kwonlyargs = list(names[nargs:nargs+nkwargs])
  957. step = 0
  958. nargs += nkwargs
  959. varargs = None
  960. if co.co_flags & CO_VARARGS:
  961. varargs = co.co_varnames[nargs]
  962. nargs = nargs + 1
  963. varkw = None
  964. if co.co_flags & CO_VARKEYWORDS:
  965. varkw = co.co_varnames[nargs]
  966. return Arguments(args + kwonlyargs, varargs, varkw)
  967. ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
  968. def getargspec(func):
  969. """Get the names and default values of a function's parameters.
  970. A tuple of four things is returned: (args, varargs, keywords, defaults).
  971. 'args' is a list of the argument names, including keyword-only argument names.
  972. 'varargs' and 'keywords' are the names of the * and ** parameters or None.
  973. 'defaults' is an n-tuple of the default values of the last n parameters.
  974. This function is deprecated, as it does not support annotations or
  975. keyword-only parameters and will raise ValueError if either is present
  976. on the supplied callable.
  977. For a more structured introspection API, use inspect.signature() instead.
  978. Alternatively, use getfullargspec() for an API with a similar namedtuple
  979. based interface, but full support for annotations and keyword-only
  980. parameters.
  981. Deprecated since Python 3.5, use `inspect.getfullargspec()`.
  982. """
  983. warnings.warn("inspect.getargspec() is deprecated since Python 3.0, "
  984. "use inspect.signature() or inspect.getfullargspec()",
  985. DeprecationWarning, stacklevel=2)
  986. args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
  987. getfullargspec(func)
  988. if kwonlyargs or ann:
  989. raise ValueError("Function has keyword-only parameters or annotations"
  990. ", use inspect.signature() API which can support them")
  991. return ArgSpec(args, varargs, varkw, defaults)
  992. FullArgSpec = namedtuple('FullArgSpec',
  993. 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
  994. def getfullargspec(func):
  995. """Get the names and default values of a callable object's parameters.
  996. A tuple of seven things is returned:
  997. (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
  998. 'args' is a list of the parameter names.
  999. 'varargs' and 'varkw' are the names of the * and ** parameters or None.
  1000. 'defaults' is an n-tuple of the default values of the last n parameters.
  1001. 'kwonlyargs' is a list of keyword-only parameter names.
  1002. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
  1003. 'annotations' is a dictionary mapping parameter names to annotations.
  1004. Notable differences from inspect.signature():
  1005. - the "self" parameter is always reported, even for bound methods
  1006. - wrapper chains defined by __wrapped__ *not* unwrapped automatically
  1007. """
  1008. try:
  1009. # Re: `skip_bound_arg=False`
  1010. #
  1011. # There is a notable difference in behaviour between getfullargspec
  1012. # and Signature: the former always returns 'self' parameter for bound
  1013. # methods, whereas the Signature always shows the actual calling
  1014. # signature of the passed object.
  1015. #
  1016. # To simulate this behaviour, we "unbind" bound methods, to trick
  1017. # inspect.signature to always return their first parameter ("self",
  1018. # usually)
  1019. # Re: `follow_wrapper_chains=False`
  1020. #
  1021. # getfullargspec() historically ignored __wrapped__ attributes,
  1022. # so we ensure that remains the case in 3.3+
  1023. sig = _signature_from_callable(func,
  1024. follow_wrapper_chains=False,
  1025. skip_bound_arg=False,
  1026. sigcls=Signature)
  1027. except Exception as ex:
  1028. # Most of the times 'signature' will raise ValueError.
  1029. # But, it can also raise AttributeError, and, maybe something
  1030. # else. So to be fully backwards compatible, we catch all
  1031. # possible exceptions here, and reraise a TypeError.
  1032. raise TypeError('unsupported callable') from ex
  1033. args = []
  1034. varargs = None
  1035. varkw = None
  1036. posonlyargs = []
  1037. kwonlyargs = []
  1038. annotations = {}
  1039. defaults = ()
  1040. kwdefaults = {}
  1041. if sig.return_annotation is not sig.empty:
  1042. annotations['return'] = sig.return_annotation
  1043. for param in sig.parameters.values():
  1044. kind = param.kind
  1045. name = param.name
  1046. if kind is _POSITIONAL_ONLY:
  1047. posonlyargs.append(name)
  1048. if param.default is not param.empty:
  1049. defaults += (param.default,)
  1050. elif kind is _POSITIONAL_OR_KEYWORD:
  1051. args.append(name)
  1052. if param.default is not param.empty:
  1053. defaults += (param.default,)
  1054. elif kind is _VAR_POSITIONAL:
  1055. varargs = name
  1056. elif kind is _KEYWORD_ONLY:
  1057. kwonlyargs.append(name)
  1058. if param.default is not param.empty:
  1059. kwdefaults[name] = param.default
  1060. elif kind is _VAR_KEYWORD:
  1061. varkw = name
  1062. if param.annotation is not param.empty:
  1063. annotations[name] = param.annotation
  1064. if not kwdefaults:
  1065. # compatibility with 'func.__kwdefaults__'
  1066. kwdefaults = None
  1067. if not defaults:
  1068. # compatibility with 'func.__defaults__'
  1069. defaults = None
  1070. return FullArgSpec(posonlyargs + args, varargs, varkw, defaults,
  1071. kwonlyargs, kwdefaults, annotations)
  1072. ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
  1073. def getargvalues(frame):
  1074. """Get information about arguments passed into a particular frame.
  1075. A tuple of four things is returned: (args, varargs, varkw, locals).
  1076. 'args' is a list of the argument names.
  1077. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  1078. 'locals' is the locals dictionary of the given frame."""
  1079. args, varargs, varkw = getargs(frame.f_code)
  1080. return ArgInfo(args, varargs, varkw, frame.f_locals)
  1081. def formatannotation(annotation, base_module=None):
  1082. if getattr(annotation, '__module__', None) == 'typing':
  1083. return repr(annotation).replace('typing.', '')
  1084. if isinstance(annotation, type):
  1085. if annotation.__module__ in ('builtins', base_module):
  1086. return annotation.__qualname__
  1087. return annotation.__module__+'.'+annotation.__qualname__
  1088. return repr(annotation)
  1089. def formatannotationrelativeto(object):
  1090. module = getattr(object, '__module__', None)
  1091. def _formatannotation(annotation):
  1092. return formatannotation(annotation, module)
  1093. return _formatannotation
  1094. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  1095. kwonlyargs=(), kwonlydefaults={}, annotations={},
  1096. formatarg=str,
  1097. formatvarargs=lambda name: '*' + name,
  1098. formatvarkw=lambda name: '**' + name,
  1099. formatvalue=lambda value: '=' + repr(value),
  1100. formatreturns=lambda text: ' -> ' + text,
  1101. formatannotation=formatannotation):
  1102. """Format an argument spec from the values returned by getfullargspec.
  1103. The first seven arguments are (args, varargs, varkw, defaults,
  1104. kwonlyargs, kwonlydefaults, annotations). The other five arguments
  1105. are the corresponding optional formatting functions that are called to
  1106. turn names and values into strings. The last argument is an optional
  1107. function to format the sequence of arguments.
  1108. Deprecated since Python 3.5: use the `signature` function and `Signature`
  1109. objects.
  1110. """
  1111. from warnings import warn
  1112. warn("`formatargspec` is deprecated since Python 3.5. Use `signature` and "
  1113. "the `Signature` object directly",
  1114. DeprecationWarning,
  1115. stacklevel=2)
  1116. def formatargandannotation(arg):
  1117. result = formatarg(arg)
  1118. if arg in annotations:
  1119. result += ': ' + formatannotation(annotations[arg])
  1120. return result
  1121. specs = []
  1122. if defaults:
  1123. firstdefault = len(args) - len(defaults)
  1124. for i, arg in enumerate(args):
  1125. spec = formatargandannotation(arg)
  1126. if defaults and i >= firstdefault:
  1127. spec = spec + formatvalue(defaults[i - firstdefault])
  1128. specs.append(spec)
  1129. if varargs is not None:
  1130. specs.append(formatvarargs(formatargandannotation(varargs)))
  1131. else:
  1132. if kwonlyargs:
  1133. specs.append('*')
  1134. if kwonlyargs:
  1135. for kwonlyarg in kwonlyargs:
  1136. spec = formatargandannotation(kwonlyarg)
  1137. if kwonlydefaults and kwonlyarg in kwonlydefaults:
  1138. spec += formatvalue(kwonlydefaults[kwonlyarg])
  1139. specs.append(spec)
  1140. if varkw is not None:
  1141. specs.append(formatvarkw(formatargandannotation(varkw)))
  1142. result = '(' + ', '.join(specs) + ')'
  1143. if 'return' in annotations:
  1144. result += formatreturns(formatannotation(annotations['return']))
  1145. return result
  1146. def formatargvalues(args, varargs, varkw, locals,
  1147. formatarg=str,
  1148. formatvarargs=lambda name: '*' + name,
  1149. formatvarkw=lambda name: '**' + name,
  1150. formatvalue=lambda value: '=' + repr(value)):
  1151. """Format an argument spec from the 4 values returned by getargvalues.
  1152. The first four arguments are (args, varargs, varkw, locals). The
  1153. next four arguments are the corresponding optional formatting functions
  1154. that are called to turn names and values into strings. The ninth
  1155. argument is an optional function to format the sequence of arguments."""
  1156. def convert(name, locals=locals,
  1157. formatarg=formatarg, formatvalue=formatvalue):
  1158. return formatarg(name) + formatvalue(locals[name])
  1159. specs = []
  1160. for i in range(len(args)):
  1161. specs.append(convert(args[i]))
  1162. if varargs:
  1163. specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  1164. if varkw:
  1165. specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  1166. return '(' + ', '.join(specs) + ')'
  1167. def _missing_arguments(f_name, argnames, pos, values):
  1168. names = [repr(name) for name in argnames if name not in values]
  1169. missing = len(names)
  1170. if missing == 1:
  1171. s = names[0]
  1172. elif missing == 2:
  1173. s = "{} and {}".format(*names)
  1174. else:
  1175. tail = ", {} and {}".format(*names[-2:])
  1176. del names[-2:]
  1177. s = ", ".join(names) + tail
  1178. raise TypeError("%s() missing %i required %s argument%s: %s" %
  1179. (f_name, missing,
  1180. "positional" if pos else "keyword-only",
  1181. "" if missing == 1 else "s", s))
  1182. def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
  1183. atleast = len(args) - defcount
  1184. kwonly_given = len([arg for arg in kwonly if arg in values])
  1185. if varargs:
  1186. plural = atleast != 1
  1187. sig = "at least %d" % (atleast,)
  1188. elif defcount:
  1189. plural = True
  1190. sig = "from %d to %d" % (atleast, len(args))
  1191. else:
  1192. plural = len(args) != 1
  1193. sig = str(len(args))
  1194. kwonly_sig = ""
  1195. if kwonly_given:
  1196. msg = " positional argument%s (and %d keyword-only argument%s)"
  1197. kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
  1198. "s" if kwonly_given != 1 else ""))
  1199. raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
  1200. (f_name, sig, "s" if plural else "", given, kwonly_sig,
  1201. "was" if given == 1 and not kwonly_given else "were"))
  1202. def getcallargs(func, /, *positional, **named):
  1203. """Get the mapping of arguments to values.
  1204. A dict is returned, with keys the function argument names (including the
  1205. names of the * and ** arguments, if any), and values the respective bound
  1206. values from 'positional' and 'named'."""
  1207. spec = getfullargspec(func)
  1208. args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
  1209. f_name = func.__name__
  1210. arg2value = {}
  1211. if ismethod(func) and func.__self__ is not None:
  1212. # implicit 'self' (or 'cls' for classmethods) argument
  1213. positional = (func.__self__,) + positional
  1214. num_pos = len(positional)
  1215. num_args = len(args)
  1216. num_defaults = len(defaults) if defaults else 0
  1217. n = min(num_pos, num_args)
  1218. for i in range(n):
  1219. arg2value[args[i]] = positional[i]
  1220. if varargs:
  1221. arg2value[varargs] = tuple(positional[n:])
  1222. possible_kwargs = set(args + kwonlyargs)
  1223. if varkw:
  1224. arg2value[varkw] = {}
  1225. for kw, value in named.items():
  1226. if kw not in possible_kwargs:
  1227. if not varkw:
  1228. raise TypeError("%s() got an unexpected keyword argument %r" %
  1229. (f_name, kw))
  1230. arg2value[varkw][kw] = value
  1231. continue
  1232. if kw in arg2value:
  1233. raise TypeError("%s() got multiple values for argument %r" %
  1234. (f_name, kw))
  1235. arg2value[kw] = value
  1236. if num_pos > num_args and not varargs:
  1237. _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
  1238. num_pos, arg2value)
  1239. if num_pos < num_args:
  1240. req = args[:num_args - num_defaults]
  1241. for arg in req:
  1242. if arg not in arg2value:
  1243. _missing_arguments(f_name, req, True, arg2value)
  1244. for i, arg in enumerate(args[num_args - num_defaults:]):
  1245. if arg not in arg2value:
  1246. arg2value[arg] = defaults[i]
  1247. missing = 0
  1248. for kwarg in kwonlyargs:
  1249. if kwarg not in arg2value:
  1250. if kwonlydefaults and kwarg in kwonlydefaults:
  1251. arg2value[kwarg] = kwonlydefaults[kwarg]
  1252. else:
  1253. missing += 1
  1254. if missing:
  1255. _missing_arguments(f_name, kwonlyargs, False, arg2value)
  1256. return arg2value
  1257. ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
  1258. def getclosurevars(func):
  1259. """
  1260. Get the mapping of free variables to their current values.
  1261. Returns a named tuple of dicts mapping the current nonlocal, global
  1262. and builtin references as seen by the body of the function. A final
  1263. set of unbound names that could not be resolved is also provided.
  1264. """
  1265. if ismethod(func):
  1266. func = func.__func__
  1267. if not isfunction(func):
  1268. raise TypeError("{!r} is not a Python function".format(func))
  1269. code = func.__code__
  1270. # Nonlocal references are named in co_freevars and resolved
  1271. # by looking them up in __closure__ by positional index
  1272. if func.__closure__ is None:
  1273. nonlocal_vars = {}
  1274. else:
  1275. nonlocal_vars = {
  1276. var : cell.cell_contents
  1277. for var, cell in zip(code.co_freevars, func.__closure__)
  1278. }
  1279. # Global and builtin references are named in co_names and resolved
  1280. # by looking them up in __globals__ or __builtins__
  1281. global_ns = func.__globals__
  1282. builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
  1283. if ismodule(builtin_ns):
  1284. builtin_ns = builtin_ns.__dict__
  1285. global_vars = {}
  1286. builtin_vars = {}
  1287. unbound_names = set()
  1288. for name in code.co_names:
  1289. if name in ("None", "True", "False"):
  1290. # Because these used to be builtins instead of keywords, they
  1291. # may still show up as name references. We ignore them.
  1292. continue
  1293. try:
  1294. global_vars[name] = global_ns[name]
  1295. except KeyError:
  1296. try:
  1297. builtin_vars[name] = builtin_ns[name]
  1298. except KeyError:
  1299. unbound_names.add(name)
  1300. return ClosureVars(nonlocal_vars, global_vars,
  1301. builtin_vars, unbound_names)
  1302. # -------------------------------------------------- stack frame extraction
  1303. Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
  1304. def getframeinfo(frame, context=1):
  1305. """Get information about a frame or traceback object.
  1306. A tuple of five things is returned: the filename, the line number of
  1307. the current line, the function name, a list of lines of context from
  1308. the source code, and the index of the current line within that list.
  1309. The optional second argument specifies the number of lines of context
  1310. to return, which are centered around the current line."""
  1311. if istraceback(frame):
  1312. lineno = frame.tb_lineno
  1313. frame = frame.tb_frame
  1314. else:
  1315. lineno = frame.f_lineno
  1316. if not isframe(frame):
  1317. raise TypeError('{!r} is not a frame or traceback object'.format(frame))
  1318. filename = getsourcefile(frame) or getfile(frame)
  1319. if context > 0:
  1320. start = lineno - 1 - context//2
  1321. try:
  1322. lines, lnum = findsource(frame)
  1323. except OSError:
  1324. lines = index = None
  1325. else:
  1326. start = max(0, min(start, len(lines) - context))
  1327. lines = lines[start:start+context]
  1328. index = lineno - 1 - start
  1329. else:
  1330. lines = index = None
  1331. return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
  1332. def getlineno(frame):
  1333. """Get the line number from a frame object, allowing for optimization."""
  1334. # FrameType.f_lineno is now a descriptor that grovels co_lnotab
  1335. return frame.f_lineno
  1336. FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
  1337. def getouterframes(frame, context=1):
  1338. """Get a list of records for a frame and all higher (calling) frames.
  1339. Each record contains a frame object, filename, line number, function
  1340. name, a list of lines of context, and index within the context."""
  1341. framelist = []
  1342. while frame:
  1343. frameinfo = (frame,) + getframeinfo(frame, context)
  1344. framelist.append(FrameInfo(*frameinfo))
  1345. frame = frame.f_back
  1346. return framelist
  1347. def getinnerframes(tb, context=1):
  1348. """Get a list of records for a traceback's frame and all lower frames.
  1349. Each record contains a frame object, filename, line number, function
  1350. name, a list of lines of context, and index within the context."""
  1351. framelist = []
  1352. while tb:
  1353. frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
  1354. framelist.append(FrameInfo(*frameinfo))
  1355. tb = tb.tb_next
  1356. return framelist
  1357. def currentframe():
  1358. """Return the frame of the caller or None if this is not possible."""
  1359. return sys._getframe(1) if hasattr(sys, "_getframe") else None
  1360. def stack(context=1):
  1361. """Return a list of records for the stack above the caller's frame."""
  1362. return getouterframes(sys._getframe(1), context)
  1363. def trace(context=1):
  1364. """Return a list of records for the stack below the current exception."""
  1365. return getinnerframes(sys.exc_info()[2], context)
  1366. # ------------------------------------------------ static version of getattr
  1367. _sentinel = object()
  1368. def _static_getmro(klass):
  1369. return type.__dict__['__mro__'].__get__(klass)
  1370. def _check_instance(obj, attr):
  1371. instance_dict = {}
  1372. try:
  1373. instance_dict = object.__getattribute__(obj, "__dict__")
  1374. except AttributeError:
  1375. pass
  1376. return dict.get(instance_dict, attr, _sentinel)
  1377. def _check_class(klass, attr):
  1378. for entry in _static_getmro(klass):
  1379. if _shadowed_dict(type(entry)) is _sentinel:
  1380. try:
  1381. return entry.__dict__[attr]
  1382. except KeyError:
  1383. pass
  1384. return _sentinel
  1385. def _is_type(obj):
  1386. try:
  1387. _static_getmro(obj)
  1388. except TypeError:
  1389. return False
  1390. return True
  1391. def _shadowed_dict(klass):
  1392. dict_attr = type.__dict__["__dict__"]
  1393. for entry in _static_getmro(klass):
  1394. try:
  1395. class_dict = dict_attr.__get__(entry)["__dict__"]
  1396. except KeyError:
  1397. pass
  1398. else:
  1399. if not (type(class_dict) is types.GetSetDescriptorType and
  1400. class_dict.__name__ == "__dict__" and
  1401. class_dict.__objclass__ is entry):
  1402. return class_dict
  1403. return _sentinel
  1404. def getattr_static(obj, attr, default=_sentinel):
  1405. """Retrieve attributes without triggering dynamic lookup via the
  1406. descriptor protocol, __getattr__ or __getattribute__.
  1407. Note: this function may not be able to retrieve all attributes
  1408. that getattr can fetch (like dynamically created attributes)
  1409. and may find attributes that getattr can't (like descriptors
  1410. that raise AttributeError). It can also return descriptor objects
  1411. instead of instance members in some cases. See the
  1412. documentation for details.
  1413. """
  1414. instance_result = _sentinel
  1415. if not _is_type(obj):
  1416. klass = type(obj)
  1417. dict_attr = _shadowed_dict(klass)
  1418. if (dict_attr is _sentinel or
  1419. type(dict_attr) is types.MemberDescriptorType):
  1420. instance_result = _check_instance(obj, attr)
  1421. else:
  1422. klass = obj
  1423. klass_result = _check_class(klass, attr)
  1424. if instance_result is not _sentinel and klass_result is not _sentinel:
  1425. if (_check_class(type(klass_result), '__get__') is not _sentinel and
  1426. _check_class(type(klass_result), '__set__') is not _sentinel):
  1427. return klass_result
  1428. if instance_result is not _sentinel:
  1429. return instance_result
  1430. if klass_result is not _sentinel:
  1431. return klass_result
  1432. if obj is klass:
  1433. # for types we check the metaclass too
  1434. for entry in _static_getmro(type(klass)):
  1435. if _shadowed_dict(type(entry)) is _sentinel:
  1436. try:
  1437. return entry.__dict__[attr]
  1438. except KeyError:
  1439. pass
  1440. if default is not _sentinel:
  1441. return default
  1442. raise AttributeError(attr)
  1443. # ------------------------------------------------ generator introspection
  1444. GEN_CREATED = 'GEN_CREATED'
  1445. GEN_RUNNING = 'GEN_RUNNING'
  1446. GEN_SUSPENDED = 'GEN_SUSPENDED'
  1447. GEN_CLOSED = 'GEN_CLOSED'
  1448. def getgeneratorstate(generator):
  1449. """Get current state of a generator-iterator.
  1450. Possible states are:
  1451. GEN_CREATED: Waiting to start execution.
  1452. GEN_RUNNING: Currently being executed by the interpreter.
  1453. GEN_SUSPENDED: Currently suspended at a yield expression.
  1454. GEN_CLOSED: Execution has completed.
  1455. """
  1456. if generator.gi_running:
  1457. return GEN_RUNNING
  1458. if generator.gi_frame is None:
  1459. return GEN_CLOSED
  1460. if generator.gi_frame.f_lasti == -1:
  1461. return GEN_CREATED
  1462. return GEN_SUSPENDED
  1463. def getgeneratorlocals(generator):
  1464. """
  1465. Get the mapping of generator local variables to their current values.
  1466. A dict is returned, with the keys the local variable names and values the
  1467. bound values."""
  1468. if not isgenerator(generator):
  1469. raise TypeError("{!r} is not a Python generator".format(generator))
  1470. frame = getattr(generator, "gi_frame", None)
  1471. if frame is not None:
  1472. return generator.gi_frame.f_locals
  1473. else:
  1474. return {}
  1475. # ------------------------------------------------ coroutine introspection
  1476. CORO_CREATED = 'CORO_CREATED'
  1477. CORO_RUNNING = 'CORO_RUNNING'
  1478. CORO_SUSPENDED = 'CORO_SUSPENDED'
  1479. CORO_CLOSED = 'CORO_CLOSED'
  1480. def getcoroutinestate(coroutine):
  1481. """Get current state of a coroutine object.
  1482. Possible states are:
  1483. CORO_CREATED: Waiting to start execution.
  1484. CORO_RUNNING: Currently being executed by the interpreter.
  1485. CORO_SUSPENDED: Currently suspended at an await expression.
  1486. CORO_CLOSED: Execution has completed.
  1487. """
  1488. if coroutine.cr_running:
  1489. return CORO_RUNNING
  1490. if coroutine.cr_frame is None:
  1491. return CORO_CLOSED
  1492. if coroutine.cr_frame.f_lasti == -1:
  1493. return CORO_CREATED
  1494. return CORO_SUSPENDED
  1495. def getcoroutinelocals(coroutine):
  1496. """
  1497. Get the mapping of coroutine local variables to their current values.
  1498. A dict is returned, with the keys the local variable names and values the
  1499. bound values."""
  1500. frame = getattr(coroutine, "cr_frame", None)
  1501. if frame is not None:
  1502. return frame.f_locals
  1503. else:
  1504. return {}
  1505. ###############################################################################
  1506. ### Function Signature Object (PEP 362)
  1507. ###############################################################################
  1508. _WrapperDescriptor = type(type.__call__)
  1509. _MethodWrapper = type(all.__call__)
  1510. _ClassMethodWrapper = type(int.__dict__['from_bytes'])
  1511. _NonUserDefinedCallables = (_WrapperDescriptor,
  1512. _MethodWrapper,
  1513. _ClassMethodWrapper,
  1514. types.BuiltinFunctionType)
  1515. def _signature_get_user_defined_method(cls, method_name):
  1516. """Private helper. Checks if ``cls`` has an attribute
  1517. named ``method_name`` and returns it only if it is a
  1518. pure python function.
  1519. """
  1520. try:
  1521. meth = getattr(cls, method_name)
  1522. except AttributeError:
  1523. return
  1524. else:
  1525. if not isinstance(meth, _NonUserDefinedCallables):
  1526. # Once '__signature__' will be added to 'C'-level
  1527. # callables, this check won't be necessary
  1528. return meth
  1529. def _signature_get_partial(wrapped_sig, partial, extra_args=()):
  1530. """Private helper to calculate how 'wrapped_sig' signature will
  1531. look like after applying a 'functools.partial' object (or alike)
  1532. on it.
  1533. """
  1534. old_params = wrapped_sig.parameters
  1535. new_params = OrderedDict(old_params.items())
  1536. partial_args = partial.args or ()
  1537. partial_keywords = partial.keywords or {}
  1538. if extra_args:
  1539. partial_args = extra_args + partial_args
  1540. try:
  1541. ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
  1542. except TypeError as ex:
  1543. msg = 'partial object {!r} has incorrect arguments'.format(partial)
  1544. raise ValueError(msg) from ex
  1545. transform_to_kwonly = False
  1546. for param_name, param in old_params.items():
  1547. try:
  1548. arg_value = ba.arguments[param_name]
  1549. except KeyError:
  1550. pass
  1551. else:
  1552. if param.kind is _POSITIONAL_ONLY:
  1553. # If positional-only parameter is bound by partial,
  1554. # it effectively disappears from the signature
  1555. new_params.pop(param_name)
  1556. continue
  1557. if param.kind is _POSITIONAL_OR_KEYWORD:
  1558. if param_name in partial_keywords:
  1559. # This means that this parameter, and all parameters
  1560. # after it should be keyword-only (and var-positional
  1561. # should be removed). Here's why. Consider the following
  1562. # function:
  1563. # foo(a, b, *args, c):
  1564. # pass
  1565. #
  1566. # "partial(foo, a='spam')" will have the following
  1567. # signature: "(*, a='spam', b, c)". Because attempting
  1568. # to call that partial with "(10, 20)" arguments will
  1569. # raise a TypeError, saying that "a" argument received
  1570. # multiple values.
  1571. transform_to_kwonly = True
  1572. # Set the new default value
  1573. new_params[param_name] = param.replace(default=arg_value)
  1574. else:
  1575. # was passed as a positional argument
  1576. new_params.pop(param.name)
  1577. continue
  1578. if param.kind is _KEYWORD_ONLY:
  1579. # Set the new default value
  1580. new_params[param_name] = param.replace(default=arg_value)
  1581. if transform_to_kwonly:
  1582. assert param.kind is not _POSITIONAL_ONLY
  1583. if param.kind is _POSITIONAL_OR_KEYWORD:
  1584. new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
  1585. new_params[param_name] = new_param
  1586. new_params.move_to_end(param_name)
  1587. elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
  1588. new_params.move_to_end(param_name)
  1589. elif param.kind is _VAR_POSITIONAL:
  1590. new_params.pop(param.name)
  1591. return wrapped_sig.replace(parameters=new_params.values())
  1592. def _signature_bound_method(sig):
  1593. """Private helper to transform signatures for unbound
  1594. functions to bound methods.
  1595. """
  1596. params = tuple(sig.parameters.values())
  1597. if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  1598. raise ValueError('invalid method signature')
  1599. kind = params[0].kind
  1600. if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
  1601. # Drop first parameter:
  1602. # '(p1, p2[, ...])' -> '(p2[, ...])'
  1603. params = params[1:]
  1604. else:
  1605. if kind is not _VAR_POSITIONAL:
  1606. # Unless we add a new parameter type we never
  1607. # get here
  1608. raise ValueError('invalid argument type')
  1609. # It's a var-positional parameter.
  1610. # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
  1611. return sig.replace(parameters=params)
  1612. def _signature_is_builtin(obj):
  1613. """Private helper to test if `obj` is a callable that might
  1614. support Argument Clinic's __text_signature__ protocol.
  1615. """
  1616. return (isbuiltin(obj) or
  1617. ismethoddescriptor(obj) or
  1618. isinstance(obj, _NonUserDefinedCallables) or
  1619. # Can't test 'isinstance(type)' here, as it would
  1620. # also be True for regular python classes
  1621. obj in (type, object))
  1622. def _signature_is_functionlike(obj):
  1623. """Private helper to test if `obj` is a duck type of FunctionType.
  1624. A good example of such objects are functions compiled with
  1625. Cython, which have all attributes that a pure Python function
  1626. would have, but have their code statically compiled.
  1627. """
  1628. if not callable(obj) or isclass(obj):
  1629. # All function-like objects are obviously callables,
  1630. # and not classes.
  1631. return False
  1632. name = getattr(obj, '__name__', None)
  1633. code = getattr(obj, '__code__', None)
  1634. defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
  1635. kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
  1636. annotations = getattr(obj, '__annotations__', None)
  1637. return (isinstance(code, types.CodeType) and
  1638. isinstance(name, str) and
  1639. (defaults is None or isinstance(defaults, tuple)) and
  1640. (kwdefaults is None or isinstance(kwdefaults, dict)) and
  1641. isinstance(annotations, dict))
  1642. def _signature_get_bound_param(spec):
  1643. """ Private helper to get first parameter name from a
  1644. __text_signature__ of a builtin method, which should
  1645. be in the following format: '($param1, ...)'.
  1646. Assumptions are that the first argument won't have
  1647. a default value or an annotation.
  1648. """
  1649. assert spec.startswith('($')
  1650. pos = spec.find(',')
  1651. if pos == -1:
  1652. pos = spec.find(')')
  1653. cpos = spec.find(':')
  1654. assert cpos == -1 or cpos > pos
  1655. cpos = spec.find('=')
  1656. assert cpos == -1 or cpos > pos
  1657. return spec[2:pos]
  1658. def _signature_strip_non_python_syntax(signature):
  1659. """
  1660. Private helper function. Takes a signature in Argument Clinic's
  1661. extended signature format.
  1662. Returns a tuple of three things:
  1663. * that signature re-rendered in standard Python syntax,
  1664. * the index of the "self" parameter (generally 0), or None if
  1665. the function does not have a "self" parameter, and
  1666. * the index of the last "positional only" parameter,
  1667. or None if the signature has no positional-only parameters.
  1668. """
  1669. if not signature:
  1670. return signature, None, None
  1671. self_parameter = None
  1672. last_positional_only = None
  1673. lines = [l.encode('ascii') for l in signature.split('\n')]
  1674. generator = iter(lines).__next__
  1675. token_stream = tokenize.tokenize(generator)
  1676. delayed_comma = False
  1677. skip_next_comma = False
  1678. text = []
  1679. add = text.append
  1680. current_parameter = 0
  1681. OP = token.OP
  1682. ERRORTOKEN = token.ERRORTOKEN
  1683. # token stream always starts with ENCODING token, skip it
  1684. t = next(token_stream)
  1685. assert t.type == tokenize.ENCODING
  1686. for t in token_stream:
  1687. type, string = t.type, t.string
  1688. if type == OP:
  1689. if string == ',':
  1690. if skip_next_comma:
  1691. skip_next_comma = False
  1692. else:
  1693. assert not delayed_comma
  1694. delayed_comma = True
  1695. current_parameter += 1
  1696. continue
  1697. if string == '/':
  1698. assert not skip_next_comma
  1699. assert last_positional_only is None
  1700. skip_next_comma = True
  1701. last_positional_only = current_parameter - 1
  1702. continue
  1703. if (type == ERRORTOKEN) and (string == '$'):
  1704. assert self_parameter is None
  1705. self_parameter = current_parameter
  1706. continue
  1707. if delayed_comma:
  1708. delayed_comma = False
  1709. if not ((type == OP) and (string == ')')):
  1710. add(', ')
  1711. add(string)
  1712. if (string == ','):
  1713. add(' ')
  1714. clean_signature = ''.join(text)
  1715. return clean_signature, self_parameter, last_positional_only
  1716. def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
  1717. """Private helper to parse content of '__text_signature__'
  1718. and return a Signature based on it.
  1719. """
  1720. # Lazy import ast because it's relatively heavy and
  1721. # it's not used for other than this function.
  1722. import ast
  1723. Parameter = cls._parameter_cls
  1724. clean_signature, self_parameter, last_positional_only = \
  1725. _signature_strip_non_python_syntax(s)
  1726. program = "def foo" + clean_signature + ": pass"
  1727. try:
  1728. module = ast.parse(program)
  1729. except SyntaxError:
  1730. module = None
  1731. if not isinstance(module, ast.Module):
  1732. raise ValueError("{!r} builtin has invalid signature".format(obj))
  1733. f = module.body[0]
  1734. parameters = []
  1735. empty = Parameter.empty
  1736. invalid = object()
  1737. module = None
  1738. module_dict = {}
  1739. module_name = getattr(obj, '__module__', None)
  1740. if module_name:
  1741. module = sys.modules.get(module_name, None)
  1742. if module:
  1743. module_dict = module.__dict__
  1744. sys_module_dict = sys.modules.copy()
  1745. def parse_name(node):
  1746. assert isinstance(node, ast.arg)
  1747. if node.annotation is not None:
  1748. raise ValueError("Annotations are not currently supported")
  1749. return node.arg
  1750. def wrap_value(s):
  1751. try:
  1752. value = eval(s, module_dict)
  1753. except NameError:
  1754. try:
  1755. value = eval(s, sys_module_dict)
  1756. except NameError:
  1757. raise RuntimeError()
  1758. if isinstance(value, (str, int, float, bytes, bool, type(None))):
  1759. return ast.Constant(value)
  1760. raise RuntimeError()
  1761. class RewriteSymbolics(ast.NodeTransformer):
  1762. def visit_Attribute(self, node):
  1763. a = []
  1764. n = node
  1765. while isinstance(n, ast.Attribute):
  1766. a.append(n.attr)
  1767. n = n.value
  1768. if not isinstance(n, ast.Name):
  1769. raise RuntimeError()
  1770. a.append(n.id)
  1771. value = ".".join(reversed(a))
  1772. return wrap_value(value)
  1773. def visit_Name(self, node):
  1774. if not isinstance(node.ctx, ast.Load):
  1775. raise ValueError()
  1776. return wrap_value(node.id)
  1777. def p(name_node, default_node, default=empty):
  1778. name = parse_name(name_node)
  1779. if name is invalid:
  1780. return None
  1781. if default_node and default_node is not _empty:
  1782. try:
  1783. default_node = RewriteSymbolics().visit(default_node)
  1784. o = ast.literal_eval(default_node)
  1785. except ValueError:
  1786. o = invalid
  1787. if o is invalid:
  1788. return None
  1789. default = o if o is not invalid else default
  1790. parameters.append(Parameter(name, kind, default=default, annotation=empty))
  1791. # non-keyword-only parameters
  1792. args = reversed(f.args.args)
  1793. defaults = reversed(f.args.defaults)
  1794. iter = itertools.zip_longest(args, defaults, fillvalue=None)
  1795. if last_positional_only is not None:
  1796. kind = Parameter.POSITIONAL_ONLY
  1797. else:
  1798. kind = Parameter.POSITIONAL_OR_KEYWORD
  1799. for i, (name, default) in enumerate(reversed(list(iter))):
  1800. p(name, default)
  1801. if i == last_positional_only:
  1802. kind = Parameter.POSITIONAL_OR_KEYWORD
  1803. # *args
  1804. if f.args.vararg:
  1805. kind = Parameter.VAR_POSITIONAL
  1806. p(f.args.vararg, empty)
  1807. # keyword-only arguments
  1808. kind = Parameter.KEYWORD_ONLY
  1809. for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
  1810. p(name, default)
  1811. # **kwargs
  1812. if f.args.kwarg:
  1813. kind = Parameter.VAR_KEYWORD
  1814. p(f.args.kwarg, empty)
  1815. if self_parameter is not None:
  1816. # Possibly strip the bound argument:
  1817. # - We *always* strip first bound argument if
  1818. # it is a module.
  1819. # - We don't strip first bound argument if
  1820. # skip_bound_arg is False.
  1821. assert parameters
  1822. _self = getattr(obj, '__self__', None)
  1823. self_isbound = _self is not None
  1824. self_ismodule = ismodule(_self)
  1825. if self_isbound and (self_ismodule or skip_bound_arg):
  1826. parameters.pop(0)
  1827. else:
  1828. # for builtins, self parameter is always positional-only!
  1829. p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
  1830. parameters[0] = p
  1831. return cls(parameters, return_annotation=cls.empty)
  1832. def _signature_from_builtin(cls, func, skip_bound_arg=True):
  1833. """Private helper function to get signature for
  1834. builtin callables.
  1835. """
  1836. if not _signature_is_builtin(func):
  1837. raise TypeError("{!r} is not a Python builtin "
  1838. "function".format(func))
  1839. s = getattr(func, "__text_signature__", None)
  1840. if not s:
  1841. raise ValueError("no signature found for builtin {!r}".format(func))
  1842. return _signature_fromstr(cls, func, s, skip_bound_arg)
  1843. def _signature_from_function(cls, func, skip_bound_arg=True):
  1844. """Private helper: constructs Signature for the given python function."""
  1845. is_duck_function = False
  1846. if not isfunction(func):
  1847. if _signature_is_functionlike(func):
  1848. is_duck_function = True
  1849. else:
  1850. # If it's not a pure Python function, and not a duck type
  1851. # of pure function:
  1852. raise TypeError('{!r} is not a Python function'.format(func))
  1853. s = getattr(func, "__text_signature__", None)
  1854. if s:
  1855. return _signature_fromstr(cls, func, s, skip_bound_arg)
  1856. Parameter = cls._parameter_cls
  1857. # Parameter information.
  1858. func_code = func.__code__
  1859. pos_count = func_code.co_argcount
  1860. arg_names = func_code.co_varnames
  1861. posonly_count = func_code.co_posonlyargcount
  1862. positional = arg_names[:pos_count]
  1863. keyword_only_count = func_code.co_kwonlyargcount
  1864. keyword_only = arg_names[pos_count:pos_count + keyword_only_count]
  1865. annotations = func.__annotations__
  1866. defaults = func.__defaults__
  1867. kwdefaults = func.__kwdefaults__
  1868. if defaults:
  1869. pos_default_count = len(defaults)
  1870. else:
  1871. pos_default_count = 0
  1872. parameters = []
  1873. non_default_count = pos_count - pos_default_count
  1874. posonly_left = posonly_count
  1875. # Non-keyword-only parameters w/o defaults.
  1876. for name in positional[:non_default_count]:
  1877. kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
  1878. annotation = annotations.get(name, _empty)
  1879. parameters.append(Parameter(name, annotation=annotation,
  1880. kind=kind))
  1881. if posonly_left:
  1882. posonly_left -= 1
  1883. # ... w/ defaults.
  1884. for offset, name in enumerate(positional[non_default_count:]):
  1885. kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
  1886. annotation = annotations.get(name, _empty)
  1887. parameters.append(Parameter(name, annotation=annotation,
  1888. kind=kind,
  1889. default=defaults[offset]))
  1890. if posonly_left:
  1891. posonly_left -= 1
  1892. # *args
  1893. if func_code.co_flags & CO_VARARGS:
  1894. name = arg_names[pos_count + keyword_only_count]
  1895. annotation = annotations.get(name, _empty)
  1896. parameters.append(Parameter(name, annotation=annotation,
  1897. kind=_VAR_POSITIONAL))
  1898. # Keyword-only parameters.
  1899. for name in keyword_only:
  1900. default = _empty
  1901. if kwdefaults is not None:
  1902. default = kwdefaults.get(name, _empty)
  1903. annotation = annotations.get(name, _empty)
  1904. parameters.append(Parameter(name, annotation=annotation,
  1905. kind=_KEYWORD_ONLY,
  1906. default=default))
  1907. # **kwargs
  1908. if func_code.co_flags & CO_VARKEYWORDS:
  1909. index = pos_count + keyword_only_count
  1910. if func_code.co_flags & CO_VARARGS:
  1911. index += 1
  1912. name = arg_names[index]
  1913. annotation = annotations.get(name, _empty)
  1914. parameters.append(Parameter(name, annotation=annotation,
  1915. kind=_VAR_KEYWORD))
  1916. # Is 'func' is a pure Python function - don't validate the
  1917. # parameters list (for correct order and defaults), it should be OK.
  1918. return cls(parameters,
  1919. return_annotation=annotations.get('return', _empty),
  1920. __validate_parameters__=is_duck_function)
  1921. def _signature_from_callable(obj, *,
  1922. follow_wrapper_chains=True,
  1923. skip_bound_arg=True,
  1924. sigcls):
  1925. """Private helper function to get signature for arbitrary
  1926. callable objects.
  1927. """
  1928. if not callable(obj):
  1929. raise TypeError('{!r} is not a callable object'.format(obj))
  1930. if isinstance(obj, types.MethodType):
  1931. # In this case we skip the first parameter of the underlying
  1932. # function (usually `self` or `cls`).
  1933. sig = _signature_from_callable(
  1934. obj.__func__,
  1935. follow_wrapper_chains=follow_wrapper_chains,
  1936. skip_bound_arg=skip_bound_arg,
  1937. sigcls=sigcls)
  1938. if skip_bound_arg:
  1939. return _signature_bound_method(sig)
  1940. else:
  1941. return sig
  1942. # Was this function wrapped by a decorator?
  1943. if follow_wrapper_chains:
  1944. obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
  1945. if isinstance(obj, types.MethodType):
  1946. # If the unwrapped object is a *method*, we might want to
  1947. # skip its first parameter (self).
  1948. # See test_signature_wrapped_bound_method for details.
  1949. return _signature_from_callable(
  1950. obj,
  1951. follow_wrapper_chains=follow_wrapper_chains,
  1952. skip_bound_arg=skip_bound_arg,
  1953. sigcls=sigcls)
  1954. try:
  1955. sig = obj.__signature__
  1956. except AttributeError:
  1957. pass
  1958. else:
  1959. if sig is not None:
  1960. if not isinstance(sig, Signature):
  1961. raise TypeError(
  1962. 'unexpected object {!r} in __signature__ '
  1963. 'attribute'.format(sig))
  1964. return sig
  1965. try:
  1966. partialmethod = obj._partialmethod
  1967. except AttributeError:
  1968. pass
  1969. else:
  1970. if isinstance(partialmethod, functools.partialmethod):
  1971. # Unbound partialmethod (see functools.partialmethod)
  1972. # This means, that we need to calculate the signature
  1973. # as if it's a regular partial object, but taking into
  1974. # account that the first positional argument
  1975. # (usually `self`, or `cls`) will not be passed
  1976. # automatically (as for boundmethods)
  1977. wrapped_sig = _signature_from_callable(
  1978. partialmethod.func,
  1979. follow_wrapper_chains=follow_wrapper_chains,
  1980. skip_bound_arg=skip_bound_arg,
  1981. sigcls=sigcls)
  1982. sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
  1983. first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
  1984. if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
  1985. # First argument of the wrapped callable is `*args`, as in
  1986. # `partialmethod(lambda *args)`.
  1987. return sig
  1988. else:
  1989. sig_params = tuple(sig.parameters.values())
  1990. assert (not sig_params or
  1991. first_wrapped_param is not sig_params[0])
  1992. new_params = (first_wrapped_param,) + sig_params
  1993. return sig.replace(parameters=new_params)
  1994. if isfunction(obj) or _signature_is_functionlike(obj):
  1995. # If it's a pure Python function, or an object that is duck type
  1996. # of a Python function (Cython functions, for instance), then:
  1997. return _signature_from_function(sigcls, obj,
  1998. skip_bound_arg=skip_bound_arg)
  1999. if _signature_is_builtin(obj):
  2000. return _signature_from_builtin(sigcls, obj,
  2001. skip_bound_arg=skip_bound_arg)
  2002. if isinstance(obj, functools.partial):
  2003. wrapped_sig = _signature_from_callable(
  2004. obj.func,
  2005. follow_wrapper_chains=follow_wrapper_chains,
  2006. skip_bound_arg=skip_bound_arg,
  2007. sigcls=sigcls)
  2008. return _signature_get_partial(wrapped_sig, obj)
  2009. sig = None
  2010. if isinstance(obj, type):
  2011. # obj is a class or a metaclass
  2012. # First, let's see if it has an overloaded __call__ defined
  2013. # in its metaclass
  2014. call = _signature_get_user_defined_method(type(obj), '__call__')
  2015. if call is not None:
  2016. sig = _signature_from_callable(
  2017. call,
  2018. follow_wrapper_chains=follow_wrapper_chains,
  2019. skip_bound_arg=skip_bound_arg,
  2020. sigcls=sigcls)
  2021. else:
  2022. # Now we check if the 'obj' class has a '__new__' method
  2023. new = _signature_get_user_defined_method(obj, '__new__')
  2024. if new is not None:
  2025. sig = _signature_from_callable(
  2026. new,
  2027. follow_wrapper_chains=follow_wrapper_chains,
  2028. skip_bound_arg=skip_bound_arg,
  2029. sigcls=sigcls)
  2030. else:
  2031. # Finally, we should have at least __init__ implemented
  2032. init = _signature_get_user_defined_method(obj, '__init__')
  2033. if init is not None:
  2034. sig = _signature_from_callable(
  2035. init,
  2036. follow_wrapper_chains=follow_wrapper_chains,
  2037. skip_bound_arg=skip_bound_arg,
  2038. sigcls=sigcls)
  2039. if sig is None:
  2040. # At this point we know, that `obj` is a class, with no user-
  2041. # defined '__init__', '__new__', or class-level '__call__'
  2042. for base in obj.__mro__[:-1]:
  2043. # Since '__text_signature__' is implemented as a
  2044. # descriptor that extracts text signature from the
  2045. # class docstring, if 'obj' is derived from a builtin
  2046. # class, its own '__text_signature__' may be 'None'.
  2047. # Therefore, we go through the MRO (except the last
  2048. # class in there, which is 'object') to find the first
  2049. # class with non-empty text signature.
  2050. try:
  2051. text_sig = base.__text_signature__
  2052. except AttributeError:
  2053. pass
  2054. else:
  2055. if text_sig:
  2056. # If 'obj' class has a __text_signature__ attribute:
  2057. # return a signature based on it
  2058. return _signature_fromstr(sigcls, obj, text_sig)
  2059. # No '__text_signature__' was found for the 'obj' class.
  2060. # Last option is to check if its '__init__' is
  2061. # object.__init__ or type.__init__.
  2062. if type not in obj.__mro__:
  2063. # We have a class (not metaclass), but no user-defined
  2064. # __init__ or __new__ for it
  2065. if (obj.__init__ is object.__init__ and
  2066. obj.__new__ is object.__new__):
  2067. # Return a signature of 'object' builtin.
  2068. return sigcls.from_callable(object)
  2069. else:
  2070. raise ValueError(
  2071. 'no signature found for builtin type {!r}'.format(obj))
  2072. elif not isinstance(obj, _NonUserDefinedCallables):
  2073. # An object with __call__
  2074. # We also check that the 'obj' is not an instance of
  2075. # _WrapperDescriptor or _MethodWrapper to avoid
  2076. # infinite recursion (and even potential segfault)
  2077. call = _signature_get_user_defined_method(type(obj), '__call__')
  2078. if call is not None:
  2079. try:
  2080. sig = _signature_from_callable(
  2081. call,
  2082. follow_wrapper_chains=follow_wrapper_chains,
  2083. skip_bound_arg=skip_bound_arg,
  2084. sigcls=sigcls)
  2085. except ValueError as ex:
  2086. msg = 'no signature found for {!r}'.format(obj)
  2087. raise ValueError(msg) from ex
  2088. if sig is not None:
  2089. # For classes and objects we skip the first parameter of their
  2090. # __call__, __new__, or __init__ methods
  2091. if skip_bound_arg:
  2092. return _signature_bound_method(sig)
  2093. else:
  2094. return sig
  2095. if isinstance(obj, types.BuiltinFunctionType):
  2096. # Raise a nicer error message for builtins
  2097. msg = 'no signature found for builtin function {!r}'.format(obj)
  2098. raise ValueError(msg)
  2099. raise ValueError('callable {!r} is not supported by signature'.format(obj))
  2100. class _void:
  2101. """A private marker - used in Parameter & Signature."""
  2102. class _empty:
  2103. """Marker object for Signature.empty and Parameter.empty."""
  2104. class _ParameterKind(enum.IntEnum):
  2105. POSITIONAL_ONLY = 0
  2106. POSITIONAL_OR_KEYWORD = 1
  2107. VAR_POSITIONAL = 2
  2108. KEYWORD_ONLY = 3
  2109. VAR_KEYWORD = 4
  2110. def __str__(self):
  2111. return self._name_
  2112. @property
  2113. def description(self):
  2114. return _PARAM_NAME_MAPPING[self]
  2115. _POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
  2116. _POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
  2117. _VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
  2118. _KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
  2119. _VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
  2120. _PARAM_NAME_MAPPING = {
  2121. _POSITIONAL_ONLY: 'positional-only',
  2122. _POSITIONAL_OR_KEYWORD: 'positional or keyword',
  2123. _VAR_POSITIONAL: 'variadic positional',
  2124. _KEYWORD_ONLY: 'keyword-only',
  2125. _VAR_KEYWORD: 'variadic keyword'
  2126. }
  2127. class Parameter:
  2128. """Represents a parameter in a function signature.
  2129. Has the following public attributes:
  2130. * name : str
  2131. The name of the parameter as a string.
  2132. * default : object
  2133. The default value for the parameter if specified. If the
  2134. parameter has no default value, this attribute is set to
  2135. `Parameter.empty`.
  2136. * annotation
  2137. The annotation for the parameter if specified. If the
  2138. parameter has no annotation, this attribute is set to
  2139. `Parameter.empty`.
  2140. * kind : str
  2141. Describes how argument values are bound to the parameter.
  2142. Possible values: `Parameter.POSITIONAL_ONLY`,
  2143. `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
  2144. `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
  2145. """
  2146. __slots__ = ('_name', '_kind', '_default', '_annotation')
  2147. POSITIONAL_ONLY = _POSITIONAL_ONLY
  2148. POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
  2149. VAR_POSITIONAL = _VAR_POSITIONAL
  2150. KEYWORD_ONLY = _KEYWORD_ONLY
  2151. VAR_KEYWORD = _VAR_KEYWORD
  2152. empty = _empty
  2153. def __init__(self, name, kind, *, default=_empty, annotation=_empty):
  2154. try:
  2155. self._kind = _ParameterKind(kind)
  2156. except ValueError:
  2157. raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
  2158. if default is not _empty:
  2159. if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
  2160. msg = '{} parameters cannot have default values'
  2161. msg = msg.format(self._kind.description)
  2162. raise ValueError(msg)
  2163. self._default = default
  2164. self._annotation = annotation
  2165. if name is _empty:
  2166. raise ValueError('name is a required attribute for Parameter')
  2167. if not isinstance(name, str):
  2168. msg = 'name must be a str, not a {}'.format(type(name).__name__)
  2169. raise TypeError(msg)
  2170. if name[0] == '.' and name[1:].isdigit():
  2171. # These are implicit arguments generated by comprehensions. In
  2172. # order to provide a friendlier interface to users, we recast
  2173. # their name as "implicitN" and treat them as positional-only.
  2174. # See issue 19611.
  2175. if self._kind != _POSITIONAL_OR_KEYWORD:
  2176. msg = (
  2177. 'implicit arguments must be passed as '
  2178. 'positional or keyword arguments, not {}'
  2179. )
  2180. msg = msg.format(self._kind.description)
  2181. raise ValueError(msg)
  2182. self._kind = _POSITIONAL_ONLY
  2183. name = 'implicit{}'.format(name[1:])
  2184. if not name.isidentifier():
  2185. raise ValueError('{!r} is not a valid parameter name'.format(name))
  2186. self._name = name
  2187. def __reduce__(self):
  2188. return (type(self),
  2189. (self._name, self._kind),
  2190. {'_default': self._default,
  2191. '_annotation': self._annotation})
  2192. def __setstate__(self, state):
  2193. self._default = state['_default']
  2194. self._annotation = state['_annotation']
  2195. @property
  2196. def name(self):
  2197. return self._name
  2198. @property
  2199. def default(self):
  2200. return self._default
  2201. @property
  2202. def annotation(self):
  2203. return self._annotation
  2204. @property
  2205. def kind(self):
  2206. return self._kind
  2207. def replace(self, *, name=_void, kind=_void,
  2208. annotation=_void, default=_void):
  2209. """Creates a customized copy of the Parameter."""
  2210. if name is _void:
  2211. name = self._name
  2212. if kind is _void:
  2213. kind = self._kind
  2214. if annotation is _void:
  2215. annotation = self._annotation
  2216. if default is _void:
  2217. default = self._default
  2218. return type(self)(name, kind, default=default, annotation=annotation)
  2219. def __str__(self):
  2220. kind = self.kind
  2221. formatted = self._name
  2222. # Add annotation and default value
  2223. if self._annotation is not _empty:
  2224. formatted = '{}: {}'.format(formatted,
  2225. formatannotation(self._annotation))
  2226. if self._default is not _empty:
  2227. if self._annotation is not _empty:
  2228. formatted = '{} = {}'.format(formatted, repr(self._default))
  2229. else:
  2230. formatted = '{}={}'.format(formatted, repr(self._default))
  2231. if kind == _VAR_POSITIONAL:
  2232. formatted = '*' + formatted
  2233. elif kind == _VAR_KEYWORD:
  2234. formatted = '**' + formatted
  2235. return formatted
  2236. def __repr__(self):
  2237. return '<{} "{}">'.format(self.__class__.__name__, self)
  2238. def __hash__(self):
  2239. return hash((self.name, self.kind, self.annotation, self.default))
  2240. def __eq__(self, other):
  2241. if self is other:
  2242. return True
  2243. if not isinstance(other, Parameter):
  2244. return NotImplemented
  2245. return (self._name == other._name and
  2246. self._kind == other._kind and
  2247. self._default == other._default and
  2248. self._annotation == other._annotation)
  2249. class BoundArguments:
  2250. """Result of `Signature.bind` call. Holds the mapping of arguments
  2251. to the function's parameters.
  2252. Has the following public attributes:
  2253. * arguments : dict
  2254. An ordered mutable mapping of parameters' names to arguments' values.
  2255. Does not contain arguments' default values.
  2256. * signature : Signature
  2257. The Signature object that created this instance.
  2258. * args : tuple
  2259. Tuple of positional arguments values.
  2260. * kwargs : dict
  2261. Dict of keyword arguments values.
  2262. """
  2263. __slots__ = ('arguments', '_signature', '__weakref__')
  2264. def __init__(self, signature, arguments):
  2265. self.arguments = arguments
  2266. self._signature = signature
  2267. @property
  2268. def signature(self):
  2269. return self._signature
  2270. @property
  2271. def args(self):
  2272. args = []
  2273. for param_name, param in self._signature.parameters.items():
  2274. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2275. break
  2276. try:
  2277. arg = self.arguments[param_name]
  2278. except KeyError:
  2279. # We're done here. Other arguments
  2280. # will be mapped in 'BoundArguments.kwargs'
  2281. break
  2282. else:
  2283. if param.kind == _VAR_POSITIONAL:
  2284. # *args
  2285. args.extend(arg)
  2286. else:
  2287. # plain argument
  2288. args.append(arg)
  2289. return tuple(args)
  2290. @property
  2291. def kwargs(self):
  2292. kwargs = {}
  2293. kwargs_started = False
  2294. for param_name, param in self._signature.parameters.items():
  2295. if not kwargs_started:
  2296. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2297. kwargs_started = True
  2298. else:
  2299. if param_name not in self.arguments:
  2300. kwargs_started = True
  2301. continue
  2302. if not kwargs_started:
  2303. continue
  2304. try:
  2305. arg = self.arguments[param_name]
  2306. except KeyError:
  2307. pass
  2308. else:
  2309. if param.kind == _VAR_KEYWORD:
  2310. # **kwargs
  2311. kwargs.update(arg)
  2312. else:
  2313. # plain keyword argument
  2314. kwargs[param_name] = arg
  2315. return kwargs
  2316. def apply_defaults(self):
  2317. """Set default values for missing arguments.
  2318. For variable-positional arguments (*args) the default is an
  2319. empty tuple.
  2320. For variable-keyword arguments (**kwargs) the default is an
  2321. empty dict.
  2322. """
  2323. arguments = self.arguments
  2324. new_arguments = []
  2325. for name, param in self._signature.parameters.items():
  2326. try:
  2327. new_arguments.append((name, arguments[name]))
  2328. except KeyError:
  2329. if param.default is not _empty:
  2330. val = param.default
  2331. elif param.kind is _VAR_POSITIONAL:
  2332. val = ()
  2333. elif param.kind is _VAR_KEYWORD:
  2334. val = {}
  2335. else:
  2336. # This BoundArguments was likely produced by
  2337. # Signature.bind_partial().
  2338. continue
  2339. new_arguments.append((name, val))
  2340. self.arguments = dict(new_arguments)
  2341. def __eq__(self, other):
  2342. if self is other:
  2343. return True
  2344. if not isinstance(other, BoundArguments):
  2345. return NotImplemented
  2346. return (self.signature == other.signature and
  2347. self.arguments == other.arguments)
  2348. def __setstate__(self, state):
  2349. self._signature = state['_signature']
  2350. self.arguments = state['arguments']
  2351. def __getstate__(self):
  2352. return {'_signature': self._signature, 'arguments': self.arguments}
  2353. def __repr__(self):
  2354. args = []
  2355. for arg, value in self.arguments.items():
  2356. args.append('{}={!r}'.format(arg, value))
  2357. return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
  2358. class Signature:
  2359. """A Signature object represents the overall signature of a function.
  2360. It stores a Parameter object for each parameter accepted by the
  2361. function, as well as information specific to the function itself.
  2362. A Signature object has the following public attributes and methods:
  2363. * parameters : OrderedDict
  2364. An ordered mapping of parameters' names to the corresponding
  2365. Parameter objects (keyword-only arguments are in the same order
  2366. as listed in `code.co_varnames`).
  2367. * return_annotation : object
  2368. The annotation for the return type of the function if specified.
  2369. If the function has no annotation for its return type, this
  2370. attribute is set to `Signature.empty`.
  2371. * bind(*args, **kwargs) -> BoundArguments
  2372. Creates a mapping from positional and keyword arguments to
  2373. parameters.
  2374. * bind_partial(*args, **kwargs) -> BoundArguments
  2375. Creates a partial mapping from positional and keyword arguments
  2376. to parameters (simulating 'functools.partial' behavior.)
  2377. """
  2378. __slots__ = ('_return_annotation', '_parameters')
  2379. _parameter_cls = Parameter
  2380. _bound_arguments_cls = BoundArguments
  2381. empty = _empty
  2382. def __init__(self, parameters=None, *, return_annotation=_empty,
  2383. __validate_parameters__=True):
  2384. """Constructs Signature from the given list of Parameter
  2385. objects and 'return_annotation'. All arguments are optional.
  2386. """
  2387. if parameters is None:
  2388. params = OrderedDict()
  2389. else:
  2390. if __validate_parameters__:
  2391. params = OrderedDict()
  2392. top_kind = _POSITIONAL_ONLY
  2393. kind_defaults = False
  2394. for param in parameters:
  2395. kind = param.kind
  2396. name = param.name
  2397. if kind < top_kind:
  2398. msg = (
  2399. 'wrong parameter order: {} parameter before {} '
  2400. 'parameter'
  2401. )
  2402. msg = msg.format(top_kind.description,
  2403. kind.description)
  2404. raise ValueError(msg)
  2405. elif kind > top_kind:
  2406. kind_defaults = False
  2407. top_kind = kind
  2408. if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
  2409. if param.default is _empty:
  2410. if kind_defaults:
  2411. # No default for this parameter, but the
  2412. # previous parameter of the same kind had
  2413. # a default
  2414. msg = 'non-default argument follows default ' \
  2415. 'argument'
  2416. raise ValueError(msg)
  2417. else:
  2418. # There is a default for this parameter.
  2419. kind_defaults = True
  2420. if name in params:
  2421. msg = 'duplicate parameter name: {!r}'.format(name)
  2422. raise ValueError(msg)
  2423. params[name] = param
  2424. else:
  2425. params = OrderedDict((param.name, param) for param in parameters)
  2426. self._parameters = types.MappingProxyType(params)
  2427. self._return_annotation = return_annotation
  2428. @classmethod
  2429. def from_function(cls, func):
  2430. """Constructs Signature for the given python function.
  2431. Deprecated since Python 3.5, use `Signature.from_callable()`.
  2432. """
  2433. warnings.warn("inspect.Signature.from_function() is deprecated since "
  2434. "Python 3.5, use Signature.from_callable()",
  2435. DeprecationWarning, stacklevel=2)
  2436. return _signature_from_function(cls, func)
  2437. @classmethod
  2438. def from_builtin(cls, func):
  2439. """Constructs Signature for the given builtin function.
  2440. Deprecated since Python 3.5, use `Signature.from_callable()`.
  2441. """
  2442. warnings.warn("inspect.Signature.from_builtin() is deprecated since "
  2443. "Python 3.5, use Signature.from_callable()",
  2444. DeprecationWarning, stacklevel=2)
  2445. return _signature_from_builtin(cls, func)
  2446. @classmethod
  2447. def from_callable(cls, obj, *, follow_wrapped=True):
  2448. """Constructs Signature for the given callable object."""
  2449. return _signature_from_callable(obj, sigcls=cls,
  2450. follow_wrapper_chains=follow_wrapped)
  2451. @property
  2452. def parameters(self):
  2453. return self._parameters
  2454. @property
  2455. def return_annotation(self):
  2456. return self._return_annotation
  2457. def replace(self, *, parameters=_void, return_annotation=_void):
  2458. """Creates a customized copy of the Signature.
  2459. Pass 'parameters' and/or 'return_annotation' arguments
  2460. to override them in the new copy.
  2461. """
  2462. if parameters is _void:
  2463. parameters = self.parameters.values()
  2464. if return_annotation is _void:
  2465. return_annotation = self._return_annotation
  2466. return type(self)(parameters,
  2467. return_annotation=return_annotation)
  2468. def _hash_basis(self):
  2469. params = tuple(param for param in self.parameters.values()
  2470. if param.kind != _KEYWORD_ONLY)
  2471. kwo_params = {param.name: param for param in self.parameters.values()
  2472. if param.kind == _KEYWORD_ONLY}
  2473. return params, kwo_params, self.return_annotation
  2474. def __hash__(self):
  2475. params, kwo_params, return_annotation = self._hash_basis()
  2476. kwo_params = frozenset(kwo_params.values())
  2477. return hash((params, kwo_params, return_annotation))
  2478. def __eq__(self, other):
  2479. if self is other:
  2480. return True
  2481. if not isinstance(other, Signature):
  2482. return NotImplemented
  2483. return self._hash_basis() == other._hash_basis()
  2484. def _bind(self, args, kwargs, *, partial=False):
  2485. """Private method. Don't use directly."""
  2486. arguments = {}
  2487. parameters = iter(self.parameters.values())
  2488. parameters_ex = ()
  2489. arg_vals = iter(args)
  2490. while True:
  2491. # Let's iterate through the positional arguments and corresponding
  2492. # parameters
  2493. try:
  2494. arg_val = next(arg_vals)
  2495. except StopIteration:
  2496. # No more positional arguments
  2497. try:
  2498. param = next(parameters)
  2499. except StopIteration:
  2500. # No more parameters. That's it. Just need to check that
  2501. # we have no `kwargs` after this while loop
  2502. break
  2503. else:
  2504. if param.kind == _VAR_POSITIONAL:
  2505. # That's OK, just empty *args. Let's start parsing
  2506. # kwargs
  2507. break
  2508. elif param.name in kwargs:
  2509. if param.kind == _POSITIONAL_ONLY:
  2510. msg = '{arg!r} parameter is positional only, ' \
  2511. 'but was passed as a keyword'
  2512. msg = msg.format(arg=param.name)
  2513. raise TypeError(msg) from None
  2514. parameters_ex = (param,)
  2515. break
  2516. elif (param.kind == _VAR_KEYWORD or
  2517. param.default is not _empty):
  2518. # That's fine too - we have a default value for this
  2519. # parameter. So, lets start parsing `kwargs`, starting
  2520. # with the current parameter
  2521. parameters_ex = (param,)
  2522. break
  2523. else:
  2524. # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
  2525. # not in `kwargs`
  2526. if partial:
  2527. parameters_ex = (param,)
  2528. break
  2529. else:
  2530. msg = 'missing a required argument: {arg!r}'
  2531. msg = msg.format(arg=param.name)
  2532. raise TypeError(msg) from None
  2533. else:
  2534. # We have a positional argument to process
  2535. try:
  2536. param = next(parameters)
  2537. except StopIteration:
  2538. raise TypeError('too many positional arguments') from None
  2539. else:
  2540. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2541. # Looks like we have no parameter for this positional
  2542. # argument
  2543. raise TypeError(
  2544. 'too many positional arguments') from None
  2545. if param.kind == _VAR_POSITIONAL:
  2546. # We have an '*args'-like argument, let's fill it with
  2547. # all positional arguments we have left and move on to
  2548. # the next phase
  2549. values = [arg_val]
  2550. values.extend(arg_vals)
  2551. arguments[param.name] = tuple(values)
  2552. break
  2553. if param.name in kwargs and param.kind != _POSITIONAL_ONLY:
  2554. raise TypeError(
  2555. 'multiple values for argument {arg!r}'.format(
  2556. arg=param.name)) from None
  2557. arguments[param.name] = arg_val
  2558. # Now, we iterate through the remaining parameters to process
  2559. # keyword arguments
  2560. kwargs_param = None
  2561. for param in itertools.chain(parameters_ex, parameters):
  2562. if param.kind == _VAR_KEYWORD:
  2563. # Memorize that we have a '**kwargs'-like parameter
  2564. kwargs_param = param
  2565. continue
  2566. if param.kind == _VAR_POSITIONAL:
  2567. # Named arguments don't refer to '*args'-like parameters.
  2568. # We only arrive here if the positional arguments ended
  2569. # before reaching the last parameter before *args.
  2570. continue
  2571. param_name = param.name
  2572. try:
  2573. arg_val = kwargs.pop(param_name)
  2574. except KeyError:
  2575. # We have no value for this parameter. It's fine though,
  2576. # if it has a default value, or it is an '*args'-like
  2577. # parameter, left alone by the processing of positional
  2578. # arguments.
  2579. if (not partial and param.kind != _VAR_POSITIONAL and
  2580. param.default is _empty):
  2581. raise TypeError('missing a required argument: {arg!r}'. \
  2582. format(arg=param_name)) from None
  2583. else:
  2584. if param.kind == _POSITIONAL_ONLY:
  2585. # This should never happen in case of a properly built
  2586. # Signature object (but let's have this check here
  2587. # to ensure correct behaviour just in case)
  2588. raise TypeError('{arg!r} parameter is positional only, '
  2589. 'but was passed as a keyword'. \
  2590. format(arg=param.name))
  2591. arguments[param_name] = arg_val
  2592. if kwargs:
  2593. if kwargs_param is not None:
  2594. # Process our '**kwargs'-like parameter
  2595. arguments[kwargs_param.name] = kwargs
  2596. else:
  2597. raise TypeError(
  2598. 'got an unexpected keyword argument {arg!r}'.format(
  2599. arg=next(iter(kwargs))))
  2600. return self._bound_arguments_cls(self, arguments)
  2601. def bind(self, /, *args, **kwargs):
  2602. """Get a BoundArguments object, that maps the passed `args`
  2603. and `kwargs` to the function's signature. Raises `TypeError`
  2604. if the passed arguments can not be bound.
  2605. """
  2606. return self._bind(args, kwargs)
  2607. def bind_partial(self, /, *args, **kwargs):
  2608. """Get a BoundArguments object, that partially maps the
  2609. passed `args` and `kwargs` to the function's signature.
  2610. Raises `TypeError` if the passed arguments can not be bound.
  2611. """
  2612. return self._bind(args, kwargs, partial=True)
  2613. def __reduce__(self):
  2614. return (type(self),
  2615. (tuple(self._parameters.values()),),
  2616. {'_return_annotation': self._return_annotation})
  2617. def __setstate__(self, state):
  2618. self._return_annotation = state['_return_annotation']
  2619. def __repr__(self):
  2620. return '<{} {}>'.format(self.__class__.__name__, self)
  2621. def __str__(self):
  2622. result = []
  2623. render_pos_only_separator = False
  2624. render_kw_only_separator = True
  2625. for param in self.parameters.values():
  2626. formatted = str(param)
  2627. kind = param.kind
  2628. if kind == _POSITIONAL_ONLY:
  2629. render_pos_only_separator = True
  2630. elif render_pos_only_separator:
  2631. # It's not a positional-only parameter, and the flag
  2632. # is set to 'True' (there were pos-only params before.)
  2633. result.append('/')
  2634. render_pos_only_separator = False
  2635. if kind == _VAR_POSITIONAL:
  2636. # OK, we have an '*args'-like parameter, so we won't need
  2637. # a '*' to separate keyword-only arguments
  2638. render_kw_only_separator = False
  2639. elif kind == _KEYWORD_ONLY and render_kw_only_separator:
  2640. # We have a keyword-only parameter to render and we haven't
  2641. # rendered an '*args'-like parameter before, so add a '*'
  2642. # separator to the parameters list ("foo(arg1, *, arg2)" case)
  2643. result.append('*')
  2644. # This condition should be only triggered once, so
  2645. # reset the flag
  2646. render_kw_only_separator = False
  2647. result.append(formatted)
  2648. if render_pos_only_separator:
  2649. # There were only positional-only parameters, hence the
  2650. # flag was not reset to 'False'
  2651. result.append('/')
  2652. rendered = '({})'.format(', '.join(result))
  2653. if self.return_annotation is not _empty:
  2654. anno = formatannotation(self.return_annotation)
  2655. rendered += ' -> {}'.format(anno)
  2656. return rendered
  2657. def signature(obj, *, follow_wrapped=True):
  2658. """Get a signature object for the passed callable."""
  2659. return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  2660. def _main():
  2661. """ Logic for inspecting an object given at command line """
  2662. import argparse
  2663. import importlib
  2664. parser = argparse.ArgumentParser()
  2665. parser.add_argument(
  2666. 'object',
  2667. help="The object to be analysed. "
  2668. "It supports the 'module:qualname' syntax")
  2669. parser.add_argument(
  2670. '-d', '--details', action='store_true',
  2671. help='Display info about the module rather than its source code')
  2672. args = parser.parse_args()
  2673. target = args.object
  2674. mod_name, has_attrs, attrs = target.partition(":")
  2675. try:
  2676. obj = module = importlib.import_module(mod_name)
  2677. except Exception as exc:
  2678. msg = "Failed to import {} ({}: {})".format(mod_name,
  2679. type(exc).__name__,
  2680. exc)
  2681. print(msg, file=sys.stderr)
  2682. sys.exit(2)
  2683. if has_attrs:
  2684. parts = attrs.split(".")
  2685. obj = module
  2686. for part in parts:
  2687. obj = getattr(obj, part)
  2688. if module.__name__ in sys.builtin_module_names:
  2689. print("Can't get info for builtin modules.", file=sys.stderr)
  2690. sys.exit(1)
  2691. if args.details:
  2692. print('Target: {}'.format(target))
  2693. print('Origin: {}'.format(getsourcefile(module)))
  2694. print('Cached: {}'.format(module.__cached__))
  2695. if obj is module:
  2696. print('Loader: {}'.format(repr(module.__loader__)))
  2697. if hasattr(module, '__path__'):
  2698. print('Submodule search path: {}'.format(module.__path__))
  2699. else:
  2700. try:
  2701. __, lineno = findsource(obj)
  2702. except Exception:
  2703. pass
  2704. else:
  2705. print('Line: {}'.format(lineno))
  2706. print('\n')
  2707. else:
  2708. print(getsource(obj))
  2709. if __name__ == "__main__":
  2710. _main()