Skip to content

Commit

Permalink
Add method to clone parameters with private attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
ogenstad committed Jun 11, 2024
1 parent 46ecb53 commit 3ec08a6
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions nornir/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(
self.inventory = inventory
self.config = config or Config()
self.processors = processors or Processors()
self.runner = runner
self._runner = runner

def __enter__(self) -> "Nornir":
return self
Expand All @@ -65,14 +65,16 @@ def with_processors(self, processors: List[Processor]) -> "Nornir":
Given a list of Processor objects return a copy of the nornir object with the processors
assigned to the copy. The orinal object is left unmodified.
"""
return Nornir(**{**self.__dict__, **{"processors": Processors(processors)}})
return Nornir(
**{**self._clone_parameters(), **{"processors": Processors(processors)}}
)

def with_runner(self, runner: RunnerPlugin) -> "Nornir":
"""
Given a runner return a copy of the nornir object with the runner
assigned to the copy. The orinal object is left unmodified.
"""
return Nornir(**{**self.__dict__, **{"runner": runner}})
return Nornir(**{**self._clone_parameters(), **{"runner": runner}})

def filter(self, *args: Any, **kwargs: Any) -> "Nornir":
"""
Expand All @@ -81,7 +83,7 @@ def filter(self, *args: Any, **kwargs: Any) -> "Nornir":
Returns:
:obj:`Nornir`: A new object with same configuration as ``self`` but filtered inventory.
"""
b = Nornir(**self.__dict__)
b = Nornir(**self._clone_parameters())
b.inventory = self.inventory.filter(*args, **kwargs)
return b

Expand Down Expand Up @@ -143,7 +145,7 @@ def run(
else:
logger.warning("Task %r has not been run – 0 hosts selected", task.name)

result = self._runner.run(task, run_on)
result = self.runner.run(task, run_on)

raise_on_error = (
raise_on_error
Expand All @@ -170,12 +172,21 @@ def close_connections_task(task):
self.run(task=close_connections_task, on_good=on_good, on_failed=on_failed)

@property
def _runner(self) -> RunnerPlugin:
if self.runner:
return self.runner
def runner(self) -> RunnerPlugin:
if self._runner:
return self._runner

raise PluginNotRegistered("Runner plugin not registered")

def _clone_parameters(self) -> dict:
return {
"data": self.data,
"inventory": self.inventory,
"config": self.config,
"processors": self.processors,
"runner": self._runner,
}

@classmethod
def get_validators(cls) -> Generator[Callable[["Nornir"], "Nornir"], None, None]:
yield cls.validate
Expand Down

0 comments on commit 3ec08a6

Please sign in to comment.