You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Using python3 keyword-only arguments or annotated arguments causes a ValueError from inspect #357
Defining a task that uses the new Python3 keyword-only or annotation argument syntax and invoking causes a ValueError: Function has keyword-only arguments or annotations, use getfullargspec() API which can support them and halts.
Per the docstring for Python3 inspect, getfullargspec() could be used, but that function is itself deprecated in favor of inspect.signature() Unfortunately, neither of those functions exists in Python 2.6, so some level of cascading will be necessary.
Reacted by Alexander Iljushkin ✅, Franklin Chen, Vladimir, Manabu Kobayashi, Nathaniel Ford, Jesse Talavera, Juan José, Alexander Gorokhov, Yoko Karasaki, Nathan and 55 more
Thanks for the bump, I'll take a look at #373 soon which seems to be the main patch around this.
@FranklinChen If you can check out that PR's branch and confirm it works against latest master & solves your particular flavor of the issue, that'd be a big help!
nford@Nathaniels-MacBook-Pro:~/repos/deploy-apps $ invoke --list -v
Traceback (most recent call last):
File "/usr/local/bin/invoke", line 11, in <module>
sys.exit(program.run())
File "/usr/local/lib/python3.6/site-packages/invoke/program.py", line 324, in run
self.parse_collection()
File "/usr/local/lib/python3.6/site-packages/invoke/program.py", line 408, in parse_collection
self.load_collection()
File "/usr/local/lib/python3.6/site-packages/invoke/program.py", line 599, in load_collection
module, parent = loader.load(coll_name)
File "/usr/local/lib/python3.6/site-packages/invoke/loader.py", line 76, in load
module = imp.load_module(name, fd, path, desc)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imp.py", line 245, in load_module
return load_package(name, filename)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imp.py", line 217, in load_package
return _load(spec)
File "<frozen importlib._bootstrap>", line 684, in _load
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/nmford/repos/deploy-apps/tasks/__init__.py", line 2, in <module>
from tasks import install
File "/Users/nmford/repos/deploy-apps/tasks/install.py", line 26, in <module>
def domino(context, app: str):
File "/usr/local/lib/python3.6/site-packages/invoke/tasks.py", line 313, in task
return klass(args[0], **kwargs)
File "/usr/local/lib/python3.6/site-packages/invoke/tasks.py", line 77, in __init__
self.positional = self.fill_implicit_positionals(positional)
File "/usr/local/lib/python3.6/site-packages/invoke/tasks.py", line 168, in fill_implicit_positionals
args, spec_dict = self.argspec(self.body)
File "/usr/local/lib/python3.6/site-packages/invoke/tasks.py", line 154, in argspec
spec = inspect.getargspec(func)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 1075, in getargspec
raise ValueError("Function has keyword-only parameters or annotations"
ValueError: Function has keyword-only parameters or annotations, use getfullargspec() API which can support them
I am not sure what might need to be done to diagnose or resolve it from my end. Is anyone else still running into this?
Reacted by Pedro Celes, kenjiuno, Vladimir Shteyn, Václav Dohnal, Jan-Hein Bührman, Tatsuya Suzuki, Thomas Mansencal, Michael Scharf and Josh Peak
@nathanielford Just run into this too. As it says in the exception itself, replaced inspect.getargspec at invoke/tasks.py with inspect.getfullargspec manually. Works for me.
@SantjagoCorkez I may not be understanding you correctly, but I don't think it'll work for us to manually fork the invoke library code. If I get a chance, though, I'll see if I can put a PR together to submit here, unless the maintainers already have one ready? I'm a little unclear on where they believe the state of the bug to be, given the merged PR.
@nathanielford Well, the bug is more than 2 years old at the moment. Developers still didn't apply a patch that is proposed by the exception message itself. So, they don't care. You're on your own.
Reacted by James, Eugene Brodsky, Jamie Thomson, jacqueline he and Augustin LAVILLE
@karan-webkul Python 2 is at EOL, and while everyone using this package already is avoiding using type hints because it does not support it, this issue is around the fact that we'd like to both use the package and type hints, like other modern Python 3 apps.
Reacted by elonzh, Michel Albert, Konrad Gądek, Conor Heine, Kai Ase Siren, Russell and Steffen
I'll revisit this after dropping Python 2, which is one of the next things on the roadmap. Should make it much easier to apply/fix overall.
Reacted by Thomas Mansencal, Jarek Głowacki, Jamie Thomson, Josh Peak and Udi Oron
Reacted by Mohammed Alshehri, Zane Dufour, Michel Albert, Laurentiu, Paulo S. Costa, Charlie Denton, Stanislav Pankevich, Laurent Sorber, Arkadiusz Michał Ryś, hangedman and 5 more
This gives me both invoke tasks and type-safety. But it is really cumbersome as the args need to be touched in 3 areas if they change. Can't wait to get this fix released wink crossed_fingers
Once this is released I can drop the delegator and just move the @task decorator to the real function.
@exhuma I decided to do something like this, just automatically. I created a wrapper around @task, which simply creates wrapper function with modified signature, where the annotations are removed. Since there's plan to add proper support for those tasks in invoke at some point, it should be easy to just replace it with from invoke import task instead and have it working.
importinspectimportinvokeimportmakefunfromtypingimportOptionaldeftask(*taskargs, **taskkwargs):
defdecorator(fun):
""" Define invoke.task, while removing annotations from the visible signature in order to work around invoke bug pyinvoke/invoke/357 """# Copy over `fun` signature to `wrapper`# without annotations to work around https://github.com/pyinvoke/invoke/issues/357func_sig=inspect.Signature(
[
p.replace(annotation=inspect.Parameter.empty)
forpininspect.signature(fun).parameters.values()
]
)
@invoke.task(*taskargs, **taskkwargs)@makefun.wraps(fun, new_sig=func_sig)defwrapper(ctx, *args, **kwargs):
returnfun(ctx, *args, **kwargs)
returnwrapperifnottaskkwargsandlen(taskargs) ==1andcallable(taskargs[0]):
# The decorator was used without any argumentsfun=taskargs[0]
taskargs= []
returndecorator(fun)
returndecorator@taskdefhello(ctx, name: str, surname: Optional[str] =None) ->None:
"""Greets you by your name and (optionally) surname"""ifsurnameisNone:
print(f"Hello {name}!")
else:
print(f"Hello {name}{surname}!")
@task(default=True)defhi(ctx) ->None:
"""Says Hi you :)"""print("Hi you")
Usage:
$ inv -l
Available tasks:
hello Greets you by your name and (optionally) surname
hi Says Hi you :)
Default task: hi
$ inv
Hi you
$ inv --help hello
Usage: inv[oke] [--core-opts] hello [--options] [other tasks here ...]
Docstring:
Greets you by your name and (optionally) surname
Options:
-n STRING, --name=STRING
-s STRING, --surname=STRING
$ inv hello John
Hello John!
$ inv hello John --surname=Doe
Hello John Doe!
@bitprophet - I would also like to contribute. I have previously worked on vcrpy as a maintainer for a year and my new role is seeing me need invoke a lot and I would like to put the time and energy into breathing new life into keeping invoke relevant. I couldn't see a CONTRIBUTING.md to get a gist of who to contact about becoming a maintainer.
In particular I am coming from a few years over in Typescript where projects like lerna and npm workspaces coupled with the fact npm has scripts built into their package.json I feel this is lacking in the Python ecosystem.
poetry is about to launch v1.2.+ which allows plugins and I think combining poetry and invoke is a really awesome combination especially for multi-project mono-repos.
Dropping Python2 support (that test matrix was getting wild)
Also invoke is part of the fabric and paramiko ecosystem and they need equal amounts of love too.
But I am doing my best over the coming weeks and months to help close the items that will have the greatest impact for our limited cognitive bandwidth and volunteer time.
Reacted by Chris, Árni Már Jónsson, Konrad Gądek, TheDubliner, Kai Ase Siren, Matthew Gamble, Gösta, Rudo Terry, Paulo S. Costa and red8888
importinspectimportsiximporttypesfrominvoke.tasksimportTask, NO_DEFAULTifsix.PY3:
fromitertoolsimportzip_longestelse:
fromitertoolsimportizip_longestaszip_longestdefpatched_argspec(self, body):
""" Returns two-tuple: * First item is list of arg names, in order defined. * I.e. we *cannot* simply use a dict's ``keys()`` method here. * Second item is dict mapping arg names to default values or `.NO_DEFAULT` (an 'empty' value distinct from None, since None is a valid value on its own). """# Handle callable-but-not-function objects# TODO: __call__ exhibits the 'self' arg; do we manually nix 1st result# in argspec, or is there a way to get the "really callable" spec?func=bodyifisinstance(body, types.FunctionType) elsebody.__call__ifsix.PY3:
sig=inspect.signature(func)
arg_names= [kfork, vinsig.parameters.items()]
spec_dict= {}
fork, vinsig.parameters.items():
value=v.defaultifnotv.default==sig.emptyelseNO_DEFAULTspec_dict.update({k: value})
else:
spec=inspect.getargspec(func)
arg_names=spec.args[:]
matched_args= [
reversed(x) forxin [spec.args, spec.defaultsor []]]
spec_dict=dict(zip_longest(*matched_args, fillvalue=NO_DEFAULT))
# Pop context argumenttry:
context_arg=arg_names.pop(0)
exceptIndexError:
# TODO: see TODO under __call__, this should be same typeraiseTypeError("Tasks must have an initial Context argument!")
delspec_dict[context_arg]
returnarg_names, spec_dictTask.argspec=types.MethodType(patched_argspec, Task)
save above code to hotfix.py and import it when you need.
Activity
Allow annotations to be used for Python 3 Tasks
Allow annotations to be used for Python 3 Tasks
Allow annotations to be used for Python 3 Tasks
Allow annotations to be used for Python 3 Tasks
FranklinChen commentedon Apr 13, 2018
Any word on this? I use Python 3 with
mypyfor types and just realized that I'm blocked on usinginvokeright now.bitprophet commentedon Apr 19, 2018
Thanks for the bump, I'll take a look at #373 soon which seems to be the main patch around this.
@FranklinChen If you can check out that PR's branch and confirm it works against latest master & solves your particular flavor of the issue, that'd be a big help!
FranklinChen commentedon Apr 19, 2018
@bitprophet Yes, I am actually using the fork at #373 and it works for me.
nathanielford commentedon Sep 13, 2018
Hi! I'm still seeing this with version
1.1.1.I am not sure what might need to be done to diagnose or resolve it from my end. Is anyone else still running into this?
SantjagoCorkez commentedon Oct 9, 2018
@nathanielford Just run into this too. As it says in the exception itself, replaced
inspect.getargspecat invoke/tasks.py withinspect.getfullargspecmanually. Works for me.nathanielford commentedon Oct 9, 2018
@SantjagoCorkez I may not be understanding you correctly, but I don't think it'll work for us to manually fork the invoke library code. If I get a chance, though, I'll see if I can put a PR together to submit here, unless the maintainers already have one ready? I'm a little unclear on where they believe the state of the bug to be, given the merged PR.
SantjagoCorkez commentedon Oct 10, 2018
@nathanielford Well, the bug is more than 2 years old at the moment. Developers still didn't apply a patch that is proposed by the exception message itself. So, they don't care. You're on your own.
JesseTG commentedon Nov 15, 2018
@bitprophet Hello? How's it going?
fix pyinvoke#357 - ValueError for annotated tasks
20 remaining items
coilysiren commentedon Jun 24, 2021
Heya, it looks like this still isn't fixed? Any idea what the blockers are? It's been years
nathanielford commentedon Sep 17, 2021
@karan-webkul Python 2 is at EOL, and while everyone using this package already is avoiding using type hints because it does not support it, this issue is around the fact that we'd like to both use the package and type hints, like other modern Python 3 apps.
davidalo commentedon Sep 23, 2021
@zelo 's workaround works pretty well, any update on this to avoid this workaround?
emersonmx commentedon Oct 2, 2021
I do something similar to what @dralshehri showed, but for the function.
bitprophet commentedon Oct 8, 2021
I'll revisit this after dropping Python 2, which is one of the next things on the roadmap. Should make it much easier to apply/fix overall.
sbienkow-ninja commentedon Jan 13, 2022
@exhuma I decided to do something like this, just automatically. I created a wrapper around
@task, which simply creates wrapper function with modified signature, where the annotations are removed. Since there's plan to add proper support for those tasks in invoke at some point, it should be easy to just replace it withfrom invoke import taskinstead and have it working.Usage:
Jma353 commentedon Feb 11, 2022
@bitprophet - have you folks started working on this support? I'd be interested in contributing this support if not!
neozenith commentedon Mar 16, 2022
@bitprophet - I would also like to contribute. I have previously worked on
vcrpyas a maintainer for a year and my new role is seeing me needinvokea lot and I would like to put the time and energy into breathing new life into keepinginvokerelevant. I couldn't see aCONTRIBUTING.mdto get a gist of who to contact about becoming a maintainer.In particular I am coming from a few years over in Typescript where projects like
lernaandnpm workspacescoupled with the factnpmhasscriptsbuilt into theirpackage.jsonI feel this is lacking in the Python ecosystem.poetryis about to launchv1.2.+which allows plugins and I think combiningpoetryandinvokeis a really awesome combination especially for multi-project mono-repos.Especially as a consultant I can provide packages of prebaked tasks similar to the
invocationsproject for our clients to get their dev workflows started.If there is a gitter channel hit me up or DM me on LinkedIn or twitter.
neozenith commentedon Mar 23, 2022
For those playing along at home I am now working on issue and PR triage to help catch up on the backlog that has accumulated.
https://bitprophet.org/projects/#roadmap
The big tasks that are being worked on are:
Also
invokeis part of thefabricandparamikoecosystem and they need equal amounts of love too.But I am doing my best over the coming weeks and months to help close the items that will have the greatest impact for our limited cognitive bandwidth and volunteer time.
nnnewb commentedon Sep 19, 2022
another workaround here.
monkey patch #373
save above code to
hotfix.pyand import it when you need.adamcunnington-mlg commentedon Nov 20, 2022
bitprophet commentedon Jan 6, 2023
2.0.0 will be out soon & is now using
inspect.signature!