Repository navigation
Description
Related problem
Add "traditional" function call syntax as a solution to the "flag-passing" problem:
def func [--bar: int, --flag] { }
def spam [--bar: int, --flag] {
func # How to pass --bar and --flag forward?
}
Currently, the only solution is to use if or match to go through all the combinations which quickly gets out of hand with growing number of parameters.
Describe the solution you'd like
Allow "traditional" function call syntax known from other languages:
func(bar: $bar, flag: $flag)
If the parameters are named the same, you could use the following shorthand (inspired by https://github.com/SerenityOS/jakt):
func($bar, $flag)
Describe alternatives you've considered
This solution intentionally does not provides fully dynamic variable-length arguments in the style of kwargs known from Python. "kwargs"-like functionality would bypass signature type checking and it also tends to produce less readable APIs turning the signature into a black box. If you need a fully dynamic parameter, you can pass a record.
For externals, you can use newly allowed blocks to extern (#8956). The variable-length args are stored as strings under $rest which makes creating custom wrappers around externals much easier.
We could also use = instead of ::
func(bar: $bar, flag: $flag)
vs.
func(bar = $bar, flag = $flag)
I might lean towards : here.
A possible caveat:
func($bar, $flag)
vs.
func ($bar, $flag)
In the second case, it would try to call func with one subexpression arg which might produce strange errors.
Additional context and details
The function call syntax also allows nice inlining of calls into expressions: 3 + add-ten(7) + 20 vs. 3 + (add-ten 7) + 20
Activity
cumber commentedon May 20, 2023
Given that nushell generally does whitespace-separated arguments rather than C-like arguments, using C-like syntax for this one thing feels a little "off" to me. The
func($bar, $flag)vsfunc ($bar, $flag)caveat is a manifestation of this infelicity.In a way the
(bar: $bar, flag: $flag)part of the syntax looks rather like a funny way of writing a record:{ bar: $bar, flag: $flag }. So maybe a more fitting way of doing this would be to have special syntax for applying a command to a record. Something like:Some sort of special syntax (like
@) would be required to distinguish this apply-to-record feature from applyingfuncto a single positional argument which happened to be a record. (If the "special syntax" we use is to swap the braces for parentheses rather than adding an operator or keyword, we get back to the "traditional function call syntax", so if we stop here my suggestion is merely bikeshedding the syntax)But I wonder, if we see this as an ability to apply a command to a record, rather than merely as unusual syntax required for passing flags, would it be possible to do this with a runtime record value rather than only a record-literal? E.g. would it be possible to implement a feature that would allow:
Or even:
I would expect the fields accessed in
$argsto be determined by the signature forfunc, and a runtime error if$argsturns out not to have the required fields (or not to be a record). Much like the behaviour of this:So if it's possible to tell the signature of
funcat parse time, this wouldn't even necessarily require any more runtime type checking than things likeextract-some-fieldsalready do. And yet it would provide a lot of the flexibility of python-like**kwargsapplication (not receiving**kwargs) while (I think) remaining within the existing style and principles of Nushell.But if only a static version with record-literals would be possible, then maybe the "traditional-function-call" idea is indeed better, as looking like "real" records could mislead people into trying to use it more dynamically.
kubouch commentedon May 21, 2023
These are good points. A problematic aspect of the proposed syntax are:
or
???
2. Space being significant:
func(bar: $bar, flag: $flag)vsfunc (bar: $bar, flag: $flag)being two completely different things.The applying record method is interesting. One important part of the design is to be able to shorten
func(bar: $bar, flag: $flag)tofunc($bar, $flag)BUT WHAT IF we allowed this shortening for records in general, e.g.,let record = { $bar, $flag }?cumber commentedon May 21, 2023
@kubouch I would definitely use such shorthand syntax for records in general, yes!
cumber commentedon May 21, 2023
@kubouch I suppose using an operator rather than parentheses to indicate that the command is being applied to an argument list rather than normal arguments (whether it's a record or special-purpose argument list syntax) would help the multi-word command case as well? At least I think I would be less confused to see
than
(Especially if there is no permitted space between the
funcand the(). My brain just has an easier time reading the operator as "lower precedence" than the grouping ofspamandfunc.I don't know whether it would be possible to extend that to allow partially applying a command to some arguments normally and then filling in the rest from a record, but that would be useful too. e.g.
I'd imagine that would be added implementation complexity that shouldn't be in the first draft, but it would be cool if it eventually developed that way. It's still all theoretically determinable what it means just from knowledge of the signature of
func, I think. Maybe some tricky spots with$restarguments. The other way around (partially applying to a record and then filling in more arguments via normal application) would be more problematic, as you'd have to also know the contents of the record to tell how to interpret any following positional arguments.kubouch commentedon May 21, 2023
I think it could all be a record because all signature parameters are named. For example:
would be called as
with the traditional syntax or
with your proposed syntax.
The problem with the
@syntax is that it might not be obvious what it means. Imagine seeing this when you just learned about Nushell:Is it clear enough? To me, definitely less clear than
spam($bar, flag: $x). Maybe we could find something more intuitive? For example @pingiun proposedapplycommand some time ago in #7758 (comment) that would look like this:amtoine commentedon May 21, 2023
i think i like the more shell-like feeling of
or
compared to the standard calling syntax
🤔
amtoine commentedon May 21, 2023
other ideas to replace
@foo <- { ... }foo ^ { ... }foo % { ... }(i prefer
@😕)kubouch commentedon May 21, 2023
One benefit of the functional syntax we'd lose with is being able to use it directly in expressions without wrapping into
():kubouch commentedon May 21, 2023
If we allow "traditional namespace syntax" then, we could write
which would solve the subcommand naming problem.
Just throwing ideas here.
amtoine commentedon May 21, 2023
these are also nice 🤔
cumber commentedon May 21, 2023
Yeah,
@was a suggestion with very little thought behind it. It could be a different operator, or a keyword (likeapply), or any other syntax.The meat of my idea was to encode the argument list as a standard record, so that the argument list as a whole is a first-class value and you can use any existing tools for working with records to assemble an argument list. That's the main downside of the traditional call syntax; it's dedicated syntax for associating parameter names with argument values, instead of piggy-backing on the syntactic structures we already have for associating names and values.
Also, I think it's easy to overestimate how intuitive the traditional call syntax. It only seems that way because it's common elsewhere, so a lot of people already know it. That's not really inherently intuitive though, it's relying on users already having memorised the notation; everything is intuitive once you've memorised it. It wouldn't be obvious to anyone for whom nushell is their first programming language. A keyword like
applyhas a claim that the word "apply" communicates some of the idea, but using symbols like()(or@) doesn't; it's just something you have to learn about and memorise.There's even an argument to be made that the parenthesis-based syntax might be less intuitive than some other arbitrary symbol, since nushell already uses parentheses for other purposes. It's easier for users to learn what syntactic structures do if they always do the same thing (and it prevents issues like needing to use whitespace to distinguish
func ($bar)fromfunc($bar)).cumber commentedon May 21, 2023
Why couldn't that work with an operator? It's just a matter of giving it a high enough precedence isn't it?
4 remaining items
kubouch commentedon May 24, 2023
func x y --flagis again obvious to anyone who has ever interacted with a CLI tool :-).If you have a command
printfoothat takes no parameters, then in10 + printfoo + 20the "printfoo" is still interpreted as a string. That's how the language currently works that bare words in value positions are interpreted as strings. You could enforce a command call with10 + printfoo() + 20with the "traditional" syntax. The@syntax would need something similar:10 + printfoo @ {} + 20. Maybe would be clearer without the spaces:10 + printfoo@{} + 20, not sure.Also, going back to your original message, the records would need to be record literals, or maybe
const, but you wouldn't have the full flexibility of Python's kwargs. Even havingconstrecord could create confusing situations:It could make the code less readable. Fully dynamic kwargs were recently dismissed as they can create very confusing APIs. If you need a full Python-like kwargs, you could just pass the record itself as a parameter.
It's an interesting idea, though. The traditional call syntax still suffers from the space problem (
foo($bar)vsfoo ($bar)), so no solution is without drawbacks.cumber commentedon May 25, 2023
"100 lines later, what is $foo I forgot" goes for any variable, it has nothing to do with this specific usage. You can't avoid confusion for users by denying them any features that could possibly be confusing! Not unless you give them a system that does nothing.
I saw that having a kwargs-style parameter for receiving arguments had already been discussed and rejected, but that's not what I'm proposing. Python has two syntactic features you might call "kwargs" and they're actually independent; don't confuse them.
Receiving kwargs would mean the function is defined like
def foo [**kwargs] {...}and then called with the ordinaryfoo --x=13 --y=hellosyntax, and insidefooyou would have$kwargsbound to{ x: 13, y: "hello" }. I agree this would be a bad idea; it means any call has to be closely coupled to the implementation of the command (because that's what determines which parameters it will examine in the$kwargsrecord, which is its actual interface), basically requiring fragile and hard-to-understand code. And as you point out, taking an untyped record parameter is equivalent anyway. Any API that needs this flexibility can already be written in Nushell today. Receiving kwargs would only provide the minor syntactic shortcut of letting you fill a dynamic structure (a record) from a static argument list.--foo=1 --bar=$whatevercontains the exact same information as{ foo: 1, bar: $whatever }, and it's only 3 characters shorter!What I'm proposing is the other way around. I want kwargs-style specification of arguments I'm passing, not ones I'm receiving. I want to work with things defined like
def foo [x : int, y : string] {...}where the arguments it takes are fully specified as normal, with no confusing dynamic API. I just want callfooasfoo @ $argsif$argis of typerecord<x: int, y: string>. This would give me flexibility to dynamically assemble a call to an ordinary pre-defined command, something that is a new capability (unlike receiving kwargs). The alternative is writing a wrapper for every command I want to call this way that takes all the same parameters as fields of a single record and then properly extracts them and passes them as normal arguments; this can be a lot of extra boiler plate if the command has a lot of parameters, and it has to be updated to stay in sync. Passing kwargs allows us to avoid this extra fragile code.Note you can already do this in Nushell today:
And you get an error if the runtime value of
kwargsdoesn't have the correct fields. So it clearly is possible for Nushell to check a dynamic record against the signature of a command, without it being a const. All that is required is a way to say "match a command's signature against the fields of a record instead of a hard-coded list of arguments". That would give the ability to use this flexibility on all existing commands, instead of requiring them all to be rewritten to take a single record.The traditional-style function call syntax is just another way of writing a static list of arguments. If it weren't for the fact that the CLI style way of writing a static list of arguments doesn't provide any way to pass the value of a boolean flag from a variable, then implementing the traditional syntax would gain absolutely no capability. (Even the ability to avoid parentheses around a call in the middle of an expression isn't really a benefit, since you need to add parentheses around the argument list in the call instead!
10 + printfoo() + 20is exactly the same characters as10 + (printfoo) + 20, just in a different order). If that very minor capability is all we're getting, I personally would prefer we just fixed it so that--flag=$varworked, instead of boolean flags ignoring an explicitly passed value. That would be a much smaller change, no dual-syntax to confuse users, no space issue, no drawbacks that I can think of at all.dedebenui commentedon Oct 11, 2023
I'm on board with the
@syntax. It's a bit tricky to work with positional arguments though since users are not expected to know their internal names. How about flipping the@syntax to work more like a pipe?This has two benefits in my view:
If
@takes precedence over|, working in conjunction with normal pipes is fine too. Putting all together:bew commentedon Nov 30, 2023
Edit: reading this thread made me think about all of this, but it might be a bit too general for this issue and could benefit from a separate issue, or be split. Tell me if I need to move/split this
Instead of
@what about using the new spread operator?Where we could do:
func ...{$flag1, $flag2} ...[positional params] # or more complex/realistic: def some-git [ --colors --no-pager --git-dir: string ...rest # (could even allow $in?) ] { mut global_opts = { $git_dir $no_pager } # (with a list, order would be retained, but we loose easy access (/ability to set) an option, like in the if branch below) if $colors { $global_opts.c = "color.ui=always" } git ...$global_opts commit ...$rest } some-git --no-pager --colors ./some/file --dry-run # => git --no-pager -c color.ui=auto commit ./some/file --dry-run some-git --git-dir=/custom.git ./file1 ./file2 # => git --git-dir=/custom.git commit ./file1 ./file2The spread operator would learn the ability to apply record/lists to cmd calls
(in addition to be usable in records, lists, ...)
WDYT?
Might be far-fetched, but here's a
smallbrain dump to go further:An issue with the above idea is that order of arguments isn't preserved/guaranteed.
To represent a list of (ordered) arguments (which can be either flags, options or positional args) I'm thinking we could have a new kind of collection that can be used to store that ordered list of args, with easy access to any arg like a record, with ability to append new items like a list, and when using the spread operator on it it would expand to the full list of args..
More ideas... This looks like the basis of a kind of mini-framework to define structured wrappers to many kind of programs
In addition we could add dedicated types (or special kind of records with a set of known keys) for each kind of arg:
option: like--work-tree=/foo,-c hello(both formats should be supported as some programs don't/only support=between option name and value) or-vvvvflag: like--verbose,--no-pageror-V(
flagcould be a special case ofoptionwith no value? or a forced boolean value?)arg: likecommit,/pathor"some text"(the most generic argument item, all others types should resolve to 0+
args)These types could be used to define new args on-the-fly without having to define them in a
defargs list.Sample syntax ideas:
WDYT?
Thinking about this even more...
This could be a kind of fully detailed declarative arguments definition for nushell functions!
This basic nushell function:
Could be a shortcut for another, more flexible syntax:
This could open-up the ability to share a set of args between multiple functions, without having to re-write it, maintain duplicated definitions/documentations/completion/...
=> more composable
WDYT?
Well this blew up, if you're not allergic to these kind of ideas I'll probably make a separate issue/RFC with this... (or multiple?)
amtoine commentedon Nov 30, 2023
@bew
i just tried and the following already works without the spread operator 😋
bew commentedon Dec 3, 2023
Well that would be a solution for the first part 🤔
Why does it work? Does the parser detects if the target command is an external one?
Although to me this is not something that should happen automagically.
From a readability point of view it doesn't feel right, because the implicit spread is not predictable, unless you know that the command you're passing this into is an external command.
Having to explicitly spread the args would be more predictable and easy to read and understand.
amtoine commentedon Dec 3, 2023
@bew
yup, i think the parser detects that!
we are currently adding a spread operator to Nushell, see #11006 and #11144, and we might reconsider the automatic spreading for externals at some point 👍
bew commentedon Dec 3, 2023
Allright 👌
What about the rest of my brain dump, do you have thoughts on this kind of mini-framework to define and manipulate args in a structured way? 🤔
amtoine commentedon Dec 3, 2023
not sure i see what you mean 😕
ohh, the big post of yours above?! let me have another look 😉
amtoine commentedon Dec 3, 2023
@bew
interesting idea but i'm not sure what hole in the current arg syntax these new types would fill 😕
i must have missed it but it looks to me like all the more complex examples using
arg flagcan already be done natively?kubouch commentedon Nov 26, 2024
Because the
()syntax looks too much like a subexpression, I think adding this would add too much confusion. The “flag-passing” problem is largely solved by allowing flags to take boolean parameters, like--flag=$value.Let's try not to have two ways to do the same thing, I think we can close it for now.