traitlets.py 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312
  1. """
  2. A lightweight Traits like module.
  3. This is designed to provide a lightweight, simple, pure Python version of
  4. many of the capabilities of enthought.traits. This includes:
  5. * Validation
  6. * Type specification with defaults
  7. * Static and dynamic notification
  8. * Basic predefined types
  9. * An API that is similar to enthought.traits
  10. We don't support:
  11. * Delegation
  12. * Automatic GUI generation
  13. * A full set of trait types. Most importantly, we don't provide container
  14. traits (list, dict, tuple) that can trigger notifications if their
  15. contents change.
  16. * API compatibility with enthought.traits
  17. There are also some important difference in our design:
  18. * enthought.traits does not validate default values. We do.
  19. We choose to create this module because we need these capabilities, but
  20. we need them to be pure Python so they work in all Python implementations,
  21. including Jython and IronPython.
  22. Inheritance diagram:
  23. .. inheritance-diagram:: traitlets.traitlets
  24. :parts: 3
  25. """
  26. # Copyright (c) IPython Development Team.
  27. # Distributed under the terms of the Modified BSD License.
  28. #
  29. # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
  30. # also under the terms of the Modified BSD License.
  31. from __future__ import annotations
  32. import contextlib
  33. import enum
  34. import inspect
  35. import os
  36. import re
  37. import sys
  38. import types
  39. import typing as t
  40. from ast import literal_eval
  41. from .utils.bunch import Bunch
  42. from .utils.descriptions import add_article, class_of, describe, repr_type
  43. from .utils.getargspec import getargspec
  44. from .utils.importstring import import_item
  45. from .utils.sentinel import Sentinel
  46. from .utils.warnings import deprecated_method, should_warn, warn
  47. SequenceTypes = (list, tuple, set, frozenset)
  48. # backward compatibility, use to differ between Python 2 and 3.
  49. ClassTypes = (type,)
  50. if t.TYPE_CHECKING:
  51. from typing_extensions import TypeVar
  52. else:
  53. from typing import TypeVar
  54. # exports:
  55. __all__ = [
  56. "All",
  57. "Any",
  58. "BaseDescriptor",
  59. "Bool",
  60. "Bytes",
  61. "CBool",
  62. "CBytes",
  63. "CComplex",
  64. "CFloat",
  65. "CInt",
  66. "CLong",
  67. "CRegExp",
  68. "CUnicode",
  69. "Callable",
  70. "CaselessStrEnum",
  71. "ClassBasedTraitType",
  72. "Complex",
  73. "Container",
  74. "DefaultHandler",
  75. "Dict",
  76. "DottedObjectName",
  77. "Enum",
  78. "EventHandler",
  79. "Float",
  80. "ForwardDeclaredInstance",
  81. "ForwardDeclaredMixin",
  82. "ForwardDeclaredType",
  83. "FuzzyEnum",
  84. "HasDescriptors",
  85. "HasTraits",
  86. "Instance",
  87. "Int",
  88. "Integer",
  89. "List",
  90. "Long",
  91. "MetaHasDescriptors",
  92. "MetaHasTraits",
  93. "ObjectName",
  94. "ObserveHandler",
  95. "Set",
  96. "TCPAddress",
  97. "This",
  98. "TraitError",
  99. "TraitType",
  100. "Tuple",
  101. "Type",
  102. "Unicode",
  103. "Undefined",
  104. "Union",
  105. "UseEnum",
  106. "ValidateHandler",
  107. "default",
  108. "directional_link",
  109. "dlink",
  110. "link",
  111. "observe",
  112. "observe_compat",
  113. "parse_notifier_name",
  114. "validate",
  115. ]
  116. # any TraitType subclass (that doesn't start with _) will be added automatically
  117. # -----------------------------------------------------------------------------
  118. # Basic classes
  119. # -----------------------------------------------------------------------------
  120. Undefined = Sentinel(
  121. "Undefined",
  122. "traitlets",
  123. """
  124. Used in Traitlets to specify that no defaults are set in kwargs
  125. """,
  126. )
  127. All = Sentinel(
  128. "All",
  129. "traitlets",
  130. """
  131. Used in Traitlets to listen to all types of notification or to notifications
  132. from all trait attributes.
  133. """,
  134. )
  135. # Deprecated alias
  136. NoDefaultSpecified = Undefined
  137. class TraitError(Exception):
  138. pass
  139. # -----------------------------------------------------------------------------
  140. # Utilities
  141. # -----------------------------------------------------------------------------
  142. def isidentifier(s: t.Any) -> bool:
  143. return t.cast(bool, s.isidentifier())
  144. def _safe_literal_eval(s: str) -> t.Any:
  145. """Safely evaluate an expression
  146. Returns original string if eval fails.
  147. Use only where types are ambiguous.
  148. """
  149. try:
  150. return literal_eval(s)
  151. except (NameError, SyntaxError, ValueError):
  152. return s
  153. def is_trait(t: t.Any) -> bool:
  154. """Returns whether the given value is an instance or subclass of TraitType."""
  155. return isinstance(t, TraitType) or (isinstance(t, type) and issubclass(t, TraitType))
  156. def parse_notifier_name(names: Sentinel | str | t.Iterable[Sentinel | str]) -> t.Iterable[t.Any]:
  157. """Convert the name argument to a list of names.
  158. Examples
  159. --------
  160. >>> parse_notifier_name([])
  161. [traitlets.All]
  162. >>> parse_notifier_name("a")
  163. ['a']
  164. >>> parse_notifier_name(["a", "b"])
  165. ['a', 'b']
  166. >>> parse_notifier_name(All)
  167. [traitlets.All]
  168. """
  169. if names is All or isinstance(names, str):
  170. return [names]
  171. elif isinstance(names, Sentinel):
  172. raise TypeError("`names` must be either `All`, a str, or a list of strs.")
  173. else:
  174. if not names or All in names:
  175. return [All]
  176. for n in names:
  177. if not isinstance(n, str):
  178. raise TypeError(f"names must be strings, not {type(n).__name__}({n!r})")
  179. return names
  180. class _SimpleTest:
  181. def __init__(self, value: t.Any) -> None:
  182. self.value = value
  183. def __call__(self, test: t.Any) -> bool:
  184. return bool(test == self.value)
  185. def __repr__(self) -> str:
  186. return "<SimpleTest(%r)" % self.value
  187. def __str__(self) -> str:
  188. return self.__repr__()
  189. def getmembers(object: t.Any, predicate: t.Any = None) -> list[tuple[str, t.Any]]:
  190. """A safe version of inspect.getmembers that handles missing attributes.
  191. This is useful when there are descriptor based attributes that for
  192. some reason raise AttributeError even though they exist. This happens
  193. in zope.interface with the __provides__ attribute.
  194. """
  195. results = []
  196. for key in dir(object):
  197. try:
  198. value = getattr(object, key)
  199. except AttributeError:
  200. pass
  201. else:
  202. if not predicate or predicate(value):
  203. results.append((key, value))
  204. results.sort()
  205. return results
  206. def _validate_link(*tuples: t.Any) -> None:
  207. """Validate arguments for traitlet link functions"""
  208. for tup in tuples:
  209. if not len(tup) == 2:
  210. raise TypeError(
  211. "Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t
  212. )
  213. obj, trait_name = tup
  214. if not isinstance(obj, HasTraits):
  215. raise TypeError("Each object must be HasTraits, not %r" % type(obj))
  216. if trait_name not in obj.traits():
  217. raise TypeError(f"{obj!r} has no trait {trait_name!r}")
  218. class link:
  219. """Link traits from different objects together so they remain in sync.
  220. Parameters
  221. ----------
  222. source : (object / attribute name) pair
  223. target : (object / attribute name) pair
  224. transform: iterable with two callables (optional)
  225. Data transformation between source and target and target and source.
  226. Examples
  227. --------
  228. >>> class X(HasTraits):
  229. ... value = Int()
  230. >>> src = X(value=1)
  231. >>> tgt = X(value=42)
  232. >>> c = link((src, "value"), (tgt, "value"))
  233. Setting source updates target objects:
  234. >>> src.value = 5
  235. >>> tgt.value
  236. 5
  237. """
  238. updating = False
  239. def __init__(self, source: t.Any, target: t.Any, transform: t.Any = None) -> None:
  240. _validate_link(source, target)
  241. self.source, self.target = source, target
  242. self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2
  243. self.link()
  244. def link(self) -> None:
  245. try:
  246. setattr(
  247. self.target[0],
  248. self.target[1],
  249. self._transform(getattr(self.source[0], self.source[1])),
  250. )
  251. finally:
  252. self.source[0].observe(self._update_target, names=self.source[1])
  253. self.target[0].observe(self._update_source, names=self.target[1])
  254. @contextlib.contextmanager
  255. def _busy_updating(self) -> t.Any:
  256. self.updating = True
  257. try:
  258. yield
  259. finally:
  260. self.updating = False
  261. def _update_target(self, change: t.Any) -> None:
  262. if self.updating:
  263. return
  264. with self._busy_updating():
  265. setattr(self.target[0], self.target[1], self._transform(change.new))
  266. if getattr(self.source[0], self.source[1]) != change.new:
  267. raise TraitError(
  268. f"Broken link {self}: the source value changed while updating " "the target."
  269. )
  270. def _update_source(self, change: t.Any) -> None:
  271. if self.updating:
  272. return
  273. with self._busy_updating():
  274. setattr(self.source[0], self.source[1], self._transform_inv(change.new))
  275. if getattr(self.target[0], self.target[1]) != change.new:
  276. raise TraitError(
  277. f"Broken link {self}: the target value changed while updating " "the source."
  278. )
  279. def unlink(self) -> None:
  280. self.source[0].unobserve(self._update_target, names=self.source[1])
  281. self.target[0].unobserve(self._update_source, names=self.target[1])
  282. class directional_link:
  283. """Link the trait of a source object with traits of target objects.
  284. Parameters
  285. ----------
  286. source : (object, attribute name) pair
  287. target : (object, attribute name) pair
  288. transform: callable (optional)
  289. Data transformation between source and target.
  290. Examples
  291. --------
  292. >>> class X(HasTraits):
  293. ... value = Int()
  294. >>> src = X(value=1)
  295. >>> tgt = X(value=42)
  296. >>> c = directional_link((src, "value"), (tgt, "value"))
  297. Setting source updates target objects:
  298. >>> src.value = 5
  299. >>> tgt.value
  300. 5
  301. Setting target does not update source object:
  302. >>> tgt.value = 6
  303. >>> src.value
  304. 5
  305. """
  306. updating = False
  307. def __init__(self, source: t.Any, target: t.Any, transform: t.Any = None) -> None:
  308. self._transform = transform if transform else lambda x: x
  309. _validate_link(source, target)
  310. self.source, self.target = source, target
  311. self.link()
  312. def link(self) -> None:
  313. try:
  314. setattr(
  315. self.target[0],
  316. self.target[1],
  317. self._transform(getattr(self.source[0], self.source[1])),
  318. )
  319. finally:
  320. self.source[0].observe(self._update, names=self.source[1])
  321. @contextlib.contextmanager
  322. def _busy_updating(self) -> t.Any:
  323. self.updating = True
  324. try:
  325. yield
  326. finally:
  327. self.updating = False
  328. def _update(self, change: t.Any) -> None:
  329. if self.updating:
  330. return
  331. with self._busy_updating():
  332. setattr(self.target[0], self.target[1], self._transform(change.new))
  333. def unlink(self) -> None:
  334. self.source[0].unobserve(self._update, names=self.source[1])
  335. dlink = directional_link
  336. # -----------------------------------------------------------------------------
  337. # Base Descriptor Class
  338. # -----------------------------------------------------------------------------
  339. class BaseDescriptor:
  340. """Base descriptor class
  341. Notes
  342. -----
  343. This implements Python's descriptor protocol.
  344. This class is the base class for all such descriptors. The
  345. only magic we use is a custom metaclass for the main :class:`HasTraits`
  346. class that does the following:
  347. 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
  348. instance in the class dict to the name of the attribute.
  349. 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
  350. instance in the class dict to the *class* that declared the trait.
  351. This is used by the :class:`This` trait to allow subclasses to
  352. accept superclasses for :class:`This` values.
  353. """
  354. name: str | None = None
  355. this_class: type[HasTraits] | None = None
  356. def class_init(self, cls: type[HasTraits], name: str | None) -> None:
  357. """Part of the initialization which may depend on the underlying
  358. HasDescriptors class.
  359. It is typically overloaded for specific types.
  360. This method is called by :meth:`MetaHasDescriptors.__init__`
  361. passing the class (`cls`) and `name` under which the descriptor
  362. has been assigned.
  363. """
  364. self.this_class = cls
  365. self.name = name
  366. def subclass_init(self, cls: type[HasTraits]) -> None:
  367. # Instead of HasDescriptors.setup_instance calling
  368. # every instance_init, we opt in by default.
  369. # This gives descriptors a change to opt out for
  370. # performance reasons.
  371. # Because most traits do not need instance_init,
  372. # and it will otherwise be called for every HasTrait instance
  373. # being created, this otherwise gives a significant performance
  374. # pentalty. Most TypeTraits in traitlets opt out.
  375. cls._instance_inits.append(self.instance_init)
  376. def instance_init(self, obj: t.Any) -> None:
  377. """Part of the initialization which may depend on the underlying
  378. HasDescriptors instance.
  379. It is typically overloaded for specific types.
  380. This method is called by :meth:`HasTraits.__new__` and in the
  381. :meth:`BaseDescriptor.instance_init` method of descriptors holding
  382. other descriptors.
  383. """
  384. G = TypeVar("G")
  385. S = TypeVar("S")
  386. T = TypeVar("T")
  387. # Self from typing extension doesn't work well with mypy https://github.com/python/mypy/pull/14041
  388. # see https://peps.python.org/pep-0673/#use-in-generic-classes
  389. # Self = t.TypeVar("Self", bound="TraitType[Any, Any]")
  390. if t.TYPE_CHECKING:
  391. from typing_extensions import Literal, Self
  392. K = TypeVar("K", default=str)
  393. V = TypeVar("V", default=t.Any)
  394. # We use a type for the getter (G) and setter (G) because we allow
  395. # for traits to cast (for instance CInt will use G=int, S=t.Any)
  396. class TraitType(BaseDescriptor, t.Generic[G, S]):
  397. """A base class for all trait types."""
  398. metadata: dict[str, t.Any] = {}
  399. allow_none: bool = False
  400. read_only: bool = False
  401. info_text: str = "any value"
  402. default_value: t.Any = Undefined
  403. def __init__(
  404. self: TraitType[G, S],
  405. default_value: t.Any = Undefined,
  406. allow_none: bool = False,
  407. read_only: bool | None = None,
  408. help: str | None = None,
  409. config: t.Any = None,
  410. **kwargs: t.Any,
  411. ) -> None:
  412. """Declare a traitlet.
  413. If *allow_none* is True, None is a valid value in addition to any
  414. values that are normally valid. The default is up to the subclass.
  415. For most trait types, the default value for ``allow_none`` is False.
  416. If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
  417. If *help* is a string, it documents the attribute's purpose.
  418. Extra metadata can be associated with the traitlet using the .tag() convenience method
  419. or by using the traitlet instance's .metadata dictionary.
  420. """
  421. if default_value is not Undefined:
  422. self.default_value = default_value
  423. if allow_none:
  424. self.allow_none = allow_none
  425. if read_only is not None:
  426. self.read_only = read_only
  427. self.help = help if help is not None else ""
  428. if self.help:
  429. # define __doc__ so that inspectors like autodoc find traits
  430. self.__doc__ = self.help
  431. if len(kwargs) > 0:
  432. stacklevel = 1
  433. f = inspect.currentframe()
  434. # count supers to determine stacklevel for warning
  435. assert f is not None
  436. while f.f_code.co_name == "__init__":
  437. stacklevel += 1
  438. f = f.f_back
  439. assert f is not None
  440. mod = f.f_globals.get("__name__") or ""
  441. pkg = mod.split(".", 1)[0]
  442. key = ("metadata-tag", pkg, *sorted(kwargs))
  443. if should_warn(key):
  444. warn(
  445. f"metadata {kwargs} was set from the constructor. "
  446. "With traitlets 4.1, metadata should be set using the .tag() method, "
  447. "e.g., Int().tag(key1='value1', key2='value2')",
  448. DeprecationWarning,
  449. stacklevel=stacklevel,
  450. )
  451. if len(self.metadata) > 0:
  452. self.metadata = self.metadata.copy()
  453. self.metadata.update(kwargs)
  454. else:
  455. self.metadata = kwargs
  456. else:
  457. self.metadata = self.metadata.copy()
  458. if config is not None:
  459. self.metadata["config"] = config
  460. # We add help to the metadata during a deprecation period so that
  461. # code that looks for the help string there can find it.
  462. if help is not None:
  463. self.metadata["help"] = help
  464. def from_string(self, s: str) -> G | None:
  465. """Get a value from a config string
  466. such as an environment variable or CLI arguments.
  467. Traits can override this method to define their own
  468. parsing of config strings.
  469. .. seealso:: item_from_string
  470. .. versionadded:: 5.0
  471. """
  472. if self.allow_none and s == "None":
  473. return None
  474. return s # type:ignore[return-value]
  475. def default(self, obj: t.Any = None) -> G | None:
  476. """The default generator for this trait
  477. Notes
  478. -----
  479. This method is registered to HasTraits classes during ``class_init``
  480. in the same way that dynamic defaults defined by ``@default`` are.
  481. """
  482. if self.default_value is not Undefined:
  483. return t.cast(G, self.default_value)
  484. elif hasattr(self, "make_dynamic_default"):
  485. return t.cast(G, self.make_dynamic_default())
  486. else:
  487. # Undefined will raise in TraitType.get
  488. return t.cast(G, self.default_value)
  489. def get_default_value(self) -> G | None:
  490. """DEPRECATED: Retrieve the static default value for this trait.
  491. Use self.default_value instead
  492. """
  493. warn(
  494. "get_default_value is deprecated in traitlets 4.0: use the .default_value attribute",
  495. DeprecationWarning,
  496. stacklevel=2,
  497. )
  498. return t.cast(G, self.default_value)
  499. def init_default_value(self, obj: t.Any) -> G | None:
  500. """DEPRECATED: Set the static default value for the trait type."""
  501. warn(
  502. "init_default_value is deprecated in traitlets 4.0, and may be removed in the future",
  503. DeprecationWarning,
  504. stacklevel=2,
  505. )
  506. value = self._validate(obj, self.default_value)
  507. obj._trait_values[self.name] = value
  508. return value
  509. def get(self, obj: HasTraits, cls: type[t.Any] | None = None) -> G | None:
  510. assert self.name is not None
  511. try:
  512. value = obj._trait_values[self.name]
  513. except KeyError:
  514. # Check for a dynamic initializer.
  515. default = obj.trait_defaults(self.name)
  516. if default is Undefined:
  517. warn(
  518. "Explicit using of Undefined as the default value "
  519. "is deprecated in traitlets 5.0, and may cause "
  520. "exceptions in the future.",
  521. DeprecationWarning,
  522. stacklevel=2,
  523. )
  524. # Using a context manager has a large runtime overhead, so we
  525. # write out the obj.cross_validation_lock call here.
  526. _cross_validation_lock = obj._cross_validation_lock
  527. try:
  528. obj._cross_validation_lock = True
  529. value = self._validate(obj, default)
  530. finally:
  531. obj._cross_validation_lock = _cross_validation_lock
  532. obj._trait_values[self.name] = value
  533. obj._notify_observers(
  534. Bunch(
  535. name=self.name,
  536. value=value,
  537. owner=obj,
  538. type="default",
  539. )
  540. )
  541. return t.cast(G, value)
  542. except Exception as e:
  543. # This should never be reached.
  544. raise TraitError("Unexpected error in TraitType: default value not set properly") from e
  545. else:
  546. return t.cast(G, value)
  547. @t.overload
  548. def __get__(self, obj: None, cls: type[t.Any]) -> Self:
  549. ...
  550. @t.overload
  551. def __get__(self, obj: t.Any, cls: type[t.Any]) -> G:
  552. ...
  553. def __get__(self, obj: HasTraits | None, cls: type[t.Any]) -> Self | G:
  554. """Get the value of the trait by self.name for the instance.
  555. Default values are instantiated when :meth:`HasTraits.__new__`
  556. is called. Thus by the time this method gets called either the
  557. default value or a user defined value (they called :meth:`__set__`)
  558. is in the :class:`HasTraits` instance.
  559. """
  560. if obj is None:
  561. return self
  562. else:
  563. return t.cast(G, self.get(obj, cls)) # the G should encode the Optional
  564. def set(self, obj: HasTraits, value: S) -> None:
  565. new_value = self._validate(obj, value)
  566. assert self.name is not None
  567. try:
  568. old_value = obj._trait_values[self.name]
  569. except KeyError:
  570. old_value = self.default_value
  571. obj._trait_values[self.name] = new_value
  572. try:
  573. silent = bool(old_value == new_value)
  574. except Exception:
  575. # if there is an error in comparing, default to notify
  576. silent = False
  577. if silent is not True:
  578. # we explicitly compare silent to True just in case the equality
  579. # comparison above returns something other than True/False
  580. obj._notify_trait(self.name, old_value, new_value)
  581. def __set__(self, obj: HasTraits, value: S) -> None:
  582. """Set the value of the trait by self.name for the instance.
  583. Values pass through a validation stage where errors are raised when
  584. impropper types, or types that cannot be coerced, are encountered.
  585. """
  586. if self.read_only:
  587. raise TraitError('The "%s" trait is read-only.' % self.name)
  588. self.set(obj, value)
  589. def _validate(self, obj: t.Any, value: t.Any) -> G | None:
  590. if value is None and self.allow_none:
  591. return value
  592. if hasattr(self, "validate"):
  593. value = self.validate(obj, value)
  594. if obj._cross_validation_lock is False:
  595. value = self._cross_validate(obj, value)
  596. return t.cast(G, value)
  597. def _cross_validate(self, obj: t.Any, value: t.Any) -> G | None:
  598. if self.name in obj._trait_validators:
  599. proposal = Bunch({"trait": self, "value": value, "owner": obj})
  600. value = obj._trait_validators[self.name](obj, proposal)
  601. elif hasattr(obj, "_%s_validate" % self.name):
  602. meth_name = "_%s_validate" % self.name
  603. cross_validate = getattr(obj, meth_name)
  604. deprecated_method(
  605. cross_validate,
  606. obj.__class__,
  607. meth_name,
  608. "use @validate decorator instead.",
  609. )
  610. value = cross_validate(value, self)
  611. return t.cast(G, value)
  612. def __or__(self, other: TraitType[t.Any, t.Any]) -> Union:
  613. if isinstance(other, Union):
  614. return Union([self, *other.trait_types])
  615. else:
  616. return Union([self, other])
  617. def info(self) -> str:
  618. return self.info_text
  619. def error(
  620. self,
  621. obj: HasTraits | None,
  622. value: t.Any,
  623. error: Exception | None = None,
  624. info: str | None = None,
  625. ) -> t.NoReturn:
  626. """Raise a TraitError
  627. Parameters
  628. ----------
  629. obj : HasTraits or None
  630. The instance which owns the trait. If not
  631. object is given, then an object agnostic
  632. error will be raised.
  633. value : any
  634. The value that caused the error.
  635. error : Exception (default: None)
  636. An error that was raised by a child trait.
  637. The arguments of this exception should be
  638. of the form ``(value, info, *traits)``.
  639. Where the ``value`` and ``info`` are the
  640. problem value, and string describing the
  641. expected value. The ``traits`` are a series
  642. of :class:`TraitType` instances that are
  643. "children" of this one (the first being
  644. the deepest).
  645. info : str (default: None)
  646. A description of the expected value. By
  647. default this is inferred from this trait's
  648. ``info`` method.
  649. """
  650. if error is not None:
  651. # handle nested error
  652. error.args += (self,)
  653. if self.name is not None:
  654. # this is the root trait that must format the final message
  655. chain = " of ".join(describe("a", t) for t in error.args[2:])
  656. if obj is not None:
  657. error.args = (
  658. "The '{}' trait of {} instance contains {} which "
  659. "expected {}, not {}.".format(
  660. self.name,
  661. describe("an", obj),
  662. chain,
  663. error.args[1],
  664. describe("the", error.args[0]),
  665. ),
  666. )
  667. else:
  668. error.args = (
  669. "The '{}' trait contains {} which " "expected {}, not {}.".format(
  670. self.name,
  671. chain,
  672. error.args[1],
  673. describe("the", error.args[0]),
  674. ),
  675. )
  676. raise error
  677. # this trait caused an error
  678. if self.name is None:
  679. # this is not the root trait
  680. raise TraitError(value, info or self.info(), self)
  681. # this is the root trait
  682. if obj is not None:
  683. e = "The '{}' trait of {} instance expected {}, not {}.".format(
  684. self.name,
  685. class_of(obj),
  686. info or self.info(),
  687. describe("the", value),
  688. )
  689. else:
  690. e = "The '{}' trait expected {}, not {}.".format(
  691. self.name,
  692. info or self.info(),
  693. describe("the", value),
  694. )
  695. raise TraitError(e)
  696. def get_metadata(self, key: str, default: t.Any = None) -> t.Any:
  697. """DEPRECATED: Get a metadata value.
  698. Use .metadata[key] or .metadata.get(key, default) instead.
  699. """
  700. if key == "help":
  701. msg = "use the instance .help string directly, like x.help"
  702. else:
  703. msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
  704. warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
  705. return self.metadata.get(key, default)
  706. def set_metadata(self, key: str, value: t.Any) -> None:
  707. """DEPRECATED: Set a metadata key/value.
  708. Use .metadata[key] = value instead.
  709. """
  710. if key == "help":
  711. msg = "use the instance .help string directly, like x.help = value"
  712. else:
  713. msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
  714. warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
  715. self.metadata[key] = value
  716. def tag(self, **metadata: t.Any) -> Self:
  717. """Sets metadata and returns self.
  718. This allows convenient metadata tagging when initializing the trait, such as:
  719. Examples
  720. --------
  721. >>> Int(0).tag(config=True, sync=True)
  722. <traitlets.traitlets.Int object at ...>
  723. """
  724. maybe_constructor_keywords = set(metadata.keys()).intersection(
  725. {"help", "allow_none", "read_only", "default_value"}
  726. )
  727. if maybe_constructor_keywords:
  728. warn(
  729. "The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s "
  730. % maybe_constructor_keywords,
  731. UserWarning,
  732. stacklevel=2,
  733. )
  734. self.metadata.update(metadata)
  735. return self
  736. def default_value_repr(self) -> str:
  737. return repr(self.default_value)
  738. # -----------------------------------------------------------------------------
  739. # The HasTraits implementation
  740. # -----------------------------------------------------------------------------
  741. class _CallbackWrapper:
  742. """An object adapting a on_trait_change callback into an observe callback.
  743. The comparison operator __eq__ is implemented to enable removal of wrapped
  744. callbacks.
  745. """
  746. def __init__(self, cb: t.Any) -> None:
  747. self.cb = cb
  748. # Bound methods have an additional 'self' argument.
  749. offset = -1 if isinstance(self.cb, types.MethodType) else 0
  750. self.nargs = len(getargspec(cb)[0]) + offset
  751. if self.nargs > 4:
  752. raise TraitError("a trait changed callback must have 0-4 arguments.")
  753. def __eq__(self, other: object) -> bool:
  754. # The wrapper is equal to the wrapped element
  755. if isinstance(other, _CallbackWrapper):
  756. return bool(self.cb == other.cb)
  757. else:
  758. return bool(self.cb == other)
  759. def __call__(self, change: Bunch) -> None:
  760. # The wrapper is callable
  761. if self.nargs == 0:
  762. self.cb()
  763. elif self.nargs == 1:
  764. self.cb(change.name)
  765. elif self.nargs == 2:
  766. self.cb(change.name, change.new)
  767. elif self.nargs == 3:
  768. self.cb(change.name, change.old, change.new)
  769. elif self.nargs == 4:
  770. self.cb(change.name, change.old, change.new, change.owner)
  771. def _callback_wrapper(cb: t.Any) -> _CallbackWrapper:
  772. if isinstance(cb, _CallbackWrapper):
  773. return cb
  774. else:
  775. return _CallbackWrapper(cb)
  776. class MetaHasDescriptors(type):
  777. """A metaclass for HasDescriptors.
  778. This metaclass makes sure that any TraitType class attributes are
  779. instantiated and sets their name attribute.
  780. """
  781. def __new__(
  782. mcls: type[MetaHasDescriptors],
  783. name: str,
  784. bases: tuple[type, ...],
  785. classdict: dict[str, t.Any],
  786. **kwds: t.Any,
  787. ) -> MetaHasDescriptors:
  788. """Create the HasDescriptors class."""
  789. for k, v in classdict.items():
  790. # ----------------------------------------------------------------
  791. # Support of deprecated behavior allowing for TraitType types
  792. # to be used instead of TraitType instances.
  793. if inspect.isclass(v) and issubclass(v, TraitType):
  794. warn(
  795. "Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
  796. " Passing types is deprecated in traitlets 4.1.",
  797. DeprecationWarning,
  798. stacklevel=2,
  799. )
  800. classdict[k] = v()
  801. # ----------------------------------------------------------------
  802. return super().__new__(mcls, name, bases, classdict, **kwds)
  803. def __init__(
  804. cls, name: str, bases: tuple[type, ...], classdict: dict[str, t.Any], **kwds: t.Any
  805. ) -> None:
  806. """Finish initializing the HasDescriptors class."""
  807. super().__init__(name, bases, classdict, **kwds)
  808. cls.setup_class(classdict)
  809. def setup_class(cls: MetaHasDescriptors, classdict: dict[str, t.Any]) -> None:
  810. """Setup descriptor instance on the class
  811. This sets the :attr:`this_class` and :attr:`name` attributes of each
  812. BaseDescriptor in the class dict of the newly created ``cls`` before
  813. calling their :attr:`class_init` method.
  814. """
  815. cls._descriptors = []
  816. cls._instance_inits: list[t.Any] = []
  817. for k, v in classdict.items():
  818. if isinstance(v, BaseDescriptor):
  819. v.class_init(cls, k) # type:ignore[arg-type]
  820. for _, v in getmembers(cls):
  821. if isinstance(v, BaseDescriptor):
  822. v.subclass_init(cls) # type:ignore[arg-type]
  823. cls._descriptors.append(v)
  824. class MetaHasTraits(MetaHasDescriptors):
  825. """A metaclass for HasTraits."""
  826. def setup_class(cls: MetaHasTraits, classdict: dict[str, t.Any]) -> None:
  827. # for only the current class
  828. cls._trait_default_generators: dict[str, t.Any] = {}
  829. # also looking at base classes
  830. cls._all_trait_default_generators = {}
  831. cls._traits = {}
  832. cls._static_immutable_initial_values = {}
  833. super().setup_class(classdict)
  834. mro = cls.mro()
  835. for name in dir(cls):
  836. # Some descriptors raise AttributeError like zope.interface's
  837. # __provides__ attributes even though they exist. This causes
  838. # AttributeErrors even though they are listed in dir(cls).
  839. try:
  840. value = getattr(cls, name)
  841. except AttributeError:
  842. continue
  843. if isinstance(value, TraitType):
  844. cls._traits[name] = value
  845. trait = value
  846. default_method_name = "_%s_default" % name
  847. mro_trait = mro
  848. try:
  849. mro_trait = mro[: mro.index(trait.this_class) + 1] # type:ignore[arg-type]
  850. except ValueError:
  851. # this_class not in mro
  852. pass
  853. for c in mro_trait:
  854. if default_method_name in c.__dict__:
  855. cls._all_trait_default_generators[name] = c.__dict__[default_method_name]
  856. break
  857. if name in c.__dict__.get("_trait_default_generators", {}):
  858. cls._all_trait_default_generators[name] = c._trait_default_generators[name] # type: ignore[attr-defined]
  859. break
  860. else:
  861. # We don't have a dynamic default generator using @default etc.
  862. # Now if the default value is not dynamic and immutable (string, number)
  863. # and does not require any validation, we keep them in a dict
  864. # of initial values to speed up instance creation.
  865. # This is a very specific optimization, but a very common scenario in
  866. # for instance ipywidgets.
  867. none_ok = trait.default_value is None and trait.allow_none
  868. if (
  869. type(trait) in [CInt, Int]
  870. and trait.min is None # type: ignore[attr-defined]
  871. and trait.max is None # type: ignore[attr-defined]
  872. and (isinstance(trait.default_value, int) or none_ok)
  873. ):
  874. cls._static_immutable_initial_values[name] = trait.default_value
  875. elif (
  876. type(trait) in [CFloat, Float]
  877. and trait.min is None # type: ignore[attr-defined]
  878. and trait.max is None # type: ignore[attr-defined]
  879. and (isinstance(trait.default_value, float) or none_ok)
  880. ):
  881. cls._static_immutable_initial_values[name] = trait.default_value
  882. elif type(trait) in [CBool, Bool] and (
  883. isinstance(trait.default_value, bool) or none_ok
  884. ):
  885. cls._static_immutable_initial_values[name] = trait.default_value
  886. elif type(trait) in [CUnicode, Unicode] and (
  887. isinstance(trait.default_value, str) or none_ok
  888. ):
  889. cls._static_immutable_initial_values[name] = trait.default_value
  890. elif type(trait) == Any and (
  891. isinstance(trait.default_value, (str, int, float, bool)) or none_ok
  892. ):
  893. cls._static_immutable_initial_values[name] = trait.default_value
  894. elif type(trait) == Union and trait.default_value is None:
  895. cls._static_immutable_initial_values[name] = None
  896. elif (
  897. isinstance(trait, Instance)
  898. and trait.default_args is None
  899. and trait.default_kwargs is None
  900. and trait.allow_none
  901. ):
  902. cls._static_immutable_initial_values[name] = None
  903. # we always add it, because a class may change when we call add_trait
  904. # and then the instance may not have all the _static_immutable_initial_values
  905. cls._all_trait_default_generators[name] = trait.default
  906. def observe(*names: Sentinel | str, type: str = "change") -> ObserveHandler:
  907. """A decorator which can be used to observe Traits on a class.
  908. The handler passed to the decorator will be called with one ``change``
  909. dict argument. The change dictionary at least holds a 'type' key and a
  910. 'name' key, corresponding respectively to the type of notification and the
  911. name of the attribute that triggered the notification.
  912. Other keys may be passed depending on the value of 'type'. In the case
  913. where type is 'change', we also have the following keys:
  914. * ``owner`` : the HasTraits instance
  915. * ``old`` : the old value of the modified trait attribute
  916. * ``new`` : the new value of the modified trait attribute
  917. * ``name`` : the name of the modified trait attribute.
  918. Parameters
  919. ----------
  920. *names
  921. The str names of the Traits to observe on the object.
  922. type : str, kwarg-only
  923. The type of event to observe (e.g. 'change')
  924. """
  925. if not names:
  926. raise TypeError("Please specify at least one trait name to observe.")
  927. for name in names:
  928. if name is not All and not isinstance(name, str):
  929. raise TypeError("trait names to observe must be strings or All, not %r" % name)
  930. return ObserveHandler(names, type=type)
  931. def observe_compat(func: FuncT) -> FuncT:
  932. """Backward-compatibility shim decorator for observers
  933. Use with:
  934. @observe('name')
  935. @observe_compat
  936. def _foo_changed(self, change):
  937. ...
  938. With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
  939. Allows adoption of new observer API without breaking subclasses that override and super.
  940. """
  941. def compatible_observer(
  942. self: t.Any, change_or_name: str, old: t.Any = Undefined, new: t.Any = Undefined
  943. ) -> t.Any:
  944. if isinstance(change_or_name, dict): # type:ignore[unreachable]
  945. change = Bunch(change_or_name) # type:ignore[unreachable]
  946. else:
  947. clsname = self.__class__.__name__
  948. warn(
  949. f"A parent of {clsname}._{change_or_name}_changed has adopted the new (traitlets 4.1) @observe(change) API",
  950. DeprecationWarning,
  951. stacklevel=2,
  952. )
  953. change = Bunch(
  954. type="change",
  955. old=old,
  956. new=new,
  957. name=change_or_name,
  958. owner=self,
  959. )
  960. return func(self, change)
  961. return t.cast(FuncT, compatible_observer)
  962. def validate(*names: Sentinel | str) -> ValidateHandler:
  963. """A decorator to register cross validator of HasTraits object's state
  964. when a Trait is set.
  965. The handler passed to the decorator must have one ``proposal`` dict argument.
  966. The proposal dictionary must hold the following keys:
  967. * ``owner`` : the HasTraits instance
  968. * ``value`` : the proposed value for the modified trait attribute
  969. * ``trait`` : the TraitType instance associated with the attribute
  970. Parameters
  971. ----------
  972. *names
  973. The str names of the Traits to validate.
  974. Notes
  975. -----
  976. Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
  977. the registered cross validator could potentially make changes to attributes
  978. of the ``HasTraits`` instance. However, we recommend not to do so. The reason
  979. is that the cross-validation of attributes may run in arbitrary order when
  980. exiting the ``hold_trait_notifications`` context, and such changes may not
  981. commute.
  982. """
  983. if not names:
  984. raise TypeError("Please specify at least one trait name to validate.")
  985. for name in names:
  986. if name is not All and not isinstance(name, str):
  987. raise TypeError("trait names to validate must be strings or All, not %r" % name)
  988. return ValidateHandler(names)
  989. def default(name: str) -> DefaultHandler:
  990. """A decorator which assigns a dynamic default for a Trait on a HasTraits object.
  991. Parameters
  992. ----------
  993. name
  994. The str name of the Trait on the object whose default should be generated.
  995. Notes
  996. -----
  997. Unlike observers and validators which are properties of the HasTraits
  998. instance, default value generators are class-level properties.
  999. Besides, default generators are only invoked if they are registered in
  1000. subclasses of `this_type`.
  1001. ::
  1002. class A(HasTraits):
  1003. bar = Int()
  1004. @default('bar')
  1005. def get_bar_default(self):
  1006. return 11
  1007. class B(A):
  1008. bar = Float() # This trait ignores the default generator defined in
  1009. # the base class A
  1010. class C(B):
  1011. @default('bar')
  1012. def some_other_default(self): # This default generator should not be
  1013. return 3.0 # ignored since it is defined in a
  1014. # class derived from B.a.this_class.
  1015. """
  1016. if not isinstance(name, str):
  1017. raise TypeError("Trait name must be a string or All, not %r" % name)
  1018. return DefaultHandler(name)
  1019. FuncT = t.TypeVar("FuncT", bound=t.Callable[..., t.Any])
  1020. class EventHandler(BaseDescriptor):
  1021. def _init_call(self, func: FuncT) -> EventHandler:
  1022. self.func = func
  1023. return self
  1024. @t.overload
  1025. def __call__(self, func: FuncT, *args: t.Any, **kwargs: t.Any) -> FuncT:
  1026. ...
  1027. @t.overload
  1028. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  1029. ...
  1030. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  1031. """Pass `*args` and `**kwargs` to the handler's function if it exists."""
  1032. if hasattr(self, "func"):
  1033. return self.func(*args, **kwargs)
  1034. else:
  1035. return self._init_call(*args, **kwargs)
  1036. def __get__(self, inst: t.Any, cls: t.Any = None) -> types.MethodType | EventHandler:
  1037. if inst is None:
  1038. return self
  1039. return types.MethodType(self.func, inst)
  1040. class ObserveHandler(EventHandler):
  1041. def __init__(self, names: tuple[Sentinel | str, ...], type: str = "") -> None:
  1042. self.trait_names = names
  1043. self.type = type
  1044. def instance_init(self, inst: HasTraits) -> None:
  1045. inst.observe(self, self.trait_names, type=self.type)
  1046. class ValidateHandler(EventHandler):
  1047. def __init__(self, names: tuple[Sentinel | str, ...]) -> None:
  1048. self.trait_names = names
  1049. def instance_init(self, inst: HasTraits) -> None:
  1050. inst._register_validator(self, self.trait_names)
  1051. class DefaultHandler(EventHandler):
  1052. def __init__(self, name: str) -> None:
  1053. self.trait_name = name
  1054. def class_init(self, cls: type[HasTraits], name: str | None) -> None:
  1055. super().class_init(cls, name)
  1056. cls._trait_default_generators[self.trait_name] = self
  1057. class HasDescriptors(metaclass=MetaHasDescriptors):
  1058. """The base class for all classes that have descriptors."""
  1059. def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any:
  1060. # Pass cls as args[0] to allow "cls" as keyword argument
  1061. cls = args[0]
  1062. args = args[1:]
  1063. # This is needed because object.__new__ only accepts
  1064. # the cls argument.
  1065. new_meth = super(HasDescriptors, cls).__new__
  1066. if new_meth is object.__new__:
  1067. inst = new_meth(cls)
  1068. else:
  1069. inst = new_meth(cls, *args, **kwargs)
  1070. inst.setup_instance(*args, **kwargs)
  1071. return inst
  1072. def setup_instance(*args: t.Any, **kwargs: t.Any) -> None:
  1073. """
  1074. This is called **before** self.__init__ is called.
  1075. """
  1076. # Pass self as args[0] to allow "self" as keyword argument
  1077. self = args[0]
  1078. args = args[1:]
  1079. self._cross_validation_lock = False
  1080. cls = self.__class__
  1081. # Let descriptors performance initialization when a HasDescriptor
  1082. # instance is created. This allows registration of observers and
  1083. # default creations or other bookkeepings.
  1084. # Note that descriptors can opt-out of this behavior by overriding
  1085. # subclass_init.
  1086. for init in cls._instance_inits:
  1087. init(self)
  1088. class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
  1089. _trait_values: dict[str, t.Any]
  1090. _static_immutable_initial_values: dict[str, t.Any]
  1091. _trait_notifiers: dict[str | Sentinel, t.Any]
  1092. _trait_validators: dict[str | Sentinel, t.Any]
  1093. _cross_validation_lock: bool
  1094. _traits: dict[str, t.Any]
  1095. _all_trait_default_generators: dict[str, t.Any]
  1096. def setup_instance(*args: t.Any, **kwargs: t.Any) -> None:
  1097. # Pass self as args[0] to allow "self" as keyword argument
  1098. self = args[0]
  1099. args = args[1:]
  1100. # although we'd prefer to set only the initial values not present
  1101. # in kwargs, we will overwrite them in `__init__`, and simply making
  1102. # a copy of a dict is faster than checking for each key.
  1103. self._trait_values = self._static_immutable_initial_values.copy()
  1104. self._trait_notifiers = {}
  1105. self._trait_validators = {}
  1106. self._cross_validation_lock = False
  1107. super(HasTraits, self).setup_instance(*args, **kwargs)
  1108. def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
  1109. # Allow trait values to be set using keyword arguments.
  1110. # We need to use setattr for this to trigger validation and
  1111. # notifications.
  1112. super_args = args
  1113. super_kwargs = {}
  1114. if kwargs:
  1115. # this is a simplified (and faster) version of
  1116. # the hold_trait_notifications(self) context manager
  1117. def ignore(change: Bunch) -> None:
  1118. pass
  1119. self.notify_change = ignore # type:ignore[method-assign]
  1120. self._cross_validation_lock = True
  1121. changes = {}
  1122. for key, value in kwargs.items():
  1123. if self.has_trait(key):
  1124. setattr(self, key, value)
  1125. changes[key] = Bunch(
  1126. name=key,
  1127. old=None,
  1128. new=value,
  1129. owner=self,
  1130. type="change",
  1131. )
  1132. else:
  1133. # passthrough args that don't set traits to super
  1134. super_kwargs[key] = value
  1135. # notify and cross validate all trait changes that were set in kwargs
  1136. changed = set(kwargs) & set(self._traits)
  1137. for key in changed:
  1138. value = self._traits[key]._cross_validate(self, getattr(self, key))
  1139. self.set_trait(key, value)
  1140. changes[key]["new"] = value
  1141. self._cross_validation_lock = False
  1142. # Restore method retrieval from class
  1143. del self.notify_change
  1144. for key in changed:
  1145. self.notify_change(changes[key])
  1146. try:
  1147. super().__init__(*super_args, **super_kwargs)
  1148. except TypeError as e:
  1149. arg_s_list = [repr(arg) for arg in super_args]
  1150. for k, v in super_kwargs.items():
  1151. arg_s_list.append(f"{k}={v!r}")
  1152. arg_s = ", ".join(arg_s_list)
  1153. warn(
  1154. "Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n"
  1155. "{error}\n"
  1156. "This is deprecated in traitlets 4.2."
  1157. "This error will be raised in a future release of traitlets.".format(
  1158. arg_s=arg_s,
  1159. classname=self.__class__.__name__,
  1160. error=e,
  1161. ),
  1162. DeprecationWarning,
  1163. stacklevel=2,
  1164. )
  1165. def __getstate__(self) -> dict[str, t.Any]:
  1166. d = self.__dict__.copy()
  1167. # event handlers stored on an instance are
  1168. # expected to be reinstantiated during a
  1169. # recall of instance_init during __setstate__
  1170. d["_trait_notifiers"] = {}
  1171. d["_trait_validators"] = {}
  1172. d["_trait_values"] = self._trait_values.copy()
  1173. d["_cross_validation_lock"] = False # FIXME: raise if cloning locked!
  1174. return d
  1175. def __setstate__(self, state: dict[str, t.Any]) -> None:
  1176. self.__dict__ = state.copy()
  1177. # event handlers are reassigned to self
  1178. cls = self.__class__
  1179. for key in dir(cls):
  1180. # Some descriptors raise AttributeError like zope.interface's
  1181. # __provides__ attributes even though they exist. This causes
  1182. # AttributeErrors even though they are listed in dir(cls).
  1183. try:
  1184. value = getattr(cls, key)
  1185. except AttributeError:
  1186. pass
  1187. else:
  1188. if isinstance(value, EventHandler):
  1189. value.instance_init(self)
  1190. @property
  1191. @contextlib.contextmanager
  1192. def cross_validation_lock(self) -> t.Any:
  1193. """
  1194. A contextmanager for running a block with our cross validation lock set
  1195. to True.
  1196. At the end of the block, the lock's value is restored to its value
  1197. prior to entering the block.
  1198. """
  1199. if self._cross_validation_lock:
  1200. yield
  1201. return
  1202. else:
  1203. try:
  1204. self._cross_validation_lock = True
  1205. yield
  1206. finally:
  1207. self._cross_validation_lock = False
  1208. @contextlib.contextmanager
  1209. def hold_trait_notifications(self) -> t.Any:
  1210. """Context manager for bundling trait change notifications and cross
  1211. validation.
  1212. Use this when doing multiple trait assignments (init, config), to avoid
  1213. race conditions in trait notifiers requesting other trait values.
  1214. All trait notifications will fire after all values have been assigned.
  1215. """
  1216. if self._cross_validation_lock:
  1217. yield
  1218. return
  1219. else:
  1220. cache: dict[str, list[Bunch]] = {}
  1221. def compress(past_changes: list[Bunch] | None, change: Bunch) -> list[Bunch]:
  1222. """Merges the provided change with the last if possible."""
  1223. if past_changes is None:
  1224. return [change]
  1225. else:
  1226. if past_changes[-1]["type"] == "change" and change.type == "change":
  1227. past_changes[-1]["new"] = change.new
  1228. else:
  1229. # In case of changes other than 'change', append the notification.
  1230. past_changes.append(change)
  1231. return past_changes
  1232. def hold(change: Bunch) -> None:
  1233. name = change.name
  1234. cache[name] = compress(cache.get(name), change)
  1235. try:
  1236. # Replace notify_change with `hold`, caching and compressing
  1237. # notifications, disable cross validation and yield.
  1238. self.notify_change = hold # type:ignore[method-assign]
  1239. self._cross_validation_lock = True
  1240. yield
  1241. # Cross validate final values when context is released.
  1242. for name in list(cache.keys()):
  1243. trait = getattr(self.__class__, name)
  1244. value = trait._cross_validate(self, getattr(self, name))
  1245. self.set_trait(name, value)
  1246. except TraitError as e:
  1247. # Roll back in case of TraitError during final cross validation.
  1248. self.notify_change = lambda x: None # type:ignore[method-assign, assignment] # noqa: ARG005
  1249. for name, changes in cache.items():
  1250. for change in changes[::-1]:
  1251. # TODO: Separate in a rollback function per notification type.
  1252. if change.type == "change":
  1253. if change.old is not Undefined:
  1254. self.set_trait(name, change.old)
  1255. else:
  1256. self._trait_values.pop(name)
  1257. cache = {}
  1258. raise e
  1259. finally:
  1260. self._cross_validation_lock = False
  1261. # Restore method retrieval from class
  1262. del self.notify_change
  1263. # trigger delayed notifications
  1264. for changes in cache.values():
  1265. for change in changes:
  1266. self.notify_change(change)
  1267. def _notify_trait(self, name: str, old_value: t.Any, new_value: t.Any) -> None:
  1268. self.notify_change(
  1269. Bunch(
  1270. name=name,
  1271. old=old_value,
  1272. new=new_value,
  1273. owner=self,
  1274. type="change",
  1275. )
  1276. )
  1277. def notify_change(self, change: Bunch) -> None:
  1278. """Notify observers of a change event"""
  1279. return self._notify_observers(change)
  1280. def _notify_observers(self, event: Bunch) -> None:
  1281. """Notify observers of any event"""
  1282. if not isinstance(event, Bunch):
  1283. # cast to bunch if given a dict
  1284. event = Bunch(event) # type:ignore[unreachable]
  1285. name, type = event["name"], event["type"]
  1286. callables = []
  1287. if name in self._trait_notifiers:
  1288. callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
  1289. callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
  1290. if All in self._trait_notifiers:
  1291. callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
  1292. callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
  1293. # Now static ones
  1294. magic_name = "_%s_changed" % name
  1295. if event["type"] == "change" and hasattr(self, magic_name):
  1296. class_value = getattr(self.__class__, magic_name)
  1297. if not isinstance(class_value, ObserveHandler):
  1298. deprecated_method(
  1299. class_value,
  1300. self.__class__,
  1301. magic_name,
  1302. "use @observe and @unobserve instead.",
  1303. )
  1304. cb = getattr(self, magic_name)
  1305. # Only append the magic method if it was not manually registered
  1306. if cb not in callables:
  1307. callables.append(_callback_wrapper(cb))
  1308. # Call them all now
  1309. # Traits catches and logs errors here. I allow them to raise
  1310. for c in callables:
  1311. # Bound methods have an additional 'self' argument.
  1312. if isinstance(c, _CallbackWrapper):
  1313. c = c.__call__
  1314. elif isinstance(c, EventHandler) and c.name is not None:
  1315. c = getattr(self, c.name)
  1316. c(event)
  1317. def _add_notifiers(
  1318. self, handler: t.Callable[..., t.Any], name: Sentinel | str, type: str | Sentinel
  1319. ) -> None:
  1320. if name not in self._trait_notifiers:
  1321. nlist: list[t.Any] = []
  1322. self._trait_notifiers[name] = {type: nlist}
  1323. else:
  1324. if type not in self._trait_notifiers[name]:
  1325. nlist = []
  1326. self._trait_notifiers[name][type] = nlist
  1327. else:
  1328. nlist = self._trait_notifiers[name][type]
  1329. if handler not in nlist:
  1330. nlist.append(handler)
  1331. def _remove_notifiers(
  1332. self, handler: t.Callable[..., t.Any] | None, name: Sentinel | str, type: str | Sentinel
  1333. ) -> None:
  1334. try:
  1335. if handler is None:
  1336. del self._trait_notifiers[name][type]
  1337. else:
  1338. self._trait_notifiers[name][type].remove(handler)
  1339. except KeyError:
  1340. pass
  1341. def on_trait_change(
  1342. self,
  1343. handler: EventHandler | None = None,
  1344. name: Sentinel | str | None = None,
  1345. remove: bool = False,
  1346. ) -> None:
  1347. """DEPRECATED: Setup a handler to be called when a trait changes.
  1348. This is used to setup dynamic notifications of trait changes.
  1349. Static handlers can be created by creating methods on a HasTraits
  1350. subclass with the naming convention '_[traitname]_changed'. Thus,
  1351. to create static handler for the trait 'a', create the method
  1352. _a_changed(self, name, old, new) (fewer arguments can be used, see
  1353. below).
  1354. If `remove` is True and `handler` is not specified, all change
  1355. handlers for the specified name are uninstalled.
  1356. Parameters
  1357. ----------
  1358. handler : callable, None
  1359. A callable that is called when a trait changes. Its
  1360. signature can be handler(), handler(name), handler(name, new),
  1361. handler(name, old, new), or handler(name, old, new, self).
  1362. name : list, str, None
  1363. If None, the handler will apply to all traits. If a list
  1364. of str, handler will apply to all names in the list. If a
  1365. str, the handler will apply just to that name.
  1366. remove : bool
  1367. If False (the default), then install the handler. If True
  1368. then unintall it.
  1369. """
  1370. warn(
  1371. "on_trait_change is deprecated in traitlets 4.1: use observe instead",
  1372. DeprecationWarning,
  1373. stacklevel=2,
  1374. )
  1375. if name is None:
  1376. name = All
  1377. if remove:
  1378. self.unobserve(_callback_wrapper(handler), names=name)
  1379. else:
  1380. self.observe(_callback_wrapper(handler), names=name)
  1381. def observe(
  1382. self,
  1383. handler: t.Callable[..., t.Any],
  1384. names: Sentinel | str | t.Iterable[Sentinel | str] = All,
  1385. type: Sentinel | str = "change",
  1386. ) -> None:
  1387. """Setup a handler to be called when a trait changes.
  1388. This is used to setup dynamic notifications of trait changes.
  1389. Parameters
  1390. ----------
  1391. handler : callable
  1392. A callable that is called when a trait changes. Its
  1393. signature should be ``handler(change)``, where ``change`` is a
  1394. dictionary. The change dictionary at least holds a 'type' key.
  1395. * ``type``: the type of notification.
  1396. Other keys may be passed depending on the value of 'type'. In the
  1397. case where type is 'change', we also have the following keys:
  1398. * ``owner`` : the HasTraits instance
  1399. * ``old`` : the old value of the modified trait attribute
  1400. * ``new`` : the new value of the modified trait attribute
  1401. * ``name`` : the name of the modified trait attribute.
  1402. names : list, str, All
  1403. If names is All, the handler will apply to all traits. If a list
  1404. of str, handler will apply to all names in the list. If a
  1405. str, the handler will apply just to that name.
  1406. type : str, All (default: 'change')
  1407. The type of notification to filter by. If equal to All, then all
  1408. notifications are passed to the observe handler.
  1409. """
  1410. for name in parse_notifier_name(names):
  1411. self._add_notifiers(handler, name, type)
  1412. def unobserve(
  1413. self,
  1414. handler: t.Callable[..., t.Any],
  1415. names: Sentinel | str | t.Iterable[Sentinel | str] = All,
  1416. type: Sentinel | str = "change",
  1417. ) -> None:
  1418. """Remove a trait change handler.
  1419. This is used to unregister handlers to trait change notifications.
  1420. Parameters
  1421. ----------
  1422. handler : callable
  1423. The callable called when a trait attribute changes.
  1424. names : list, str, All (default: All)
  1425. The names of the traits for which the specified handler should be
  1426. uninstalled. If names is All, the specified handler is uninstalled
  1427. from the list of notifiers corresponding to all changes.
  1428. type : str or All (default: 'change')
  1429. The type of notification to filter by. If All, the specified handler
  1430. is uninstalled from the list of notifiers corresponding to all types.
  1431. """
  1432. for name in parse_notifier_name(names):
  1433. self._remove_notifiers(handler, name, type)
  1434. def unobserve_all(self, name: str | t.Any = All) -> None:
  1435. """Remove trait change handlers of any type for the specified name.
  1436. If name is not specified, removes all trait notifiers."""
  1437. if name is All:
  1438. self._trait_notifiers = {}
  1439. else:
  1440. try:
  1441. del self._trait_notifiers[name]
  1442. except KeyError:
  1443. pass
  1444. def _register_validator(
  1445. self, handler: t.Callable[..., None], names: tuple[str | Sentinel, ...]
  1446. ) -> None:
  1447. """Setup a handler to be called when a trait should be cross validated.
  1448. This is used to setup dynamic notifications for cross-validation.
  1449. If a validator is already registered for any of the provided names, a
  1450. TraitError is raised and no new validator is registered.
  1451. Parameters
  1452. ----------
  1453. handler : callable
  1454. A callable that is called when the given trait is cross-validated.
  1455. Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
  1456. with the following attributes/keys:
  1457. * ``owner`` : the HasTraits instance
  1458. * ``value`` : the proposed value for the modified trait attribute
  1459. * ``trait`` : the TraitType instance associated with the attribute
  1460. names : List of strings
  1461. The names of the traits that should be cross-validated
  1462. """
  1463. for name in names:
  1464. magic_name = "_%s_validate" % name
  1465. if hasattr(self, magic_name):
  1466. class_value = getattr(self.__class__, magic_name)
  1467. if not isinstance(class_value, ValidateHandler):
  1468. deprecated_method(
  1469. class_value,
  1470. self.__class__,
  1471. magic_name,
  1472. "use @validate decorator instead.",
  1473. )
  1474. for name in names:
  1475. self._trait_validators[name] = handler
  1476. def add_traits(self, **traits: t.Any) -> None:
  1477. """Dynamically add trait attributes to the HasTraits instance."""
  1478. cls = self.__class__
  1479. attrs = {"__module__": cls.__module__}
  1480. if hasattr(cls, "__qualname__"):
  1481. # __qualname__ introduced in Python 3.3 (see PEP 3155)
  1482. attrs["__qualname__"] = cls.__qualname__
  1483. attrs.update(traits)
  1484. self.__class__ = type(cls.__name__, (cls,), attrs)
  1485. for trait in traits.values():
  1486. trait.instance_init(self)
  1487. def set_trait(self, name: str, value: t.Any) -> None:
  1488. """Forcibly sets trait attribute, including read-only attributes."""
  1489. cls = self.__class__
  1490. if not self.has_trait(name):
  1491. raise TraitError(f"Class {cls.__name__} does not have a trait named {name}")
  1492. getattr(cls, name).set(self, value)
  1493. @classmethod
  1494. def class_trait_names(cls: type[HasTraits], **metadata: t.Any) -> list[str]:
  1495. """Get a list of all the names of this class' traits.
  1496. This method is just like the :meth:`trait_names` method,
  1497. but is unbound.
  1498. """
  1499. return list(cls.class_traits(**metadata))
  1500. @classmethod
  1501. def class_traits(cls: type[HasTraits], **metadata: t.Any) -> dict[str, TraitType[t.Any, t.Any]]:
  1502. """Get a ``dict`` of all the traits of this class. The dictionary
  1503. is keyed on the name and the values are the TraitType objects.
  1504. This method is just like the :meth:`traits` method, but is unbound.
  1505. The TraitTypes returned don't know anything about the values
  1506. that the various HasTrait's instances are holding.
  1507. The metadata kwargs allow functions to be passed in which
  1508. filter traits based on metadata values. The functions should
  1509. take a single value as an argument and return a boolean. If
  1510. any function returns False, then the trait is not included in
  1511. the output. If a metadata key doesn't exist, None will be passed
  1512. to the function.
  1513. """
  1514. traits = cls._traits.copy()
  1515. if len(metadata) == 0:
  1516. return traits
  1517. result = {}
  1518. for name, trait in traits.items():
  1519. for meta_name, meta_eval in metadata.items():
  1520. if not callable(meta_eval):
  1521. meta_eval = _SimpleTest(meta_eval)
  1522. if not meta_eval(trait.metadata.get(meta_name, None)):
  1523. break
  1524. else:
  1525. result[name] = trait
  1526. return result
  1527. @classmethod
  1528. def class_own_traits(
  1529. cls: type[HasTraits], **metadata: t.Any
  1530. ) -> dict[str, TraitType[t.Any, t.Any]]:
  1531. """Get a dict of all the traitlets defined on this class, not a parent.
  1532. Works like `class_traits`, except for excluding traits from parents.
  1533. """
  1534. sup = super(cls, cls)
  1535. return {
  1536. n: t
  1537. for (n, t) in cls.class_traits(**metadata).items()
  1538. if getattr(sup, n, None) is not t
  1539. }
  1540. def has_trait(self, name: str) -> bool:
  1541. """Returns True if the object has a trait with the specified name."""
  1542. return name in self._traits
  1543. def trait_has_value(self, name: str) -> bool:
  1544. """Returns True if the specified trait has a value.
  1545. This will return false even if ``getattr`` would return a
  1546. dynamically generated default value. These default values
  1547. will be recognized as existing only after they have been
  1548. generated.
  1549. Example
  1550. .. code-block:: python
  1551. class MyClass(HasTraits):
  1552. i = Int()
  1553. mc = MyClass()
  1554. assert not mc.trait_has_value("i")
  1555. mc.i # generates a default value
  1556. assert mc.trait_has_value("i")
  1557. """
  1558. return name in self._trait_values
  1559. def trait_values(self, **metadata: t.Any) -> dict[str, t.Any]:
  1560. """A ``dict`` of trait names and their values.
  1561. The metadata kwargs allow functions to be passed in which
  1562. filter traits based on metadata values. The functions should
  1563. take a single value as an argument and return a boolean. If
  1564. any function returns False, then the trait is not included in
  1565. the output. If a metadata key doesn't exist, None will be passed
  1566. to the function.
  1567. Returns
  1568. -------
  1569. A ``dict`` of trait names and their values.
  1570. Notes
  1571. -----
  1572. Trait values are retrieved via ``getattr``, any exceptions raised
  1573. by traits or the operations they may trigger will result in the
  1574. absence of a trait value in the result ``dict``.
  1575. """
  1576. return {name: getattr(self, name) for name in self.trait_names(**metadata)}
  1577. def _get_trait_default_generator(self, name: str) -> t.Any:
  1578. """Return default generator for a given trait
  1579. Walk the MRO to resolve the correct default generator according to inheritance.
  1580. """
  1581. method_name = "_%s_default" % name
  1582. if method_name in self.__dict__:
  1583. return getattr(self, method_name)
  1584. if method_name in self.__class__.__dict__:
  1585. return getattr(self.__class__, method_name)
  1586. return self._all_trait_default_generators[name]
  1587. def trait_defaults(self, *names: str, **metadata: t.Any) -> dict[str, t.Any] | Sentinel:
  1588. """Return a trait's default value or a dictionary of them
  1589. Notes
  1590. -----
  1591. Dynamically generated default values may
  1592. depend on the current state of the object."""
  1593. for n in names:
  1594. if not self.has_trait(n):
  1595. raise TraitError(f"'{n}' is not a trait of '{type(self).__name__}' instances")
  1596. if len(names) == 1 and len(metadata) == 0:
  1597. return t.cast(Sentinel, self._get_trait_default_generator(names[0])(self))
  1598. trait_names = self.trait_names(**metadata)
  1599. trait_names.extend(names)
  1600. defaults = {}
  1601. for n in trait_names:
  1602. defaults[n] = self._get_trait_default_generator(n)(self)
  1603. return defaults
  1604. def trait_names(self, **metadata: t.Any) -> list[str]:
  1605. """Get a list of all the names of this class' traits."""
  1606. return list(self.traits(**metadata))
  1607. def traits(self, **metadata: t.Any) -> dict[str, TraitType[t.Any, t.Any]]:
  1608. """Get a ``dict`` of all the traits of this class. The dictionary
  1609. is keyed on the name and the values are the TraitType objects.
  1610. The TraitTypes returned don't know anything about the values
  1611. that the various HasTrait's instances are holding.
  1612. The metadata kwargs allow functions to be passed in which
  1613. filter traits based on metadata values. The functions should
  1614. take a single value as an argument and return a boolean. If
  1615. any function returns False, then the trait is not included in
  1616. the output. If a metadata key doesn't exist, None will be passed
  1617. to the function.
  1618. """
  1619. traits = self._traits.copy()
  1620. if len(metadata) == 0:
  1621. return traits
  1622. result = {}
  1623. for name, trait in traits.items():
  1624. for meta_name, meta_eval in metadata.items():
  1625. if not callable(meta_eval):
  1626. meta_eval = _SimpleTest(meta_eval)
  1627. if not meta_eval(trait.metadata.get(meta_name, None)):
  1628. break
  1629. else:
  1630. result[name] = trait
  1631. return result
  1632. def trait_metadata(self, traitname: str, key: str, default: t.Any = None) -> t.Any:
  1633. """Get metadata values for trait by key."""
  1634. try:
  1635. trait = getattr(self.__class__, traitname)
  1636. except AttributeError as e:
  1637. raise TraitError(
  1638. f"Class {self.__class__.__name__} does not have a trait named {traitname}"
  1639. ) from e
  1640. metadata_name = "_" + traitname + "_metadata"
  1641. if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
  1642. return getattr(self, metadata_name).get(key, default)
  1643. else:
  1644. return trait.metadata.get(key, default)
  1645. @classmethod
  1646. def class_own_trait_events(cls: type[HasTraits], name: str) -> dict[str, EventHandler]:
  1647. """Get a dict of all event handlers defined on this class, not a parent.
  1648. Works like ``event_handlers``, except for excluding traits from parents.
  1649. """
  1650. sup = super(cls, cls)
  1651. return {
  1652. n: e
  1653. for (n, e) in cls.events(name).items() # type:ignore[attr-defined]
  1654. if getattr(sup, n, None) is not e
  1655. }
  1656. @classmethod
  1657. def trait_events(cls: type[HasTraits], name: str | None = None) -> dict[str, EventHandler]:
  1658. """Get a ``dict`` of all the event handlers of this class.
  1659. Parameters
  1660. ----------
  1661. name : str (default: None)
  1662. The name of a trait of this class. If name is ``None`` then all
  1663. the event handlers of this class will be returned instead.
  1664. Returns
  1665. -------
  1666. The event handlers associated with a trait name, or all event handlers.
  1667. """
  1668. events = {}
  1669. for k, v in getmembers(cls):
  1670. if isinstance(v, EventHandler):
  1671. if name is None:
  1672. events[k] = v
  1673. elif name in v.trait_names: # type:ignore[attr-defined]
  1674. events[k] = v
  1675. elif hasattr(v, "tags"):
  1676. if cls.trait_names(**v.tags):
  1677. events[k] = v
  1678. return events
  1679. # -----------------------------------------------------------------------------
  1680. # Actual TraitTypes implementations/subclasses
  1681. # -----------------------------------------------------------------------------
  1682. # -----------------------------------------------------------------------------
  1683. # TraitTypes subclasses for handling classes and instances of classes
  1684. # -----------------------------------------------------------------------------
  1685. class ClassBasedTraitType(TraitType[G, S]):
  1686. """
  1687. A trait with error reporting and string -> type resolution for Type,
  1688. Instance and This.
  1689. """
  1690. def _resolve_string(self, string: str) -> t.Any:
  1691. """
  1692. Resolve a string supplied for a type into an actual object.
  1693. """
  1694. return import_item(string)
  1695. class Type(ClassBasedTraitType[G, S]):
  1696. """A trait whose value must be a subclass of a specified class."""
  1697. if t.TYPE_CHECKING:
  1698. @t.overload
  1699. def __init__(
  1700. self: Type[type, type],
  1701. default_value: Sentinel | None | str = ...,
  1702. klass: None | str = ...,
  1703. allow_none: Literal[False] = ...,
  1704. read_only: bool | None = ...,
  1705. help: str | None = ...,
  1706. config: t.Any | None = ...,
  1707. **kwargs: t.Any,
  1708. ) -> None:
  1709. ...
  1710. @t.overload
  1711. def __init__(
  1712. self: Type[type | None, type | None],
  1713. default_value: Sentinel | None | str = ...,
  1714. klass: None | str = ...,
  1715. allow_none: Literal[True] = ...,
  1716. read_only: bool | None = ...,
  1717. help: str | None = ...,
  1718. config: t.Any | None = ...,
  1719. **kwargs: t.Any,
  1720. ) -> None:
  1721. ...
  1722. @t.overload
  1723. def __init__(
  1724. self: Type[S, S],
  1725. default_value: S = ...,
  1726. klass: S = ...,
  1727. allow_none: Literal[False] = ...,
  1728. read_only: bool | None = ...,
  1729. help: str | None = ...,
  1730. config: t.Any | None = ...,
  1731. **kwargs: t.Any,
  1732. ) -> None:
  1733. ...
  1734. @t.overload
  1735. def __init__(
  1736. self: Type[S | None, S | None],
  1737. default_value: S | None = ...,
  1738. klass: S = ...,
  1739. allow_none: Literal[True] = ...,
  1740. read_only: bool | None = ...,
  1741. help: str | None = ...,
  1742. config: t.Any | None = ...,
  1743. **kwargs: t.Any,
  1744. ) -> None:
  1745. ...
  1746. def __init__(
  1747. self,
  1748. default_value: t.Any = Undefined,
  1749. klass: t.Any = None,
  1750. allow_none: bool = False,
  1751. read_only: bool | None = None,
  1752. help: str | None = None,
  1753. config: t.Any | None = None,
  1754. **kwargs: t.Any,
  1755. ) -> None:
  1756. """Construct a Type trait
  1757. A Type trait specifies that its values must be subclasses of
  1758. a particular class.
  1759. If only ``default_value`` is given, it is used for the ``klass`` as
  1760. well. If neither are given, both default to ``object``.
  1761. Parameters
  1762. ----------
  1763. default_value : class, str or None
  1764. The default value must be a subclass of klass. If an str,
  1765. the str must be a fully specified class name, like 'foo.bar.Bah'.
  1766. The string is resolved into real class, when the parent
  1767. :class:`HasTraits` class is instantiated.
  1768. klass : class, str [ default object ]
  1769. Values of this trait must be a subclass of klass. The klass
  1770. may be specified in a string like: 'foo.bar.MyClass'.
  1771. The string is resolved into real class, when the parent
  1772. :class:`HasTraits` class is instantiated.
  1773. allow_none : bool [ default False ]
  1774. Indicates whether None is allowed as an assignable value.
  1775. **kwargs
  1776. extra kwargs passed to `ClassBasedTraitType`
  1777. """
  1778. if default_value is Undefined:
  1779. new_default_value = object if (klass is None) else klass
  1780. else:
  1781. new_default_value = default_value
  1782. if klass is None:
  1783. if (default_value is None) or (default_value is Undefined):
  1784. klass = object
  1785. else:
  1786. klass = default_value
  1787. if not (inspect.isclass(klass) or isinstance(klass, str)):
  1788. raise TraitError("A Type trait must specify a class.")
  1789. self.klass = klass
  1790. super().__init__(
  1791. new_default_value,
  1792. allow_none=allow_none,
  1793. read_only=read_only,
  1794. help=help,
  1795. config=config,
  1796. **kwargs,
  1797. )
  1798. def validate(self, obj: t.Any, value: t.Any) -> G:
  1799. """Validates that the value is a valid object instance."""
  1800. if isinstance(value, str):
  1801. try:
  1802. value = self._resolve_string(value)
  1803. except ImportError as e:
  1804. raise TraitError(
  1805. f"The '{self.name}' trait of {obj} instance must be a type, but "
  1806. f"{value!r} could not be imported"
  1807. ) from e
  1808. try:
  1809. if issubclass(value, self.klass): # type:ignore[arg-type]
  1810. return t.cast(G, value)
  1811. except Exception:
  1812. pass
  1813. self.error(obj, value)
  1814. def info(self) -> str:
  1815. """Returns a description of the trait."""
  1816. if isinstance(self.klass, str):
  1817. klass = self.klass
  1818. else:
  1819. klass = self.klass.__module__ + "." + self.klass.__name__
  1820. result = "a subclass of '%s'" % klass
  1821. if self.allow_none:
  1822. return result + " or None"
  1823. return result
  1824. def instance_init(self, obj: t.Any) -> None:
  1825. # we can't do this in subclass_init because that
  1826. # might be called before all imports are done.
  1827. self._resolve_classes()
  1828. def _resolve_classes(self) -> None:
  1829. if isinstance(self.klass, str):
  1830. self.klass = self._resolve_string(self.klass)
  1831. if isinstance(self.default_value, str):
  1832. self.default_value = self._resolve_string(self.default_value)
  1833. def default_value_repr(self) -> str:
  1834. value = self.default_value
  1835. assert value is not None
  1836. if isinstance(value, str):
  1837. return repr(value)
  1838. else:
  1839. return repr(f"{value.__module__}.{value.__name__}")
  1840. class Instance(ClassBasedTraitType[T, T]):
  1841. """A trait whose value must be an instance of a specified class.
  1842. The value can also be an instance of a subclass of the specified class.
  1843. Subclasses can declare default classes by overriding the klass attribute
  1844. """
  1845. klass: str | type[T] | None = None
  1846. if t.TYPE_CHECKING:
  1847. @t.overload
  1848. def __init__(
  1849. self: Instance[T],
  1850. klass: type[T] = ...,
  1851. args: tuple[t.Any, ...] | None = ...,
  1852. kw: dict[str, t.Any] | None = ...,
  1853. allow_none: Literal[False] = ...,
  1854. read_only: bool | None = ...,
  1855. help: str | None = ...,
  1856. **kwargs: t.Any,
  1857. ) -> None:
  1858. ...
  1859. @t.overload
  1860. def __init__(
  1861. self: Instance[T | None],
  1862. klass: type[T] = ...,
  1863. args: tuple[t.Any, ...] | None = ...,
  1864. kw: dict[str, t.Any] | None = ...,
  1865. allow_none: Literal[True] = ...,
  1866. read_only: bool | None = ...,
  1867. help: str | None = ...,
  1868. **kwargs: t.Any,
  1869. ) -> None:
  1870. ...
  1871. @t.overload
  1872. def __init__(
  1873. self: Instance[t.Any],
  1874. klass: str | None = ...,
  1875. args: tuple[t.Any, ...] | None = ...,
  1876. kw: dict[str, t.Any] | None = ...,
  1877. allow_none: Literal[False] = ...,
  1878. read_only: bool | None = ...,
  1879. help: str | None = ...,
  1880. **kwargs: t.Any,
  1881. ) -> None:
  1882. ...
  1883. @t.overload
  1884. def __init__(
  1885. self: Instance[t.Any | None],
  1886. klass: str | None = ...,
  1887. args: tuple[t.Any, ...] | None = ...,
  1888. kw: dict[str, t.Any] | None = ...,
  1889. allow_none: Literal[True] = ...,
  1890. read_only: bool | None = ...,
  1891. help: str | None = ...,
  1892. **kwargs: t.Any,
  1893. ) -> None:
  1894. ...
  1895. def __init__(
  1896. self,
  1897. klass: str | type[T] | None = None,
  1898. args: tuple[t.Any, ...] | None = None,
  1899. kw: dict[str, t.Any] | None = None,
  1900. allow_none: bool = False,
  1901. read_only: bool | None = None,
  1902. help: str | None = None,
  1903. **kwargs: t.Any,
  1904. ) -> None:
  1905. """Construct an Instance trait.
  1906. This trait allows values that are instances of a particular
  1907. class or its subclasses. Our implementation is quite different
  1908. from that of enthough.traits as we don't allow instances to be used
  1909. for klass and we handle the ``args`` and ``kw`` arguments differently.
  1910. Parameters
  1911. ----------
  1912. klass : class, str
  1913. The class that forms the basis for the trait. Class names
  1914. can also be specified as strings, like 'foo.bar.Bar'.
  1915. args : tuple
  1916. Positional arguments for generating the default value.
  1917. kw : dict
  1918. Keyword arguments for generating the default value.
  1919. allow_none : bool [ default False ]
  1920. Indicates whether None is allowed as a value.
  1921. **kwargs
  1922. Extra kwargs passed to `ClassBasedTraitType`
  1923. Notes
  1924. -----
  1925. If both ``args`` and ``kw`` are None, then the default value is None.
  1926. If ``args`` is a tuple and ``kw`` is a dict, then the default is
  1927. created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
  1928. None, the None is replaced by ``()`` or ``{}``, respectively.
  1929. """
  1930. if klass is None:
  1931. klass = self.klass
  1932. if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)):
  1933. self.klass = klass
  1934. else:
  1935. raise TraitError("The klass attribute must be a class not: %r" % klass)
  1936. if (kw is not None) and not isinstance(kw, dict):
  1937. raise TraitError("The 'kw' argument must be a dict or None.")
  1938. if (args is not None) and not isinstance(args, tuple):
  1939. raise TraitError("The 'args' argument must be a tuple or None.")
  1940. self.default_args = args
  1941. self.default_kwargs = kw
  1942. super().__init__(allow_none=allow_none, read_only=read_only, help=help, **kwargs)
  1943. def validate(self, obj: t.Any, value: t.Any) -> T | None:
  1944. assert self.klass is not None
  1945. if self.allow_none and value is None:
  1946. return value
  1947. if isinstance(value, self.klass): # type:ignore[arg-type]
  1948. return t.cast(T, value)
  1949. else:
  1950. self.error(obj, value)
  1951. def info(self) -> str:
  1952. if isinstance(self.klass, str):
  1953. result = add_article(self.klass)
  1954. else:
  1955. result = describe("a", self.klass)
  1956. if self.allow_none:
  1957. result += " or None"
  1958. return result
  1959. def instance_init(self, obj: t.Any) -> None:
  1960. # we can't do this in subclass_init because that
  1961. # might be called before all imports are done.
  1962. self._resolve_classes()
  1963. def _resolve_classes(self) -> None:
  1964. if isinstance(self.klass, str):
  1965. self.klass = self._resolve_string(self.klass)
  1966. def make_dynamic_default(self) -> T | None:
  1967. if (self.default_args is None) and (self.default_kwargs is None):
  1968. return None
  1969. assert self.klass is not None
  1970. return self.klass(*(self.default_args or ()), **(self.default_kwargs or {})) # type:ignore[operator]
  1971. def default_value_repr(self) -> str:
  1972. return repr(self.make_dynamic_default())
  1973. def from_string(self, s: str) -> T | None:
  1974. return t.cast(T, _safe_literal_eval(s))
  1975. class ForwardDeclaredMixin:
  1976. """
  1977. Mixin for forward-declared versions of Instance and Type.
  1978. """
  1979. def _resolve_string(self, string: str) -> t.Any:
  1980. """
  1981. Find the specified class name by looking for it in the module in which
  1982. our this_class attribute was defined.
  1983. """
  1984. modname = self.this_class.__module__ # type:ignore[attr-defined]
  1985. return import_item(".".join([modname, string]))
  1986. class ForwardDeclaredType(ForwardDeclaredMixin, Type[G, S]):
  1987. """
  1988. Forward-declared version of Type.
  1989. """
  1990. class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance[T]):
  1991. """
  1992. Forward-declared version of Instance.
  1993. """
  1994. class This(ClassBasedTraitType[t.Optional[T], t.Optional[T]]):
  1995. """A trait for instances of the class containing this trait.
  1996. Because how how and when class bodies are executed, the ``This``
  1997. trait can only have a default value of None. This, and because we
  1998. always validate default values, ``allow_none`` is *always* true.
  1999. """
  2000. info_text = "an instance of the same type as the receiver or None"
  2001. def __init__(self, **kwargs: t.Any) -> None:
  2002. super().__init__(None, **kwargs)
  2003. def validate(self, obj: t.Any, value: t.Any) -> HasTraits | None:
  2004. # What if value is a superclass of obj.__class__? This is
  2005. # complicated if it was the superclass that defined the This
  2006. # trait.
  2007. assert self.this_class is not None
  2008. if isinstance(value, self.this_class) or (value is None):
  2009. return value
  2010. else:
  2011. self.error(obj, value)
  2012. class Union(TraitType[t.Any, t.Any]):
  2013. """A trait type representing a Union type."""
  2014. def __init__(self, trait_types: t.Any, **kwargs: t.Any) -> None:
  2015. """Construct a Union trait.
  2016. This trait allows values that are allowed by at least one of the
  2017. specified trait types. A Union traitlet cannot have metadata on
  2018. its own, besides the metadata of the listed types.
  2019. Parameters
  2020. ----------
  2021. trait_types : sequence
  2022. The list of trait types of length at least 1.
  2023. **kwargs
  2024. Extra kwargs passed to `TraitType`
  2025. Notes
  2026. -----
  2027. Union([Float(), Bool(), Int()]) attempts to validate the provided values
  2028. with the validation function of Float, then Bool, and finally Int.
  2029. Parsing from string is ambiguous for container types which accept other
  2030. collection-like literals (e.g. List accepting both `[]` and `()`
  2031. precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
  2032. you can modify behaviour of too permissive container traits by overriding
  2033. ``_literal_from_string_pairs`` in subclasses.
  2034. Similarly, parsing unions of numeric types is only unambiguous if
  2035. types are provided in order of increasing permissiveness, e.g.
  2036. ``Union([Int(), Float()])`` (since floats accept integer-looking values).
  2037. """
  2038. self.trait_types = list(trait_types)
  2039. self.info_text = " or ".join([tt.info() for tt in self.trait_types])
  2040. super().__init__(**kwargs)
  2041. def default(self, obj: t.Any = None) -> t.Any:
  2042. default = super().default(obj)
  2043. for trait in self.trait_types:
  2044. if default is Undefined:
  2045. default = trait.default(obj)
  2046. else:
  2047. break
  2048. return default
  2049. def class_init(self, cls: type[HasTraits], name: str | None) -> None:
  2050. for trait_type in reversed(self.trait_types):
  2051. trait_type.class_init(cls, None)
  2052. super().class_init(cls, name)
  2053. def subclass_init(self, cls: type[t.Any]) -> None:
  2054. for trait_type in reversed(self.trait_types):
  2055. trait_type.subclass_init(cls)
  2056. # explicitly not calling super().subclass_init(cls)
  2057. # to opt out of instance_init
  2058. def validate(self, obj: t.Any, value: t.Any) -> t.Any:
  2059. with obj.cross_validation_lock:
  2060. for trait_type in self.trait_types:
  2061. try:
  2062. v = trait_type._validate(obj, value)
  2063. # In the case of an element trait, the name is None
  2064. if self.name is not None:
  2065. setattr(obj, "_" + self.name + "_metadata", trait_type.metadata)
  2066. return v
  2067. except TraitError:
  2068. continue
  2069. self.error(obj, value)
  2070. def __or__(self, other: t.Any) -> Union:
  2071. if isinstance(other, Union):
  2072. return Union(self.trait_types + other.trait_types)
  2073. else:
  2074. return Union([*self.trait_types, other])
  2075. def from_string(self, s: str) -> t.Any:
  2076. for trait_type in self.trait_types:
  2077. try:
  2078. v = trait_type.from_string(s)
  2079. return trait_type.validate(None, v)
  2080. except (TraitError, ValueError):
  2081. continue
  2082. return super().from_string(s)
  2083. # -----------------------------------------------------------------------------
  2084. # Basic TraitTypes implementations/subclasses
  2085. # -----------------------------------------------------------------------------
  2086. class Any(TraitType[t.Optional[t.Any], t.Optional[t.Any]]):
  2087. """A trait which allows any value."""
  2088. if t.TYPE_CHECKING:
  2089. @t.overload
  2090. def __init__(
  2091. self: Any,
  2092. default_value: t.Any = ...,
  2093. *,
  2094. allow_none: Literal[False],
  2095. read_only: bool | None = ...,
  2096. help: str | None = ...,
  2097. config: t.Any | None = ...,
  2098. **kwargs: t.Any,
  2099. ) -> None:
  2100. ...
  2101. @t.overload
  2102. def __init__(
  2103. self: Any,
  2104. default_value: t.Any = ...,
  2105. *,
  2106. allow_none: Literal[True],
  2107. read_only: bool | None = ...,
  2108. help: str | None = ...,
  2109. config: t.Any | None = ...,
  2110. **kwargs: t.Any,
  2111. ) -> None:
  2112. ...
  2113. @t.overload
  2114. def __init__(
  2115. self: Any,
  2116. default_value: t.Any = ...,
  2117. *,
  2118. allow_none: Literal[True, False] = ...,
  2119. help: str | None = ...,
  2120. read_only: bool | None = False,
  2121. config: t.Any = None,
  2122. **kwargs: t.Any,
  2123. ) -> None:
  2124. ...
  2125. def __init__(
  2126. self: Any,
  2127. default_value: t.Any = ...,
  2128. *,
  2129. allow_none: bool = False,
  2130. help: str | None = "",
  2131. read_only: bool | None = False,
  2132. config: t.Any = None,
  2133. **kwargs: t.Any,
  2134. ) -> None:
  2135. ...
  2136. @t.overload
  2137. def __get__(self, obj: None, cls: type[t.Any]) -> Any:
  2138. ...
  2139. @t.overload
  2140. def __get__(self, obj: t.Any, cls: type[t.Any]) -> t.Any:
  2141. ...
  2142. def __get__(self, obj: t.Any | None, cls: type[t.Any]) -> t.Any | Any:
  2143. ...
  2144. default_value: t.Any | None = None
  2145. allow_none = True
  2146. info_text = "any value"
  2147. def subclass_init(self, cls: type[t.Any]) -> None:
  2148. pass # fully opt out of instance_init
  2149. def _validate_bounds(
  2150. trait: Int[t.Any, t.Any] | Float[t.Any, t.Any], obj: t.Any, value: t.Any
  2151. ) -> t.Any:
  2152. """
  2153. Validate that a number to be applied to a trait is between bounds.
  2154. If value is not between min_bound and max_bound, this raises a
  2155. TraitError with an error message appropriate for this trait.
  2156. """
  2157. if trait.min is not None and value < trait.min:
  2158. raise TraitError(
  2159. f"The value of the '{trait.name}' trait of {class_of(obj)} instance should "
  2160. f"not be less than {trait.min}, but a value of {value} was "
  2161. "specified"
  2162. )
  2163. if trait.max is not None and value > trait.max:
  2164. raise TraitError(
  2165. f"The value of the '{trait.name}' trait of {class_of(obj)} instance should "
  2166. f"not be greater than {trait.max}, but a value of {value} was "
  2167. "specified"
  2168. )
  2169. return value
  2170. # I = t.TypeVar('I', t.Optional[int], int)
  2171. class Int(TraitType[G, S]):
  2172. """An int trait."""
  2173. default_value = 0
  2174. info_text = "an int"
  2175. @t.overload
  2176. def __init__(
  2177. self: Int[int, int],
  2178. default_value: int | Sentinel = ...,
  2179. allow_none: Literal[False] = ...,
  2180. read_only: bool | None = ...,
  2181. help: str | None = ...,
  2182. config: t.Any | None = ...,
  2183. **kwargs: t.Any,
  2184. ) -> None:
  2185. ...
  2186. @t.overload
  2187. def __init__(
  2188. self: Int[int | None, int | None],
  2189. default_value: int | Sentinel | None = ...,
  2190. allow_none: Literal[True] = ...,
  2191. read_only: bool | None = ...,
  2192. help: str | None = ...,
  2193. config: t.Any | None = ...,
  2194. **kwargs: t.Any,
  2195. ) -> None:
  2196. ...
  2197. def __init__(
  2198. self,
  2199. default_value: t.Any = Undefined,
  2200. allow_none: bool = False,
  2201. read_only: bool | None = None,
  2202. help: str | None = None,
  2203. config: t.Any | None = None,
  2204. **kwargs: t.Any,
  2205. ) -> None:
  2206. self.min = kwargs.pop("min", None)
  2207. self.max = kwargs.pop("max", None)
  2208. super().__init__(
  2209. default_value=default_value,
  2210. allow_none=allow_none,
  2211. read_only=read_only,
  2212. help=help,
  2213. config=config,
  2214. **kwargs,
  2215. )
  2216. def validate(self, obj: t.Any, value: t.Any) -> G:
  2217. if not isinstance(value, int):
  2218. self.error(obj, value)
  2219. return t.cast(G, _validate_bounds(self, obj, value))
  2220. def from_string(self, s: str) -> G:
  2221. if self.allow_none and s == "None":
  2222. return t.cast(G, None)
  2223. return t.cast(G, int(s))
  2224. def subclass_init(self, cls: type[t.Any]) -> None:
  2225. pass # fully opt out of instance_init
  2226. class CInt(Int[G, S]):
  2227. """A casting version of the int trait."""
  2228. if t.TYPE_CHECKING:
  2229. @t.overload
  2230. def __init__(
  2231. self: CInt[int, t.Any],
  2232. default_value: t.Any | Sentinel = ...,
  2233. allow_none: Literal[False] = ...,
  2234. read_only: bool | None = ...,
  2235. help: str | None = ...,
  2236. config: t.Any | None = ...,
  2237. **kwargs: t.Any,
  2238. ) -> None:
  2239. ...
  2240. @t.overload
  2241. def __init__(
  2242. self: CInt[int | None, t.Any],
  2243. default_value: t.Any | Sentinel | None = ...,
  2244. allow_none: Literal[True] = ...,
  2245. read_only: bool | None = ...,
  2246. help: str | None = ...,
  2247. config: t.Any | None = ...,
  2248. **kwargs: t.Any,
  2249. ) -> None:
  2250. ...
  2251. def __init__(
  2252. self: CInt[int | None, t.Any],
  2253. default_value: t.Any | Sentinel | None = ...,
  2254. allow_none: bool = ...,
  2255. read_only: bool | None = ...,
  2256. help: str | None = ...,
  2257. config: t.Any | None = ...,
  2258. **kwargs: t.Any,
  2259. ) -> None:
  2260. ...
  2261. def validate(self, obj: t.Any, value: t.Any) -> G:
  2262. try:
  2263. value = int(value)
  2264. except Exception:
  2265. self.error(obj, value)
  2266. return t.cast(G, _validate_bounds(self, obj, value))
  2267. Long, CLong = Int, CInt
  2268. Integer = Int
  2269. class Float(TraitType[G, S]):
  2270. """A float trait."""
  2271. default_value = 0.0
  2272. info_text = "a float"
  2273. @t.overload
  2274. def __init__(
  2275. self: Float[float, int | float],
  2276. default_value: float | Sentinel = ...,
  2277. allow_none: Literal[False] = ...,
  2278. read_only: bool | None = ...,
  2279. help: str | None = ...,
  2280. config: t.Any | None = ...,
  2281. **kwargs: t.Any,
  2282. ) -> None:
  2283. ...
  2284. @t.overload
  2285. def __init__(
  2286. self: Float[int | None, int | float | None],
  2287. default_value: float | Sentinel | None = ...,
  2288. allow_none: Literal[True] = ...,
  2289. read_only: bool | None = ...,
  2290. help: str | None = ...,
  2291. config: t.Any | None = ...,
  2292. **kwargs: t.Any,
  2293. ) -> None:
  2294. ...
  2295. def __init__(
  2296. self: Float[int | None, int | float | None],
  2297. default_value: float | Sentinel | None = Undefined,
  2298. allow_none: bool = False,
  2299. read_only: bool | None = False,
  2300. help: str | None = None,
  2301. config: t.Any | None = None,
  2302. **kwargs: t.Any,
  2303. ) -> None:
  2304. self.min = kwargs.pop("min", -float("inf"))
  2305. self.max = kwargs.pop("max", float("inf"))
  2306. super().__init__(
  2307. default_value=default_value,
  2308. allow_none=allow_none,
  2309. read_only=read_only,
  2310. help=help,
  2311. config=config,
  2312. **kwargs,
  2313. )
  2314. def validate(self, obj: t.Any, value: t.Any) -> G:
  2315. if isinstance(value, int):
  2316. value = float(value)
  2317. if not isinstance(value, float):
  2318. self.error(obj, value)
  2319. return t.cast(G, _validate_bounds(self, obj, value))
  2320. def from_string(self, s: str) -> G:
  2321. if self.allow_none and s == "None":
  2322. return t.cast(G, None)
  2323. return t.cast(G, float(s))
  2324. def subclass_init(self, cls: type[t.Any]) -> None:
  2325. pass # fully opt out of instance_init
  2326. class CFloat(Float[G, S]):
  2327. """A casting version of the float trait."""
  2328. if t.TYPE_CHECKING:
  2329. @t.overload
  2330. def __init__(
  2331. self: CFloat[float, t.Any],
  2332. default_value: t.Any = ...,
  2333. allow_none: Literal[False] = ...,
  2334. read_only: bool | None = ...,
  2335. help: str | None = ...,
  2336. config: t.Any | None = ...,
  2337. **kwargs: t.Any,
  2338. ) -> None:
  2339. ...
  2340. @t.overload
  2341. def __init__(
  2342. self: CFloat[float | None, t.Any],
  2343. default_value: t.Any = ...,
  2344. allow_none: Literal[True] = ...,
  2345. read_only: bool | None = ...,
  2346. help: str | None = ...,
  2347. config: t.Any | None = ...,
  2348. **kwargs: t.Any,
  2349. ) -> None:
  2350. ...
  2351. def __init__(
  2352. self: CFloat[float | None, t.Any],
  2353. default_value: t.Any = ...,
  2354. allow_none: bool = ...,
  2355. read_only: bool | None = ...,
  2356. help: str | None = ...,
  2357. config: t.Any | None = ...,
  2358. **kwargs: t.Any,
  2359. ) -> None:
  2360. ...
  2361. def validate(self, obj: t.Any, value: t.Any) -> G:
  2362. try:
  2363. value = float(value)
  2364. except Exception:
  2365. self.error(obj, value)
  2366. return t.cast(G, _validate_bounds(self, obj, value))
  2367. class Complex(TraitType[complex, t.Union[complex, float, int]]):
  2368. """A trait for complex numbers."""
  2369. default_value = 0.0 + 0.0j
  2370. info_text = "a complex number"
  2371. def validate(self, obj: t.Any, value: t.Any) -> complex | None:
  2372. if isinstance(value, complex):
  2373. return value
  2374. if isinstance(value, (float, int)):
  2375. return complex(value)
  2376. self.error(obj, value)
  2377. def from_string(self, s: str) -> complex | None:
  2378. if self.allow_none and s == "None":
  2379. return None
  2380. return complex(s)
  2381. def subclass_init(self, cls: type[t.Any]) -> None:
  2382. pass # fully opt out of instance_init
  2383. class CComplex(Complex, TraitType[complex, t.Any]):
  2384. """A casting version of the complex number trait."""
  2385. def validate(self, obj: t.Any, value: t.Any) -> complex | None:
  2386. try:
  2387. return complex(value)
  2388. except Exception:
  2389. self.error(obj, value)
  2390. # We should always be explicit about whether we're using bytes or unicode, both
  2391. # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
  2392. # we don't have a Str type.
  2393. class Bytes(TraitType[bytes, bytes]):
  2394. """A trait for byte strings."""
  2395. default_value = b""
  2396. info_text = "a bytes object"
  2397. def validate(self, obj: t.Any, value: t.Any) -> bytes | None:
  2398. if isinstance(value, bytes):
  2399. return value
  2400. self.error(obj, value)
  2401. def from_string(self, s: str) -> bytes | None:
  2402. if self.allow_none and s == "None":
  2403. return None
  2404. if len(s) >= 3:
  2405. # handle deprecated b"string"
  2406. for quote in ('"', "'"):
  2407. if s[:2] == f"b{quote}" and s[-1] == quote:
  2408. old_s = s
  2409. s = s[2:-1]
  2410. warn(
  2411. "Supporting extra quotes around Bytes is deprecated in traitlets 5.0. "
  2412. f"Use {s!r} instead of {old_s!r}.",
  2413. DeprecationWarning,
  2414. stacklevel=2,
  2415. )
  2416. break
  2417. return s.encode("utf8")
  2418. def subclass_init(self, cls: type[t.Any]) -> None:
  2419. pass # fully opt out of instance_init
  2420. class CBytes(Bytes, TraitType[bytes, t.Any]):
  2421. """A casting version of the byte string trait."""
  2422. def validate(self, obj: t.Any, value: t.Any) -> bytes | None:
  2423. try:
  2424. return bytes(value)
  2425. except Exception:
  2426. self.error(obj, value)
  2427. class Unicode(TraitType[G, S]):
  2428. """A trait for unicode strings."""
  2429. default_value = ""
  2430. info_text = "a unicode string"
  2431. if t.TYPE_CHECKING:
  2432. @t.overload
  2433. def __init__(
  2434. self: Unicode[str, str | bytes],
  2435. default_value: str | Sentinel = ...,
  2436. allow_none: Literal[False] = ...,
  2437. read_only: bool | None = ...,
  2438. help: str | None = ...,
  2439. config: t.Any = ...,
  2440. **kwargs: t.Any,
  2441. ) -> None:
  2442. ...
  2443. @t.overload
  2444. def __init__(
  2445. self: Unicode[str | None, str | bytes | None],
  2446. default_value: str | Sentinel | None = ...,
  2447. allow_none: Literal[True] = ...,
  2448. read_only: bool | None = ...,
  2449. help: str | None = ...,
  2450. config: t.Any = ...,
  2451. **kwargs: t.Any,
  2452. ) -> None:
  2453. ...
  2454. def __init__(
  2455. self: Unicode[str | None, str | bytes | None],
  2456. default_value: str | Sentinel | None = ...,
  2457. allow_none: bool = ...,
  2458. read_only: bool | None = ...,
  2459. help: str | None = ...,
  2460. config: t.Any = ...,
  2461. **kwargs: t.Any,
  2462. ) -> None:
  2463. ...
  2464. def validate(self, obj: t.Any, value: t.Any) -> G:
  2465. if isinstance(value, str):
  2466. return t.cast(G, value)
  2467. if isinstance(value, bytes):
  2468. try:
  2469. return t.cast(G, value.decode("ascii", "strict"))
  2470. except UnicodeDecodeError as e:
  2471. msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
  2472. raise TraitError(msg.format(value, self.name, class_of(obj))) from e
  2473. self.error(obj, value)
  2474. def from_string(self, s: str) -> G:
  2475. if self.allow_none and s == "None":
  2476. return t.cast(G, None)
  2477. s = os.path.expanduser(s)
  2478. if len(s) >= 2:
  2479. # handle deprecated "1"
  2480. for c in ('"', "'"):
  2481. if s[0] == s[-1] == c:
  2482. old_s = s
  2483. s = s[1:-1]
  2484. warn(
  2485. "Supporting extra quotes around strings is deprecated in traitlets 5.0. "
  2486. f"You can use {s!r} instead of {old_s!r} if you require traitlets >=5.",
  2487. DeprecationWarning,
  2488. stacklevel=2,
  2489. )
  2490. return t.cast(G, s)
  2491. def subclass_init(self, cls: type[t.Any]) -> None:
  2492. pass # fully opt out of instance_init
  2493. class CUnicode(Unicode[G, S], TraitType[str, t.Any]):
  2494. """A casting version of the unicode trait."""
  2495. if t.TYPE_CHECKING:
  2496. @t.overload
  2497. def __init__(
  2498. self: CUnicode[str, t.Any],
  2499. default_value: str | Sentinel = ...,
  2500. allow_none: Literal[False] = ...,
  2501. read_only: bool | None = ...,
  2502. help: str | None = ...,
  2503. config: t.Any = ...,
  2504. **kwargs: t.Any,
  2505. ) -> None:
  2506. ...
  2507. @t.overload
  2508. def __init__(
  2509. self: CUnicode[str | None, t.Any],
  2510. default_value: str | Sentinel | None = ...,
  2511. allow_none: Literal[True] = ...,
  2512. read_only: bool | None = ...,
  2513. help: str | None = ...,
  2514. config: t.Any = ...,
  2515. **kwargs: t.Any,
  2516. ) -> None:
  2517. ...
  2518. def __init__(
  2519. self: CUnicode[str | None, t.Any],
  2520. default_value: str | Sentinel | None = ...,
  2521. allow_none: bool = ...,
  2522. read_only: bool | None = ...,
  2523. help: str | None = ...,
  2524. config: t.Any = ...,
  2525. **kwargs: t.Any,
  2526. ) -> None:
  2527. ...
  2528. def validate(self, obj: t.Any, value: t.Any) -> G:
  2529. try:
  2530. return t.cast(G, str(value))
  2531. except Exception:
  2532. self.error(obj, value)
  2533. class ObjectName(TraitType[str, str]):
  2534. """A string holding a valid object name in this version of Python.
  2535. This does not check that the name exists in any scope."""
  2536. info_text = "a valid object identifier in Python"
  2537. coerce_str = staticmethod(lambda _, s: s)
  2538. def validate(self, obj: t.Any, value: t.Any) -> str:
  2539. value = self.coerce_str(obj, value)
  2540. if isinstance(value, str) and isidentifier(value):
  2541. return value
  2542. self.error(obj, value)
  2543. def from_string(self, s: str) -> str | None:
  2544. if self.allow_none and s == "None":
  2545. return None
  2546. return s
  2547. class DottedObjectName(ObjectName):
  2548. """A string holding a valid dotted object name in Python, such as A.b3._c"""
  2549. def validate(self, obj: t.Any, value: t.Any) -> str:
  2550. value = self.coerce_str(obj, value)
  2551. if isinstance(value, str) and all(isidentifier(a) for a in value.split(".")):
  2552. return value
  2553. self.error(obj, value)
  2554. class Bool(TraitType[G, S]):
  2555. """A boolean (True, False) trait."""
  2556. default_value = False
  2557. info_text = "a boolean"
  2558. if t.TYPE_CHECKING:
  2559. @t.overload
  2560. def __init__(
  2561. self: Bool[bool, bool | int],
  2562. default_value: bool | Sentinel = ...,
  2563. allow_none: Literal[False] = ...,
  2564. read_only: bool | None = ...,
  2565. help: str | None = ...,
  2566. config: t.Any = ...,
  2567. **kwargs: t.Any,
  2568. ) -> None:
  2569. ...
  2570. @t.overload
  2571. def __init__(
  2572. self: Bool[bool | None, bool | int | None],
  2573. default_value: bool | Sentinel | None = ...,
  2574. allow_none: Literal[True] = ...,
  2575. read_only: bool | None = ...,
  2576. help: str | None = ...,
  2577. config: t.Any = ...,
  2578. **kwargs: t.Any,
  2579. ) -> None:
  2580. ...
  2581. def __init__(
  2582. self: Bool[bool | None, bool | int | None],
  2583. default_value: bool | Sentinel | None = ...,
  2584. allow_none: bool = ...,
  2585. read_only: bool | None = ...,
  2586. help: str | None = ...,
  2587. config: t.Any = ...,
  2588. **kwargs: t.Any,
  2589. ) -> None:
  2590. ...
  2591. def validate(self, obj: t.Any, value: t.Any) -> G:
  2592. if isinstance(value, bool):
  2593. return t.cast(G, value)
  2594. elif isinstance(value, int):
  2595. if value == 1:
  2596. return t.cast(G, True)
  2597. elif value == 0:
  2598. return t.cast(G, False)
  2599. self.error(obj, value)
  2600. def from_string(self, s: str) -> G:
  2601. if self.allow_none and s == "None":
  2602. return t.cast(G, None)
  2603. s = s.lower()
  2604. if s in {"true", "1"}:
  2605. return t.cast(G, True)
  2606. elif s in {"false", "0"}:
  2607. return t.cast(G, False)
  2608. else:
  2609. raise ValueError("%r is not 1, 0, true, or false")
  2610. def subclass_init(self, cls: type[t.Any]) -> None:
  2611. pass # fully opt out of instance_init
  2612. def argcompleter(self, **kwargs: t.Any) -> list[str]:
  2613. """Completion hints for argcomplete"""
  2614. completions = ["true", "1", "false", "0"]
  2615. if self.allow_none:
  2616. completions.append("None")
  2617. return completions
  2618. class CBool(Bool[G, S]):
  2619. """A casting version of the boolean trait."""
  2620. if t.TYPE_CHECKING:
  2621. @t.overload
  2622. def __init__(
  2623. self: CBool[bool, t.Any],
  2624. default_value: bool | Sentinel = ...,
  2625. allow_none: Literal[False] = ...,
  2626. read_only: bool | None = ...,
  2627. help: str | None = ...,
  2628. config: t.Any = ...,
  2629. **kwargs: t.Any,
  2630. ) -> None:
  2631. ...
  2632. @t.overload
  2633. def __init__(
  2634. self: CBool[bool | None, t.Any],
  2635. default_value: bool | Sentinel | None = ...,
  2636. allow_none: Literal[True] = ...,
  2637. read_only: bool | None = ...,
  2638. help: str | None = ...,
  2639. config: t.Any = ...,
  2640. **kwargs: t.Any,
  2641. ) -> None:
  2642. ...
  2643. def __init__(
  2644. self: CBool[bool | None, t.Any],
  2645. default_value: bool | Sentinel | None = ...,
  2646. allow_none: bool = ...,
  2647. read_only: bool | None = ...,
  2648. help: str | None = ...,
  2649. config: t.Any = ...,
  2650. **kwargs: t.Any,
  2651. ) -> None:
  2652. ...
  2653. def validate(self, obj: t.Any, value: t.Any) -> G:
  2654. try:
  2655. return t.cast(G, bool(value))
  2656. except Exception:
  2657. self.error(obj, value)
  2658. class Enum(TraitType[G, G]):
  2659. """An enum whose value must be in a given sequence."""
  2660. if t.TYPE_CHECKING:
  2661. @t.overload
  2662. def __init__(
  2663. self: Enum[G],
  2664. values: t.Sequence[G],
  2665. default_value: G | Sentinel = ...,
  2666. allow_none: Literal[False] = ...,
  2667. read_only: bool | None = ...,
  2668. help: str | None = ...,
  2669. config: t.Any = ...,
  2670. **kwargs: t.Any,
  2671. ) -> None:
  2672. ...
  2673. @t.overload
  2674. def __init__(
  2675. self: Enum[G | None],
  2676. values: t.Sequence[G] | None,
  2677. default_value: G | Sentinel | None = ...,
  2678. allow_none: Literal[True] = ...,
  2679. read_only: bool | None = ...,
  2680. help: str | None = ...,
  2681. config: t.Any = ...,
  2682. **kwargs: t.Any,
  2683. ) -> None:
  2684. ...
  2685. def __init__(
  2686. self: Enum[G],
  2687. values: t.Sequence[G] | None,
  2688. default_value: G | Sentinel | None = Undefined,
  2689. allow_none: bool = False,
  2690. read_only: bool | None = None,
  2691. help: str | None = None,
  2692. config: t.Any = None,
  2693. **kwargs: t.Any,
  2694. ) -> None:
  2695. self.values = values
  2696. if allow_none is True and default_value is Undefined:
  2697. default_value = None
  2698. kwargs["allow_none"] = allow_none
  2699. kwargs["read_only"] = read_only
  2700. kwargs["help"] = help
  2701. kwargs["config"] = config
  2702. super().__init__(default_value, **kwargs)
  2703. def validate(self, obj: t.Any, value: t.Any) -> G:
  2704. if self.values and value in self.values:
  2705. return t.cast(G, value)
  2706. self.error(obj, value)
  2707. def _choices_str(self, as_rst: bool = False) -> str:
  2708. """Returns a description of the trait choices (not none)."""
  2709. choices = self.values or []
  2710. if as_rst:
  2711. choice_str = "|".join("``%r``" % x for x in choices)
  2712. else:
  2713. choice_str = repr(list(choices))
  2714. return choice_str
  2715. def _info(self, as_rst: bool = False) -> str:
  2716. """Returns a description of the trait."""
  2717. none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
  2718. return f"any of {self._choices_str(as_rst)}{none}"
  2719. def info(self) -> str:
  2720. return self._info(as_rst=False)
  2721. def info_rst(self) -> str:
  2722. return self._info(as_rst=True)
  2723. def from_string(self, s: str) -> G:
  2724. try:
  2725. return self.validate(None, s)
  2726. except TraitError:
  2727. return t.cast(G, _safe_literal_eval(s))
  2728. def subclass_init(self, cls: type[t.Any]) -> None:
  2729. pass # fully opt out of instance_init
  2730. def argcompleter(self, **kwargs: t.Any) -> list[str]:
  2731. """Completion hints for argcomplete"""
  2732. return [str(v) for v in self.values or []]
  2733. class CaselessStrEnum(Enum[G]):
  2734. """An enum of strings where the case should be ignored."""
  2735. def __init__(
  2736. self: CaselessStrEnum[t.Any],
  2737. values: t.Any,
  2738. default_value: t.Any = Undefined,
  2739. **kwargs: t.Any,
  2740. ) -> None:
  2741. super().__init__(values, default_value=default_value, **kwargs)
  2742. def validate(self, obj: t.Any, value: t.Any) -> G:
  2743. if not isinstance(value, str):
  2744. self.error(obj, value)
  2745. for v in self.values or []:
  2746. assert isinstance(v, str)
  2747. if v.lower() == value.lower():
  2748. return t.cast(G, v)
  2749. self.error(obj, value)
  2750. def _info(self, as_rst: bool = False) -> str:
  2751. """Returns a description of the trait."""
  2752. none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
  2753. return f"any of {self._choices_str(as_rst)} (case-insensitive){none}"
  2754. def info(self) -> str:
  2755. return self._info(as_rst=False)
  2756. def info_rst(self) -> str:
  2757. return self._info(as_rst=True)
  2758. class FuzzyEnum(Enum[G]):
  2759. """An case-ignoring enum matching choices by unique prefixes/substrings."""
  2760. case_sensitive = False
  2761. #: If True, choices match anywhere in the string, otherwise match prefixes.
  2762. substring_matching = False
  2763. def __init__(
  2764. self: FuzzyEnum[t.Any],
  2765. values: t.Any,
  2766. default_value: t.Any = Undefined,
  2767. case_sensitive: bool = False,
  2768. substring_matching: bool = False,
  2769. **kwargs: t.Any,
  2770. ) -> None:
  2771. self.case_sensitive = case_sensitive
  2772. self.substring_matching = substring_matching
  2773. super().__init__(values, default_value=default_value, **kwargs)
  2774. def validate(self, obj: t.Any, value: t.Any) -> G:
  2775. if not isinstance(value, str):
  2776. self.error(obj, value)
  2777. conv_func = (lambda c: c) if self.case_sensitive else lambda c: c.lower()
  2778. substring_matching = self.substring_matching
  2779. match_func = (lambda v, c: v in c) if substring_matching else (lambda v, c: c.startswith(v))
  2780. value = conv_func(value) # type:ignore[no-untyped-call]
  2781. choices = self.values or []
  2782. matches = [match_func(value, conv_func(c)) for c in choices] # type:ignore[no-untyped-call]
  2783. if sum(matches) == 1:
  2784. for v, m in zip(choices, matches):
  2785. if m:
  2786. return v
  2787. self.error(obj, value)
  2788. def _info(self, as_rst: bool = False) -> str:
  2789. """Returns a description of the trait."""
  2790. none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
  2791. case = "sensitive" if self.case_sensitive else "insensitive"
  2792. substr = "substring" if self.substring_matching else "prefix"
  2793. return f"any case-{case} {substr} of {self._choices_str(as_rst)}{none}"
  2794. def info(self) -> str:
  2795. return self._info(as_rst=False)
  2796. def info_rst(self) -> str:
  2797. return self._info(as_rst=True)
  2798. class Container(Instance[T]):
  2799. """An instance of a container (list, set, etc.)
  2800. To be subclassed by overriding klass.
  2801. """
  2802. klass: type[T] | None = None
  2803. _cast_types: t.Any = ()
  2804. _valid_defaults = SequenceTypes
  2805. _trait: t.Any = None
  2806. _literal_from_string_pairs: t.Any = ("[]", "()")
  2807. @t.overload
  2808. def __init__(
  2809. self: Container[T],
  2810. *,
  2811. allow_none: Literal[False],
  2812. read_only: bool | None = ...,
  2813. help: str | None = ...,
  2814. config: t.Any | None = ...,
  2815. **kwargs: t.Any,
  2816. ) -> None:
  2817. ...
  2818. @t.overload
  2819. def __init__(
  2820. self: Container[T | None],
  2821. *,
  2822. allow_none: Literal[True],
  2823. read_only: bool | None = ...,
  2824. help: str | None = ...,
  2825. config: t.Any | None = ...,
  2826. **kwargs: t.Any,
  2827. ) -> None:
  2828. ...
  2829. @t.overload
  2830. def __init__(
  2831. self: Container[T],
  2832. *,
  2833. trait: t.Any = ...,
  2834. default_value: t.Any = ...,
  2835. help: str = ...,
  2836. read_only: bool = ...,
  2837. config: t.Any = ...,
  2838. **kwargs: t.Any,
  2839. ) -> None:
  2840. ...
  2841. def __init__(
  2842. self,
  2843. trait: t.Any | None = None,
  2844. default_value: t.Any = Undefined,
  2845. help: str | None = None,
  2846. read_only: bool | None = None,
  2847. config: t.Any | None = None,
  2848. **kwargs: t.Any,
  2849. ) -> None:
  2850. """Create a container trait type from a list, set, or tuple.
  2851. The default value is created by doing ``List(default_value)``,
  2852. which creates a copy of the ``default_value``.
  2853. ``trait`` can be specified, which restricts the type of elements
  2854. in the container to that TraitType.
  2855. If only one arg is given and it is not a Trait, it is taken as
  2856. ``default_value``:
  2857. ``c = List([1, 2, 3])``
  2858. Parameters
  2859. ----------
  2860. trait : TraitType [ optional ]
  2861. the type for restricting the contents of the Container. If unspecified,
  2862. types are not checked.
  2863. default_value : SequenceType [ optional ]
  2864. The default value for the Trait. Must be list/tuple/set, and
  2865. will be cast to the container type.
  2866. allow_none : bool [ default False ]
  2867. Whether to allow the value to be None
  2868. **kwargs : any
  2869. further keys for extensions to the Trait (e.g. config)
  2870. """
  2871. # allow List([values]):
  2872. if trait is not None and default_value is Undefined and not is_trait(trait):
  2873. default_value = trait
  2874. trait = None
  2875. if default_value is None and not kwargs.get("allow_none", False):
  2876. # improve backward-compatibility for possible subclasses
  2877. # specifying default_value=None as default,
  2878. # keeping 'unspecified' behavior (i.e. empty container)
  2879. warn(
  2880. f"Specifying {self.__class__.__name__}(default_value=None)"
  2881. " for no default is deprecated in traitlets 5.0.5."
  2882. " Use default_value=Undefined",
  2883. DeprecationWarning,
  2884. stacklevel=2,
  2885. )
  2886. default_value = Undefined
  2887. if default_value is Undefined:
  2888. args: t.Any = ()
  2889. elif default_value is None:
  2890. # default_value back on kwargs for super() to handle
  2891. args = ()
  2892. kwargs["default_value"] = None
  2893. elif isinstance(default_value, self._valid_defaults):
  2894. args = (default_value,)
  2895. else:
  2896. raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
  2897. if is_trait(trait):
  2898. if isinstance(trait, type):
  2899. warn(
  2900. "Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
  2901. " Passing types is deprecated in traitlets 4.1.",
  2902. DeprecationWarning,
  2903. stacklevel=3,
  2904. )
  2905. self._trait = trait() if isinstance(trait, type) else trait
  2906. elif trait is not None:
  2907. raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
  2908. super().__init__(
  2909. klass=self.klass, args=args, help=help, read_only=read_only, config=config, **kwargs
  2910. )
  2911. def validate(self, obj: t.Any, value: t.Any) -> T | None:
  2912. if isinstance(value, self._cast_types):
  2913. assert self.klass is not None
  2914. value = self.klass(value) # type:ignore[call-arg]
  2915. value = super().validate(obj, value)
  2916. if value is None:
  2917. return value
  2918. value = self.validate_elements(obj, value)
  2919. return t.cast(T, value)
  2920. def validate_elements(self, obj: t.Any, value: t.Any) -> T | None:
  2921. validated = []
  2922. if self._trait is None or isinstance(self._trait, Any):
  2923. return t.cast(T, value)
  2924. for v in value:
  2925. try:
  2926. v = self._trait._validate(obj, v)
  2927. except TraitError as error:
  2928. self.error(obj, v, error)
  2929. else:
  2930. validated.append(v)
  2931. assert self.klass is not None
  2932. return self.klass(validated) # type:ignore[call-arg]
  2933. def class_init(self, cls: type[t.Any], name: str | None) -> None:
  2934. if isinstance(self._trait, TraitType):
  2935. self._trait.class_init(cls, None)
  2936. super().class_init(cls, name)
  2937. def subclass_init(self, cls: type[t.Any]) -> None:
  2938. if isinstance(self._trait, TraitType):
  2939. self._trait.subclass_init(cls)
  2940. # explicitly not calling super().subclass_init(cls)
  2941. # to opt out of instance_init
  2942. def from_string(self, s: str) -> T | None:
  2943. """Load value from a single string"""
  2944. if not isinstance(s, str):
  2945. raise TraitError(f"Expected string, got {s!r}")
  2946. try:
  2947. test = literal_eval(s)
  2948. except Exception:
  2949. test = None
  2950. return self.validate(None, test)
  2951. def from_string_list(self, s_list: list[str]) -> T | None:
  2952. """Return the value from a list of config strings
  2953. This is where we parse CLI configuration
  2954. """
  2955. assert self.klass is not None
  2956. if len(s_list) == 1:
  2957. # check for deprecated --Class.trait="['a', 'b', 'c']"
  2958. r = s_list[0]
  2959. if r == "None" and self.allow_none:
  2960. return None
  2961. if len(r) >= 2 and any(
  2962. r.startswith(start) and r.endswith(end)
  2963. for start, end in self._literal_from_string_pairs
  2964. ):
  2965. if self.this_class:
  2966. clsname = self.this_class.__name__ + "."
  2967. else:
  2968. clsname = ""
  2969. assert self.name is not None
  2970. warn(
  2971. "--{0}={1} for containers is deprecated in traitlets 5.0. "
  2972. "You can pass `--{0} item` ... multiple times to add items to a list.".format(
  2973. clsname + self.name, r
  2974. ),
  2975. DeprecationWarning,
  2976. stacklevel=2,
  2977. )
  2978. return self.klass(literal_eval(r)) # type:ignore[call-arg]
  2979. sig = inspect.signature(self.item_from_string)
  2980. if "index" in sig.parameters:
  2981. item_from_string = self.item_from_string
  2982. else:
  2983. # backward-compat: allow item_from_string to ignore index arg
  2984. def item_from_string(s: str, index: int | None = None) -> T | str:
  2985. return t.cast(T, self.item_from_string(s))
  2986. return self.klass( # type:ignore[call-arg]
  2987. [item_from_string(s, index=idx) for idx, s in enumerate(s_list)]
  2988. )
  2989. def item_from_string(self, s: str, index: int | None = None) -> T | str:
  2990. """Cast a single item from a string
  2991. Evaluated when parsing CLI configuration from a string
  2992. """
  2993. if self._trait:
  2994. return t.cast(T, self._trait.from_string(s))
  2995. else:
  2996. return s
  2997. class List(Container[t.List[T]]):
  2998. """An instance of a Python list."""
  2999. klass = list # type:ignore[assignment]
  3000. _cast_types: t.Any = (tuple,)
  3001. def __init__(
  3002. self,
  3003. trait: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None = None,
  3004. default_value: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | None = Undefined,
  3005. minlen: int = 0,
  3006. maxlen: int = sys.maxsize,
  3007. **kwargs: t.Any,
  3008. ) -> None:
  3009. """Create a List trait type from a list, set, or tuple.
  3010. The default value is created by doing ``list(default_value)``,
  3011. which creates a copy of the ``default_value``.
  3012. ``trait`` can be specified, which restricts the type of elements
  3013. in the container to that TraitType.
  3014. If only one arg is given and it is not a Trait, it is taken as
  3015. ``default_value``:
  3016. ``c = List([1, 2, 3])``
  3017. Parameters
  3018. ----------
  3019. trait : TraitType [ optional ]
  3020. the type for restricting the contents of the Container.
  3021. If unspecified, types are not checked.
  3022. default_value : SequenceType [ optional ]
  3023. The default value for the Trait. Must be list/tuple/set, and
  3024. will be cast to the container type.
  3025. minlen : Int [ default 0 ]
  3026. The minimum length of the input list
  3027. maxlen : Int [ default sys.maxsize ]
  3028. The maximum length of the input list
  3029. """
  3030. self._maxlen = maxlen
  3031. self._minlen = minlen
  3032. super().__init__(trait=trait, default_value=default_value, **kwargs)
  3033. def length_error(self, obj: t.Any, value: t.Any) -> None:
  3034. e = (
  3035. "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified."
  3036. % (self.name, class_of(obj), self._minlen, self._maxlen, value)
  3037. )
  3038. raise TraitError(e)
  3039. def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
  3040. length = len(value)
  3041. if length < self._minlen or length > self._maxlen:
  3042. self.length_error(obj, value)
  3043. return super().validate_elements(obj, value)
  3044. def set(self, obj: t.Any, value: t.Any) -> None:
  3045. if isinstance(value, str):
  3046. return super().set(obj, [value]) # type:ignore[list-item]
  3047. else:
  3048. return super().set(obj, value)
  3049. class Set(Container[t.Set[t.Any]]):
  3050. """An instance of a Python set."""
  3051. klass = set
  3052. _cast_types = (tuple, list)
  3053. _literal_from_string_pairs = ("[]", "()", "{}")
  3054. # Redefine __init__ just to make the docstring more accurate.
  3055. def __init__(
  3056. self,
  3057. trait: t.Any = None,
  3058. default_value: t.Any = Undefined,
  3059. minlen: int = 0,
  3060. maxlen: int = sys.maxsize,
  3061. **kwargs: t.Any,
  3062. ) -> None:
  3063. """Create a Set trait type from a list, set, or tuple.
  3064. The default value is created by doing ``set(default_value)``,
  3065. which creates a copy of the ``default_value``.
  3066. ``trait`` can be specified, which restricts the type of elements
  3067. in the container to that TraitType.
  3068. If only one arg is given and it is not a Trait, it is taken as
  3069. ``default_value``:
  3070. ``c = Set({1, 2, 3})``
  3071. Parameters
  3072. ----------
  3073. trait : TraitType [ optional ]
  3074. the type for restricting the contents of the Container.
  3075. If unspecified, types are not checked.
  3076. default_value : SequenceType [ optional ]
  3077. The default value for the Trait. Must be list/tuple/set, and
  3078. will be cast to the container type.
  3079. minlen : Int [ default 0 ]
  3080. The minimum length of the input list
  3081. maxlen : Int [ default sys.maxsize ]
  3082. The maximum length of the input list
  3083. """
  3084. self._maxlen = maxlen
  3085. self._minlen = minlen
  3086. super().__init__(trait=trait, default_value=default_value, **kwargs)
  3087. def length_error(self, obj: t.Any, value: t.Any) -> None:
  3088. e = (
  3089. "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified."
  3090. % (self.name, class_of(obj), self._minlen, self._maxlen, value)
  3091. )
  3092. raise TraitError(e)
  3093. def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
  3094. length = len(value)
  3095. if length < self._minlen or length > self._maxlen:
  3096. self.length_error(obj, value)
  3097. return super().validate_elements(obj, value)
  3098. def set(self, obj: t.Any, value: t.Any) -> None:
  3099. if isinstance(value, str):
  3100. return super().set(obj, {value})
  3101. else:
  3102. return super().set(obj, value)
  3103. def default_value_repr(self) -> str:
  3104. # Ensure default value is sorted for a reproducible build
  3105. list_repr = repr(sorted(self.make_dynamic_default() or []))
  3106. if list_repr == "[]":
  3107. return "set()"
  3108. return "{" + list_repr[1:-1] + "}"
  3109. class Tuple(Container[t.Tuple[t.Any, ...]]):
  3110. """An instance of a Python tuple."""
  3111. klass = tuple
  3112. _cast_types = (list,)
  3113. def __init__(self, *traits: t.Any, **kwargs: t.Any) -> None:
  3114. """Create a tuple from a list, set, or tuple.
  3115. Create a fixed-type tuple with Traits:
  3116. ``t = Tuple(Int(), Str(), CStr())``
  3117. would be length 3, with Int,Str,CStr for each element.
  3118. If only one arg is given and it is not a Trait, it is taken as
  3119. default_value:
  3120. ``t = Tuple((1, 2, 3))``
  3121. Otherwise, ``default_value`` *must* be specified by keyword.
  3122. Parameters
  3123. ----------
  3124. *traits : TraitTypes [ optional ]
  3125. the types for restricting the contents of the Tuple. If unspecified,
  3126. types are not checked. If specified, then each positional argument
  3127. corresponds to an element of the tuple. Tuples defined with traits
  3128. are of fixed length.
  3129. default_value : SequenceType [ optional ]
  3130. The default value for the Tuple. Must be list/tuple/set, and
  3131. will be cast to a tuple. If ``traits`` are specified,
  3132. ``default_value`` must conform to the shape and type they specify.
  3133. **kwargs
  3134. Other kwargs passed to `Container`
  3135. """
  3136. default_value = kwargs.pop("default_value", Undefined)
  3137. # allow Tuple((values,)):
  3138. if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
  3139. default_value = traits[0]
  3140. traits = ()
  3141. if default_value is None and not kwargs.get("allow_none", False):
  3142. # improve backward-compatibility for possible subclasses
  3143. # specifying default_value=None as default,
  3144. # keeping 'unspecified' behavior (i.e. empty container)
  3145. warn(
  3146. f"Specifying {self.__class__.__name__}(default_value=None)"
  3147. " for no default is deprecated in traitlets 5.0.5."
  3148. " Use default_value=Undefined",
  3149. DeprecationWarning,
  3150. stacklevel=2,
  3151. )
  3152. default_value = Undefined
  3153. if default_value is Undefined:
  3154. args: t.Any = ()
  3155. elif default_value is None:
  3156. # default_value back on kwargs for super() to handle
  3157. args = ()
  3158. kwargs["default_value"] = None
  3159. elif isinstance(default_value, self._valid_defaults):
  3160. args = (default_value,)
  3161. else:
  3162. raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
  3163. self._traits = []
  3164. for trait in traits:
  3165. if isinstance(trait, type):
  3166. warn(
  3167. "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
  3168. " Passing types is deprecated in traitlets 4.1.",
  3169. DeprecationWarning,
  3170. stacklevel=2,
  3171. )
  3172. trait = trait()
  3173. self._traits.append(trait)
  3174. if self._traits and (default_value is None or default_value is Undefined):
  3175. # don't allow default to be an empty container if length is specified
  3176. args = None
  3177. super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
  3178. def item_from_string(self, s: str, index: int) -> t.Any: # type:ignore[override]
  3179. """Cast a single item from a string
  3180. Evaluated when parsing CLI configuration from a string
  3181. """
  3182. if not self._traits or index >= len(self._traits):
  3183. # return s instead of raising index error
  3184. # length errors will be raised later on validation
  3185. return s
  3186. return self._traits[index].from_string(s)
  3187. def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
  3188. if not self._traits:
  3189. # nothing to validate
  3190. return value
  3191. if len(value) != len(self._traits):
  3192. e = (
  3193. "The '%s' trait of %s instance requires %i elements, but a value of %s was specified."
  3194. % (self.name, class_of(obj), len(self._traits), repr_type(value))
  3195. )
  3196. raise TraitError(e)
  3197. validated = []
  3198. for trait, v in zip(self._traits, value):
  3199. try:
  3200. v = trait._validate(obj, v)
  3201. except TraitError as error:
  3202. self.error(obj, v, error)
  3203. else:
  3204. validated.append(v)
  3205. return tuple(validated)
  3206. def class_init(self, cls: type[t.Any], name: str | None) -> None:
  3207. for trait in self._traits:
  3208. if isinstance(trait, TraitType):
  3209. trait.class_init(cls, None)
  3210. super(Container, self).class_init(cls, name)
  3211. def subclass_init(self, cls: type[t.Any]) -> None:
  3212. for trait in self._traits:
  3213. if isinstance(trait, TraitType):
  3214. trait.subclass_init(cls)
  3215. # explicitly not calling super().subclass_init(cls)
  3216. # to opt out of instance_init
  3217. class Dict(Instance["dict[K, V]"]):
  3218. """An instance of a Python dict.
  3219. One or more traits can be passed to the constructor
  3220. to validate the keys and/or values of the dict.
  3221. If you need more detailed validation,
  3222. you may use a custom validator method.
  3223. .. versionchanged:: 5.0
  3224. Added key_trait for validating dict keys.
  3225. .. versionchanged:: 5.0
  3226. Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``.
  3227. """
  3228. _value_trait = None
  3229. _key_trait = None
  3230. def __init__(
  3231. self,
  3232. value_trait: TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None = None,
  3233. per_key_traits: t.Any = None,
  3234. key_trait: TraitType[t.Any, t.Any] | None = None,
  3235. default_value: dict[K, V] | Sentinel | None = Undefined,
  3236. **kwargs: t.Any,
  3237. ) -> None:
  3238. """Create a dict trait type from a Python dict.
  3239. The default value is created by doing ``dict(default_value)``,
  3240. which creates a copy of the ``default_value``.
  3241. Parameters
  3242. ----------
  3243. value_trait : TraitType [ optional ]
  3244. The specified trait type to check and use to restrict the values of
  3245. the dict. If unspecified, values are not checked.
  3246. per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ]
  3247. A Python dictionary containing the types that are valid for
  3248. restricting the values of the dict on a per-key basis.
  3249. Each value in this dict should be a Trait for validating
  3250. key_trait : TraitType [ optional, keyword-only ]
  3251. The type for restricting the keys of the dict. If
  3252. unspecified, the types of the keys are not checked.
  3253. default_value : SequenceType [ optional, keyword-only ]
  3254. The default value for the Dict. Must be dict, tuple, or None, and
  3255. will be cast to a dict if not None. If any key or value traits are specified,
  3256. the `default_value` must conform to the constraints.
  3257. Examples
  3258. --------
  3259. a dict whose values must be text
  3260. >>> d = Dict(Unicode())
  3261. d2['n'] must be an integer
  3262. d2['s'] must be text
  3263. >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()})
  3264. d3's keys must be text
  3265. d3's values must be integers
  3266. >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())
  3267. """
  3268. # handle deprecated keywords
  3269. trait = kwargs.pop("trait", None)
  3270. if trait is not None:
  3271. if value_trait is not None:
  3272. raise TypeError(
  3273. "Found a value for both `value_trait` and its deprecated alias `trait`."
  3274. )
  3275. value_trait = trait
  3276. warn(
  3277. "Keyword `trait` is deprecated in traitlets 5.0, use `value_trait` instead",
  3278. DeprecationWarning,
  3279. stacklevel=2,
  3280. )
  3281. traits = kwargs.pop("traits", None)
  3282. if traits is not None:
  3283. if per_key_traits is not None:
  3284. raise TypeError(
  3285. "Found a value for both `per_key_traits` and its deprecated alias `traits`."
  3286. )
  3287. per_key_traits = traits
  3288. warn(
  3289. "Keyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` instead",
  3290. DeprecationWarning,
  3291. stacklevel=2,
  3292. )
  3293. # Handling positional arguments
  3294. if default_value is Undefined and value_trait is not None:
  3295. if not is_trait(value_trait):
  3296. assert not isinstance(value_trait, TraitType)
  3297. default_value = value_trait
  3298. value_trait = None
  3299. if key_trait is None and per_key_traits is not None:
  3300. if is_trait(per_key_traits):
  3301. key_trait = per_key_traits
  3302. per_key_traits = None
  3303. # Handling default value
  3304. if default_value is Undefined:
  3305. default_value = {}
  3306. if default_value is None:
  3307. args: t.Any = None
  3308. elif isinstance(default_value, dict):
  3309. args = (default_value,)
  3310. elif isinstance(default_value, SequenceTypes):
  3311. args = (default_value,)
  3312. else:
  3313. raise TypeError("default value of Dict was %s" % default_value)
  3314. # Case where a type of TraitType is provided rather than an instance
  3315. if is_trait(value_trait):
  3316. if isinstance(value_trait, type):
  3317. warn( # type:ignore[unreachable]
  3318. "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
  3319. " Passing types is deprecated in traitlets 4.1.",
  3320. DeprecationWarning,
  3321. stacklevel=2,
  3322. )
  3323. value_trait = value_trait()
  3324. self._value_trait = value_trait
  3325. elif value_trait is not None:
  3326. raise TypeError(
  3327. "`value_trait` must be a Trait or None, got %s" % repr_type(value_trait)
  3328. )
  3329. if is_trait(key_trait):
  3330. if isinstance(key_trait, type):
  3331. warn( # type:ignore[unreachable]
  3332. "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
  3333. " Passing types is deprecated in traitlets 4.1.",
  3334. DeprecationWarning,
  3335. stacklevel=2,
  3336. )
  3337. key_trait = key_trait()
  3338. self._key_trait = key_trait
  3339. elif key_trait is not None:
  3340. raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait))
  3341. self._per_key_traits = per_key_traits
  3342. super().__init__(klass=dict, args=args, **kwargs)
  3343. def element_error(
  3344. self, obj: t.Any, element: t.Any, validator: t.Any, side: str = "Values"
  3345. ) -> None:
  3346. e = (
  3347. side
  3348. + f" of the '{self.name}' trait of {class_of(obj)} instance must be {validator.info()}, but a value of {repr_type(element)} was specified."
  3349. )
  3350. raise TraitError(e)
  3351. def validate(self, obj: t.Any, value: t.Any) -> dict[K, V] | None:
  3352. value = super().validate(obj, value)
  3353. if value is None:
  3354. return value
  3355. return self.validate_elements(obj, value)
  3356. def validate_elements(self, obj: t.Any, value: dict[t.Any, t.Any]) -> dict[K, V] | None:
  3357. per_key_override = self._per_key_traits or {}
  3358. key_trait = self._key_trait
  3359. value_trait = self._value_trait
  3360. if not (key_trait or value_trait or per_key_override):
  3361. return value
  3362. validated = {}
  3363. for key in value:
  3364. v = value[key]
  3365. if key_trait:
  3366. try:
  3367. key = key_trait._validate(obj, key)
  3368. except TraitError:
  3369. self.element_error(obj, key, key_trait, "Keys")
  3370. active_value_trait = per_key_override.get(key, value_trait)
  3371. if active_value_trait:
  3372. try:
  3373. v = active_value_trait._validate(obj, v)
  3374. except TraitError:
  3375. self.element_error(obj, v, active_value_trait, "Values")
  3376. validated[key] = v
  3377. return self.klass(validated) # type:ignore[misc,operator]
  3378. def class_init(self, cls: type[t.Any], name: str | None) -> None:
  3379. if isinstance(self._value_trait, TraitType):
  3380. self._value_trait.class_init(cls, None)
  3381. if isinstance(self._key_trait, TraitType):
  3382. self._key_trait.class_init(cls, None)
  3383. if self._per_key_traits is not None:
  3384. for trait in self._per_key_traits.values():
  3385. trait.class_init(cls, None)
  3386. super().class_init(cls, name)
  3387. def subclass_init(self, cls: type[t.Any]) -> None:
  3388. if isinstance(self._value_trait, TraitType):
  3389. self._value_trait.subclass_init(cls)
  3390. if isinstance(self._key_trait, TraitType):
  3391. self._key_trait.subclass_init(cls)
  3392. if self._per_key_traits is not None:
  3393. for trait in self._per_key_traits.values():
  3394. trait.subclass_init(cls)
  3395. # explicitly not calling super().subclass_init(cls)
  3396. # to opt out of instance_init
  3397. def from_string(self, s: str) -> dict[K, V] | None:
  3398. """Load value from a single string"""
  3399. if not isinstance(s, str):
  3400. raise TypeError(f"from_string expects a string, got {s!r} of type {type(s)}")
  3401. try:
  3402. return t.cast("dict[K, V]", self.from_string_list([s]))
  3403. except Exception:
  3404. test = _safe_literal_eval(s)
  3405. if isinstance(test, dict):
  3406. return test
  3407. raise
  3408. def from_string_list(self, s_list: list[str]) -> t.Any:
  3409. """Return a dict from a list of config strings.
  3410. This is where we parse CLI configuration.
  3411. Each item should have the form ``"key=value"``.
  3412. item parsing is done in :meth:`.item_from_string`.
  3413. """
  3414. if len(s_list) == 1 and s_list[0] == "None" and self.allow_none:
  3415. return None
  3416. if len(s_list) == 1 and s_list[0].startswith("{") and s_list[0].endswith("}"):
  3417. warn(
  3418. f"--{self.name}={s_list[0]} for dict-traits is deprecated in traitlets 5.0. "
  3419. f"You can pass --{self.name} <key=value> ... multiple times to add items to a dict.",
  3420. DeprecationWarning,
  3421. stacklevel=2,
  3422. )
  3423. return literal_eval(s_list[0])
  3424. combined = {}
  3425. for d in [self.item_from_string(s) for s in s_list]:
  3426. combined.update(d)
  3427. return combined
  3428. def item_from_string(self, s: str) -> dict[K, V]:
  3429. """Cast a single-key dict from a string.
  3430. Evaluated when parsing CLI configuration from a string.
  3431. Dicts expect strings of the form key=value.
  3432. Returns a one-key dictionary,
  3433. which will be merged in :meth:`.from_string_list`.
  3434. """
  3435. if "=" not in s:
  3436. raise TraitError(
  3437. f"'{self.__class__.__name__}' options must have the form 'key=value', got {s!r}"
  3438. )
  3439. key, value = s.split("=", 1)
  3440. # cast key with key trait, if defined
  3441. if self._key_trait:
  3442. key = self._key_trait.from_string(key)
  3443. # cast value with value trait, if defined (per-key or global)
  3444. value_trait = (self._per_key_traits or {}).get(key, self._value_trait)
  3445. if value_trait:
  3446. value = value_trait.from_string(value)
  3447. return t.cast("dict[K, V]", {key: value})
  3448. class TCPAddress(TraitType[G, S]):
  3449. """A trait for an (ip, port) tuple.
  3450. This allows for both IPv4 IP addresses as well as hostnames.
  3451. """
  3452. default_value = ("127.0.0.1", 0)
  3453. info_text = "an (ip, port) tuple"
  3454. if t.TYPE_CHECKING:
  3455. @t.overload
  3456. def __init__(
  3457. self: TCPAddress[tuple[str, int], tuple[str, int]],
  3458. default_value: bool | Sentinel = ...,
  3459. allow_none: Literal[False] = ...,
  3460. read_only: bool | None = ...,
  3461. help: str | None = ...,
  3462. config: t.Any = ...,
  3463. **kwargs: t.Any,
  3464. ) -> None:
  3465. ...
  3466. @t.overload
  3467. def __init__(
  3468. self: TCPAddress[tuple[str, int] | None, tuple[str, int] | None],
  3469. default_value: bool | None | Sentinel = ...,
  3470. allow_none: Literal[True] = ...,
  3471. read_only: bool | None = ...,
  3472. help: str | None = ...,
  3473. config: t.Any = ...,
  3474. **kwargs: t.Any,
  3475. ) -> None:
  3476. ...
  3477. def __init__(
  3478. self: TCPAddress[tuple[str, int] | None, tuple[str, int] | None]
  3479. | TCPAddress[tuple[str, int], tuple[str, int]],
  3480. default_value: bool | None | Sentinel = Undefined,
  3481. allow_none: Literal[True, False] = False,
  3482. read_only: bool | None = None,
  3483. help: str | None = None,
  3484. config: t.Any = None,
  3485. **kwargs: t.Any,
  3486. ) -> None:
  3487. ...
  3488. def validate(self, obj: t.Any, value: t.Any) -> G:
  3489. if isinstance(value, tuple):
  3490. if len(value) == 2:
  3491. if isinstance(value[0], str) and isinstance(value[1], int):
  3492. port = value[1]
  3493. if port >= 0 and port <= 65535:
  3494. return t.cast(G, value)
  3495. self.error(obj, value)
  3496. def from_string(self, s: str) -> G:
  3497. if self.allow_none and s == "None":
  3498. return t.cast(G, None)
  3499. if ":" not in s:
  3500. raise ValueError("Require `ip:port`, got %r" % s)
  3501. ip, port_str = s.split(":", 1)
  3502. port = int(port_str)
  3503. return t.cast(G, (ip, port))
  3504. class CRegExp(TraitType["re.Pattern[t.Any]", t.Union["re.Pattern[t.Any]", str]]):
  3505. """A casting compiled regular expression trait.
  3506. Accepts both strings and compiled regular expressions. The resulting
  3507. attribute will be a compiled regular expression."""
  3508. info_text = "a regular expression"
  3509. def validate(self, obj: t.Any, value: t.Any) -> re.Pattern[t.Any] | None:
  3510. try:
  3511. return re.compile(value)
  3512. except Exception:
  3513. self.error(obj, value)
  3514. class UseEnum(TraitType[t.Any, t.Any]):
  3515. """Use a Enum class as model for the data type description.
  3516. Note that if no default-value is provided, the first enum-value is used
  3517. as default-value.
  3518. .. sourcecode:: python
  3519. # -- SINCE: Python 3.4 (or install backport: pip install enum34)
  3520. import enum
  3521. from traitlets import HasTraits, UseEnum
  3522. class Color(enum.Enum):
  3523. red = 1 # -- IMPLICIT: default_value
  3524. blue = 2
  3525. green = 3
  3526. class MyEntity(HasTraits):
  3527. color = UseEnum(Color, default_value=Color.blue)
  3528. entity = MyEntity(color=Color.red)
  3529. entity.color = Color.green # USE: Enum-value (preferred)
  3530. entity.color = "green" # USE: name (as string)
  3531. entity.color = "Color.green" # USE: scoped-name (as string)
  3532. entity.color = 3 # USE: number (as int)
  3533. assert entity.color is Color.green
  3534. """
  3535. default_value: enum.Enum | None = None
  3536. info_text = "Trait type adapter to a Enum class"
  3537. def __init__(
  3538. self, enum_class: type[t.Any], default_value: t.Any = None, **kwargs: t.Any
  3539. ) -> None:
  3540. assert issubclass(enum_class, enum.Enum), "REQUIRE: enum.Enum, but was: %r" % enum_class
  3541. allow_none = kwargs.get("allow_none", False)
  3542. if default_value is None and not allow_none:
  3543. default_value = next(iter(enum_class.__members__.values()))
  3544. super().__init__(default_value=default_value, **kwargs)
  3545. self.enum_class = enum_class
  3546. self.name_prefix = enum_class.__name__ + "."
  3547. def select_by_number(self, value: int, default: t.Any = Undefined) -> t.Any:
  3548. """Selects enum-value by using its number-constant."""
  3549. assert isinstance(value, int)
  3550. enum_members = self.enum_class.__members__
  3551. for enum_item in enum_members.values():
  3552. if enum_item.value == value:
  3553. return enum_item
  3554. # -- NOT FOUND:
  3555. return default
  3556. def select_by_name(self, value: str, default: t.Any = Undefined) -> t.Any:
  3557. """Selects enum-value by using its name or scoped-name."""
  3558. assert isinstance(value, str)
  3559. if value.startswith(self.name_prefix):
  3560. # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
  3561. value = value.replace(self.name_prefix, "", 1)
  3562. return self.enum_class.__members__.get(value, default)
  3563. def validate(self, obj: t.Any, value: t.Any) -> t.Any:
  3564. if isinstance(value, self.enum_class):
  3565. return value
  3566. elif isinstance(value, int):
  3567. # -- CONVERT: number => enum_value (item)
  3568. value2 = self.select_by_number(value)
  3569. if value2 is not Undefined:
  3570. return value2
  3571. elif isinstance(value, str):
  3572. # -- CONVERT: name or scoped_name (as string) => enum_value (item)
  3573. value2 = self.select_by_name(value)
  3574. if value2 is not Undefined:
  3575. return value2
  3576. elif value is None:
  3577. if self.allow_none:
  3578. return None
  3579. else:
  3580. return self.default_value
  3581. self.error(obj, value)
  3582. def _choices_str(self, as_rst: bool = False) -> str:
  3583. """Returns a description of the trait choices (not none)."""
  3584. choices = self.enum_class.__members__.keys()
  3585. if as_rst:
  3586. return "|".join("``%r``" % x for x in choices)
  3587. else:
  3588. return repr(list(choices)) # Listify because py3.4- prints odict-class
  3589. def _info(self, as_rst: bool = False) -> str:
  3590. """Returns a description of the trait."""
  3591. none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
  3592. return f"any of {self._choices_str(as_rst)}{none}"
  3593. def info(self) -> str:
  3594. return self._info(as_rst=False)
  3595. def info_rst(self) -> str:
  3596. return self._info(as_rst=True)
  3597. class Callable(TraitType[t.Callable[..., t.Any], t.Callable[..., t.Any]]):
  3598. """A trait which is callable.
  3599. Notes
  3600. -----
  3601. Classes are callable, as are instances
  3602. with a __call__() method."""
  3603. info_text = "a callable"
  3604. def validate(self, obj: t.Any, value: t.Any) -> t.Any:
  3605. if callable(value):
  3606. return value
  3607. else:
  3608. self.error(obj, value)