@@ -504,41 +504,27 @@ def move_child(
504504 elif before is not None and after is not None :
505505 raise WidgetError ("Only one of `before`or `after` can be handled." )
506506
507- # Turn the child to move into a reference to the widget, doing some
508- # checks as we do so.
509- if isinstance (child , int ):
510- try :
511- child = self .children [child ]
512- except IndexError :
513- raise WidgetError (
514- f"An index of { child } for the child to move is out of bounds"
515- ) from None
516- else :
517- # We got an actual widget, so let's be sure it really is one of
518- # our children.
519- try :
520- _ = self .children .index (child )
521- except ValueError :
522- raise WidgetError (f"{ child !r} is not a child of { self !r} " ) from None
523-
524- # Next, no matter if we're moving before or after, we just want to
525- # be sure that the target makes sense at all. So let's concentrate
526- # on that for a moment.
527- target = before if after is None else after
528- if isinstance (target , int ):
529- try :
530- target = self .children [target ]
531- except IndexError :
532- raise WidgetError (
533- f"An index of { target } for the target to move towards is out of bounds"
534- ) from None
535- elif isinstance (target , Widget ):
536- # If we got given a widget from the off, let's be sure it's
537- # actually one of our children.
538- try :
539- _ = self .children .index (target )
540- except ValueError :
541- raise WidgetError (f"{ target !r} is not a child of { self !r} " ) from None
507+ def _to_widget (child : int | Widget , called : str ) -> Widget :
508+ """Ensure a given child reference is a Widget."""
509+ if isinstance (child , int ):
510+ try :
511+ child = self .children [child ]
512+ except IndexError :
513+ raise WidgetError (
514+ f"An index of { child } for the child to { called } is out of bounds"
515+ ) from None
516+ else :
517+ # We got an actual widget, so let's be sure it really is one of
518+ # our children.
519+ try :
520+ _ = self .children .index (child )
521+ except ValueError :
522+ raise WidgetError (f"{ child !r} is not a child of { self !r} " ) from None
523+ return child
524+
525+ # Ensure the child and target are widgets.
526+ child = _to_widget (child , "move" )
527+ target = _to_widget (before if after is None else after , "move towards" )
542528
543529 # At this point we should know what we're moving, and it should be a
544530 # child; where we're moving it to, which should be within the child
0 commit comments