@@ -147,6 +147,14 @@ class RenderCache(NamedTuple):
147147 lines : Lines
148148
149149
150+ class WidgetError (Exception ):
151+ """Base widget error."""
152+
153+
154+ class MountError (WidgetError ):
155+ """Error raised when there was a problem with the mount request."""
156+
157+
150158@rich .repr .auto
151159class Widget (DOMNode ):
152160 """
@@ -233,6 +241,10 @@ def __init__(
233241 id = id ,
234242 classes = self .DEFAULT_CLASSES if classes is None else classes ,
235243 )
244+
245+ if self in children :
246+ raise WidgetError ("A widget can't be its own parent" )
247+
236248 self ._add_children (* children )
237249
238250 virtual_size = Reactive (Size (0 , 0 ), layout = True )
@@ -374,9 +386,6 @@ def _get_virtual_dom(self) -> Iterable[Widget]:
374386 if self ._scrollbar_corner is not None :
375387 yield self ._scrollbar_corner
376388
377- class MountError (Exception ):
378- """Error raised when there was a problem with the mount request."""
379-
380389 def _find_mount_point (self , spot : int | str | "Widget" ) -> tuple ["Widget" , int ]:
381390 """Attempt to locate the point where the caller wants to mount something.
382391
@@ -387,7 +396,7 @@ def _find_mount_point(self, spot: int | str | "Widget") -> tuple["Widget", int]:
387396 tuple[Widget, int]: The parent and the location in its child list.
388397
389398 Raises:
390- Widget. MountError: If there was an error finding where to mount a widget.
399+ MountError: If there was an error finding where to mount a widget.
391400
392401 The rules of this method are:
393402
@@ -414,7 +423,7 @@ def _find_mount_point(self, spot: int | str | "Widget") -> tuple["Widget", int]:
414423 # have a parent? There's no way we can use it as a sibling to make
415424 # mounting decisions if it doesn't have a parent.
416425 if spot .parent is None :
417- raise self . MountError (
426+ raise MountError (
418427 f"Unable to find relative location of { spot !r} because it has no parent"
419428 )
420429
@@ -424,7 +433,7 @@ def _find_mount_point(self, spot: int | str | "Widget") -> tuple["Widget", int]:
424433 try :
425434 return spot .parent , spot .parent .children .index (spot )
426435 except ValueError :
427- raise self . MountError (f"{ spot !r} is not a child of { self !r} " ) from None
436+ raise MountError (f"{ spot !r} is not a child of { self !r} " ) from None
428437
429438 def mount (
430439 self ,
@@ -452,7 +461,7 @@ def mount(
452461
453462 # Saying you want to mount before *and* after something is an error.
454463 if before is not None and after is not None :
455- raise self . MountError (
464+ raise MountError (
456465 "Only one of `before` or `after` can be handled -- not both"
457466 )
458467
0 commit comments