Giter Club home page Giter Club logo

in-n-out's People

Contributors

czaki avatar davidbrochart avatar dependabot[bot] avatar lucyleeow avatar pre-commit-ci[bot] avatar tlambert03 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

in-n-out's Issues

Inject dependency on a Typer function

  • in-n-out version: 0.1.6
  • Python version: 3.11
  • Operating System: Ubuntu 22.04

Description

The following code:

import in_n_out as ino
import typer

class Thing:
    pass

@ino.inject
def main(name: str, thing: Thing):
    print(f"Hello {name}")

if __name__ == "__main__":
    typer.run(main)

Fails with RuntimeError: Type not yet supported: <class '__main__.Thing'>, probably because Typer also inspects the main function signature, which doesn't play well with in-n-out.
There is a workaround:

def main(name: str):
    @ino.inject
    def inner(thing: Thing):
        print(f"Hello {name}")
    inner()

But curious to know if you can think of a better solution?

Mock obj `resolve_single_type_hints` results in empty `globalns`, preventing resolve

Description

In type_resolved_signature if hints.update(resolve_type_hints(func, localns=localns)) errors, all parameters in sig are resolved using _resolve_params_one_by_one:

try:
hints.update(resolve_type_hints(func, localns=localns))
except (NameError, TypeError) as err:
if raise_unresolved_optional_args:
raise NameError(
f"Could not resolve all annotations in signature {sig} ({err}). "
"To allow optional parameters and return types to remain unresolved, "
"use `raise_unresolved_optional_args=False`"
) from err
hints = _resolve_params_one_by_one(
sig,
localns=localns,
exclude_unresolved_mandatory=not raise_unresolved_required_args,
)

This calls resolve_single_type_hints which creates a mock object. When we later use typing.get_type_hints we get the global namespace, which for this mock object is empty. This means that if one parameter has an unresolvable type annotation, other parameters may be not resolved. (The globalns of the original object would have the required objects)

Note that this is for cases where from __future__ import annotations is used.

What I Did

Results in using _resolve_params_one_by_one:

from __future__ import annotations

from in_n_out import type_resolved_signature
from app_model import Action
from magicgui.widgets import FunctionGui

def outer():

    def myfun(a: 'unknown', b: FunctionGui):
        if isinstance(a, FunctionGui):
            return a

    return Action(id='test', title='title', callback=myfun)

act = outer()
a = type_resolved_signature(act.callback, raise_unresolved_optional_args=False, raise_unresolved_required_args=False)
print(a)

Gives:

(a: "'unknown'", b: 'FunctionGui')

Whereas if I used instead def myfun(a: str, b: FunctionGui):, b does resolve properly:

(a: str, b: magicgui.widgets._function_gui.FunctionGui)

I would always expect b to resolve properly regardless of what the other parameter annotations are.

Register a processor which has injections

  • in-n-out version: 0.1.6
  • Python version: 3.11
  • Operating System: Ubuntu 22.04

Description

Consider the following code which registers providers and processors:

import in_n_out as ino

COUNTER = 0

class Dummy:
    pass

class Thing:
    def __init__(self):
        self.list = []

def dummy_provider() -> Dummy:
    return Dummy()

@ino.inject
@ino.inject_processors
def thing_provider(dummy: Dummy) -> Thing:
    return Thing()

ino.register_provider(dummy_provider)
ino.register_provider(thing_provider)

def add_item(thing: Thing):
    global COUNTER
    thing.list.append(COUNTER)
    COUNTER += 1

ino.inject_processors(add_item)

ino.register_processor(add_item)
ino.register_processor(add_item)
ino.register_processor(add_item)

@ino.inject
def func(thing: Thing):
    print(thing.list)

func()
# prints [0, 1, 2]

Now if I want to inject a Dummy object in add_item:

@ino.inject
def add_item(dummy: Dummy, thing: Thing):
    global COUNTER
    thing.list.append(COUNTER)
    COUNTER += 1

It doesn't work anymore, as dummy and thing can be injected and the signature doesn't match with a Thing. This works:

def add_item(thing: Thing):
    @ino.inject
    def inner(dummy: Dummy):
        global COUNTER
        thing.list.append(COUNTER)
        COUNTER += 1
    inner()

But I was wondering if there could be a better solution?

Object in localns but signature of inner function not resolved

Description

When resolving the signature of a nested inner function, importing a signature object globally works but importing inside the outer function does not (even though this results in the object being in the local namespace of the outer function).

What I Did

from __future__ import annotations

from in_n_out import type_resolved_signature
from app_model import Action


def outer():
    from magicgui.widgets import FunctionGui
    def myfun(a: FunctionGui):
        if isinstance(a, FunctionGui):
            return a

    print(f'locals {locals()}')

    return Action(id='test', title='title', callback=myfun)

act = outer()
a = type_resolved_signature(act.callback, raise_unresolved_optional_args=False, raise_unresolved_required_args=False)
print(a)

gives:

locals {'myfun': <function outer.<locals>.myfun at 0x7f22eccf6280>, 'FunctionGui': <class 'magicgui.widgets._function_gui.FunctionGui'>}
(a: 'FunctionGui')

I have not yet looked into why this is happening but you may know already.

Hopefully I got this right and you would expect this to resolve.

Loosen cython reqs

When trying to update napari's packages for archlinux, I got stuck at in-n-out requiring a specific (non-latest) version of cython. As far as I can tell, everything builds fine with a later version (currently testes 3.0.0b3 instead of 3.0.0a11. Can we loosed these requirements here, or should I work around it downstream?

feature: support generators as providers

we should support generator_functions as providers, so they can perform setup/cleanup before provision

def provide_something() -> Iterator[Something]:
    try:
        yield Something()
    finally:
        ...  # cleanup

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.