Skip to content

refactor(api): Allow for non-shell facts - #2108

Open
gchazot wants to merge 9 commits into
pyinfra-dev:3.xfrom
gchazot:non_shell_facts
Open

gchazot wants to merge 9 commits into
pyinfra-dev:3.xfrom
gchazot:non_shell_facts

Conversation

@gchazot

@gchazot gchazot commented Nov 23, 2026 •

Copy link
Copy Markdown

This refactor is the beginning of work to simplify using Pyinfra to configure targets that are not easily configured with shell commands, or that are easier or safer to configure another way. Benefits include:

  • targetting hardware that offers a stable HTTP API to configure itself but different versions of the underlying OS require different files or commands.
  • avoiding to mix languages: the HTTP example means writing Pyinfra Python code, a shell script using curl or equivalent, plus the correponding HTTP request, and some shell/python(/json/xml/...?) to parse. This direction allows to think about doing all of it in Python.
  • avoiding to open shell access on devices where that could weaken their security stance.

I have put in this PR a number of changes, which, if requested, could be split in separate PRs. I'm leaving them together for now as it would make sense if discussions relate to the whole direction. The high level changes included are:

  • Refactor of get_fact and the Facts API to extract FactCore as the abstraction of any Fact
  • Addition of a @fact decorator to write facts with a simple function
  • Rename existing Fact base classes to make their purpose and scope clearer.

AI usage disclosure

  • I used Jetbrains Air/Junie on this project. If I'm at the office I might also use Cursor (not yet on this though).
  • Here I've only used AI to:
    • review my changes (help clear my own blindspots)
    • update the documentation
    • autocomplete code when typing

BREAKING CHANGE: External code calling api.facts.get_fact(...) could fail.
@wowi42 wowi42 added API API mode specific issues. facts Issues with facts. operations Issues with operations. CLI CLI mode specific issues. labels Nov 23, 2026
Comment thread src/pyinfra/api/facts.py
Comment on lines +153 to +173
positional_parameters = [
name
for name, candidate in parameters.items()
if candidate.kind
in (
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
)
]

to_insert: list[tuple[int, str, object]] = []
for name, obj in [
("state", state),
("host", host),
]:
if name in parameters:
if name in positional_parameters:
position = positional_parameters.index(name)
to_insert.append((position, name, obj))
else:
call_kwargs[name] = obj

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Starting a discussion here because I'd like feedback on this aspect.
This code, while already quite complex, does not handle properly Pyinfra fact global arguments (like _sudo). To avoid making this overly complex, one option would be to require all arguments to a "fact function" to be keyword arguments. Would this be too much of a limitation? Are there simpler solutions that I didn't think about?

@gchazot gchazot changed the title [refactor] Allow for non-shell facts refactor(api) Allow for non-shell facts Nov 23, 2026
@gchazot gchazot changed the title refactor(api) Allow for non-shell facts refactor(api): Allow for non-shell facts Nov 23, 2026
Cleans up the tests that check and inventory Fact classes, such that they make use of the new FactCore base class and they do not need to rely on confusing naming conventions for facts.

BREAKING CHANGE: Fact class `abstract` property now needs to be specified on each level of inheritance that is abstract.
Even though the class property would be inherited, the test is such that the value defined on a parent is ignored.
This is to make sure that `abstract = False` does NOT have to be specified in each and every concrete Fact class.
…tcutFact

These represent better what those facts provide.
API backwards compatibility is maintained by adding aliases that can be removed in a later release

@wowi42 wowi42 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not safe to merge in v3 yet. It removes pyinfra.api.facts.get_fact and get_short_facts without compatibility wrappers or a deprecation path. Please keep those APIs delegating to the new implementation for v3. The other blockers are inline.

Comment thread src/pyinfra/api/facts.py
bound_arguments = sig.bind(*call_args, **call_kwargs)
return fact_func(*bound_arguments.args, **bound_arguments.kwargs)

module_name = fact_func.__module__.replace("pyinfra.facts.", "")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decorator copies only name and __doc__. The generated class keeps __module__ = "pyinfra.api.facts" and __name__ = "DecoratedFact", so docs generators filter it out and operation links point to a nonexistent page. Please preserve the wrapped function metadata and add docs-generation coverage with a real decorated fact.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this one, I'm not sure I fully understand what you mean by "docs generators filter it out". But I think that the fix expected is to copy __module__ and __name__ from the fact function into the wrapper class. I've done this in 760b57e

Comment thread src/pyinfra/api/host.py Outdated
def get_fact(self, name_or_cls: type[ShortFactBase[T]], *args, **kwargs) -> T: ...

def get_fact(self, name_or_cls, *args, **kwargs):
def get_fact(self, name_or_cls: type[FactCore[T]], *args, **kwargs):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the -> T return annotation here makes Host.get_fact return Any to type checkers. Please restore the generic return type and add typing coverage for shell, shortcut, and decorated facts.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, fixed in 3088493

from pyinfra.api.facts import FactCore, fact


class TestFactDecorator(unittest.TestCase):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add regression cases for a fact function returning None, raising an exception, and being called repeatedly without caching. These documented paths are not covered by the current tests.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed these were missed. Fixed in a788ee8

@gchazot

gchazot commented Dec 1, 2026

Copy link
Copy Markdown
Author

This is not safe to merge in v3 yet. It removes pyinfra.api.facts.get_fact and get_short_facts without compatibility wrappers or a deprecation path. Please keep those APIs delegating to the new implementation for v3. The other blockers are inline.

Thanks for taking the time to review.
I've added the missing wrappers in 3088493.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

API API mode specific issues. CLI CLI mode specific issues. facts Issues with facts. operations Issues with operations.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants