def scale(self, n):
pods = self._cleanup_terminated_pods(self.pods())<EOL>if n >= len(pods):<EOL><INDENT>return self.scale_up(n, pods=pods)<EOL><DEDENT>else:<EOL><INDENT>n_to_delete = len(pods) - n<EOL>running_workers = list(self.scheduler.workers.keys())<EOL>running_ips = set(urlparse(worker).hostname<EOL>for worker in running_workers)<EOL>pending_pods = [p for p in pods<EOL>if p.status.pod_ip not in running_ips]<EOL>if pending_pods:<EOL><INDENT>pending_to_delete = pending_pods[:n_to_delete]<EOL>logger.debug("<STR_LIT>", pending_to_delete)<EOL>self._delete_pods(pending_to_delete)<EOL>n_to_delete = n_to_delete - len(pending_to_delete)<EOL>if n_to_delete <= <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT><DEDENT>to_close = select_workers_to_close(self.scheduler, n_to_delete)<EOL>logger.debug("<STR_LIT>", to_close)<EOL>if len(to_close) < len(self.scheduler.workers):<EOL><INDENT>@gen.coroutine<EOL>def f(to_close):<EOL><INDENT>yield self.scheduler.retire_workers(<EOL>workers=to_close, remove=True, close_workers=True)<EOL>yield offload(self.scale_down, to_close)<EOL><DEDENT>self.scheduler.loop.add_callback(f, to_close)<EOL>return<EOL><DEDENT>self.scale_down(to_close)<EOL><DEDENT>
Scale cluster to n workers

        Parameters
        ----------
        n: int
            Target number of workers

        Example
        -------
        >>> cluster.scale(10)  # scale cluster to ten workers

        See Also
        --------
        KubeCluster.scale_up
        KubeCluster.scale_down