inspect.py 116 KB

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