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
Properties with accessor and mutator methods #2219
Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Languageparser, language semantics
We should be able to do something along these lines
classfoo
{
[string]$bar {
get {
#getter code
}
set {
# setter code
}
}
}
Reacted by Ilya, Staffan Gustafsson, Georgi Ivanov, Michael Klement, TimNFL, Joel Bennett, antiufo, Thomas Nieto, Henry Gabryjelski, huglovefan and 8 more
Are we sure this is the syntax we want?
How does it interact with existing syntax?
What about the following:
# readonly property
class A {
[int]$i {get;} # ??? explicit backing property
A($i){
$this.i = $i
}
}
# getter setter: do we have a private backing field?
class A {
[int]$i {
get {
# what here?
}
set {
if ($value -lt 0) {throw 'x'}
$i_ = $value #field derived from propname ? or 'private [int] $i_'?
}
} = 4 # default value
}
There's been a lot of work done i C# to handle a lot of these cases, and I think it is worth to take some time to think through what we want to achieve here. And I think there is a lot to learn from other languages here.
Let us list and discuss the scenarios before jumping to implementation.
Staffan Gustafsson (@powercode) I am full agree.
Now I am preparing the base for these enhancements. I am on parser step and completed a parser for get/set {...} (Parser error recovery takes a long time).
I can inform you that the original code already does implicit get/set and backing field, and attribute processing.
Now I plan to do as soon as possible a PR with the parser and get feedback. Then do next step and make AST and compile for get/set {...}. If this discussion will adopt new features, then I can always add them immediately or in subsequent PRs because the base will be ready.
It seems the code is ready for testing.
I remember that Jason Shirk (@lzybkr) spoke about the specifics of these tests.
Where will we locate these tests? In Scripting.Classes.BasicParsing.Tests.ps1?
Any advise before I begin?
Do it makes sense to make PR now and add tests later?
Sorry, I missed commenting on this. I don't have a strong preference on tests. BasicParsing.Tests.ps1 is probably not the place for anything that tests semantics.
You can submit a PR whenever you like - but if there aren't any tests, of course you'll be asked to add them.
I have this mostly done. Implementation needs some cleaning up, may need some design changes, and still needs tests and semantic checks, but it all works. Aiming to get a PR up this weekend or next.
Ilya (@iSazonov) Hmm looking at your branch now, I don't think these tests have a ton of overlap. Your design is very clever, though I was looking for a more traditional implementation.
Thanks for clarify. I see you point. Your option is easier to implement. I tried it and refused for the same reasons (harder to understand :-) ). In my opinion, this requires more user training and makes more mistakes. Also your option gives users too much freedom and provokes side effects.
In general, I believe that this backfield should appear in an explicit form only when it is really impossible to do without it - but we can.
Seeing a setter that returns feels off. It took me a little bit to get what was happening, and I imagine it would be harder for other folks who aren't as familiar with the behind the scenes. Speculation of course, could just be me.
Also your option gives users too much freedom and provokes side effects.
I think that type of freedom fits well in PowerShell. Even so, I don't think we need to be more strict than C#.
In general, I believe that this backfield should appear in an explicit form only when it is really impossible to do without it - but we can.
I can't think of many instances where I would implement an accessor that fits neatly into that mold. If it's not generated per call (where I wouldn't need backing field) or lazy init then I'm not likely to need accessors. I think your design is a really cool idea, and would be nice to have as an option, though it wouldn't be what I'd default to.
Wow! Really amazing you guys have tackled this. Feel like I'm quite late to this discussion.
I personally found the usage of $PSItem took me a while to understand in the setter example above. The get/set syntax being basically C# I think creates the expectation of C#-like semantics where you have to explicitly create your own backing property if you want something more than just assignment and dereference of a backing field.
The thing is that PowerShell classes don't really have fields — PS class properties with no get or set are equivalent to C# class properties with { get; set; } — so explicit get and set in PowerShell classes only really make sense with non-trivial bodies. But not all getters and setters need backing fields (they might be what EF calls a "computed property"), so $PSItem doesn't apply in all cases (not really a big problem -- this is true in other usages of $PSItem in PowerShell).
I think part of the issue is that having syntax so close to C#'s creates an expectation of everything being like C#, but because .NET has getters and setters baked into it I think the syntax proposed is the most sensible (get { ... } is not unlike begin { ... }). Which basically means I think we should go with Patrick Meinecke (@SeeminglyScience)'s version where $PSItem only applies as the value in a setter.
Thomas Nieto (@ThomasNieto) I stopped working on this awhile ago. The actual code is mostly done if anyone else wants to build off of it. I'm not going to have the spare time for the design debates/probably RFC, so anyone else who wants to take this on is welcome to.
Forgive my ignorance of Powershell internals, but on the face of it could we not make use of the facts that (a) (hidden) get_ and set_ methods are automatically created for each property; (b) it is syntactically allowed to user-define the same methods, but (c) this seems to have no effect - the user definition does not override the system-generated one. If it did, that would allow as much flexibility as we could want; but I don't know what other consequences might flow from this.
but I don't know what other consequences might flow from this.
Some change would still need to be made to enable that. The biggest consequence is just having to support that forever. Plus you would need some way to annotate that it's for a property, otherwise it would be a breaking change (imagine someone using a snake_case naming convention, while not particularly popular in pwsh it's not unheard of). At that point you might as well add proper language support.
@ SeeminglyScience Thanks for the feedback.
"... otherwise it would be a breaking change...": I agree it's theoretically a breaking change, but in order for it to have any actual impact, someone would need to have written a get_/set_ method and left it there even though it hasn't ever worked (it's been masked by the system version) - not a likely occurrence, I would suggest.
"...having to support that forever...": surely there are lots of instances where a system default can be over-ridden by writing something with the same name; in fact that's more common than the reverse situation. What is different here?
Thanks for your patience.
@ SeeminglyScience Thanks for the feedback.
"... otherwise it would be a breaking change...": I agree it's theoretically a breaking change, but in order for it to have any actual impact, someone would need to have written a get_/set_ method and left it there even though it hasn't ever worked (it's been masked by the system version) - not a likely occurrence, I would suggest.
I'm thinking it's not too unlikely that some folks happened to name a method get_something in the same way one might name a method invoke_the_thing.
"...having to support that forever...": surely there are lots of instances where a system default can be over-ridden by writing something with the same name; in fact that's more common than the reverse situation. What is different here?
So ideally it would be implemented inline, so you don't have to define a property and then separately define it's getters and setters as individual methods. If the proposed workaround were implemented then it would need to continue to be supported even after the ideal solution is also implemented.
...not too unlikely that some folks happened to name a method get_something...
So you're suggesting (are you?) that this might happen when there isn't a property called 'something'; and later the 'something' property gets added, and attempting to access it behaves oddly. That might be puzzling, but it doesn't actually break anything that worked before. Incidentally, I suppose I'm assuming that accessing a property via dot notation gets translated to a get_/set_ method call (because that's probably how I would do it, and the two behave the same at the moment); but I don't know whether that is true.
...ideally it would be implemented inline...
Agreed; and I take the point that there might be strange consequences if a user used both techniques on the same property. If necessary this could either be prevented as invalid syntax, dealt with on a 'defined priority' basis (like function definitions in different scopes), or just treated like other duplicate function definitions, i.e. "last one wins".
Incidentally, I made the suggestion simply because the good work you did seems to be in limbo for want of someone to take it forward, and I thought this might be related to the perceived complexity of your solution; so it seemed sensible to ask "what is the simplest thing that might work?" - and that is what came to mind.
what became of the plan to implement this feature for classes? I have been asking how to do this in PowerShell on Reddit and StackOverflow and I was reccomended to do it in C#, as PowerShell does not support.
Please consider adding this to PowerShell 7. I dont know any C# and I want to take advantage of this feature in Powershell.
Despite the arguments from Patrick Meinecke (@SeeminglyScience) on the get_/set_ syntax suggestion from JohnFAsh, I (a PowerShell scripter who is not hindered by any C# knowledge 😊) would prefer his syntax suggestion as it has the benefit that it is downwards compatible from Windows PowerShell 5.1 (since PowerShell supports classes) where a C# like mutator will throw an error:
classfoo
{
hidden [string] $_bar
[string] $bar {
get { return'+++'+$this._bar+'+++' }
set { $this._bar="---$PSItem---" }
}
}
Currently throws:
ParserError:
Line |
5 | [string] $bar {
| ~
| Missing ';' or end-of-line in property definition.
This probably means that whenever you try to load a future class that contains accessors-as-proposed in e.g. Windows PowerShell, it will cause an error even it could still be a useful class by means of its (hidden) getter/setter methods or even by creating a "Use-ClassAccessors" cmdlet patch that implements the Script Properties in the concerned class, see StackOverflow: Is it possible to override the Getter/Setter functions in a powershell 5 class?
I'm thinking it's not too unlikely that some folks happened to name a method get_something in the same way one might name a method invoke_the_thing.
I don't think that it is very likely that this will happen (also knowing that you might further narrow the selected method with constrains as parameterless). and even than; so what?: you might get an unexpected something property...
Also; from what I understand other programming languages (JavaScript?, Python?) have a similar implementation.
(It appears to me that PowerShell is already pretty good in avoiding conflicts: it will simply use multiple underscores if the member already exist, e.g.: get__something)
Anyways, I have opened a new issue (#21079) for this as the Enhancement request is still valid and was actually already in a Up-for-Graps state.
Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Languageparser, language semantics
Activity
iSazonov commentedon Nov 21, 2016
sergei (@vors) This is interesting. Could you clarify: this requires not only changes in the parser?
vors commentedon Nov 21, 2016
It will be at least these places:
iSazonov commentedon Nov 21, 2016
sergei (@vors) Thanks! I went thinking :-)
iSazonov commentedon Nov 23, 2016
PowerShellTeam Please assign me.
powercode commentedon Nov 25, 2016
Are we sure this is the syntax we want?
How does it interact with existing syntax?
What about the following:
There's been a lot of work done i C# to handle a lot of these cases, and I think it is worth to take some time to think through what we want to achieve here. And I think there is a lot to learn from other languages here.
Let us list and discuss the scenarios before jumping to implementation.
iSazonov commentedon Nov 26, 2016
Staffan Gustafsson (@powercode) I am full agree.
Now I am preparing the base for these enhancements. I am on parser step and completed a parser for
get/set {...}(Parser error recovery takes a long time).I can inform you that the original code already does implicit get/set and backing field, and attribute processing.
Now I plan to do as soon as possible a PR with the parser and get feedback. Then do next step and make AST and compile for
get/set {...}. If this discussion will adopt new features, then I can always add them immediately or in subsequent PRs because the base will be ready.iSazonov commentedon Jan 11, 2017
It seems the code is ready for testing.
I remember that Jason Shirk (@lzybkr) spoke about the specifics of these tests.
Where will we locate these tests? In Scripting.Classes.BasicParsing.Tests.ps1?
Any advise before I begin?
Do it makes sense to make PR now and add tests later?
lzybkr commentedon Jan 20, 2017
Sorry, I missed commenting on this. I don't have a strong preference on tests. BasicParsing.Tests.ps1 is probably not the place for anything that tests semantics.
You can submit a PR whenever you like - but if there aren't any tests, of course you'll be asked to add them.
SeeminglyScience commentedon May 15, 2019
I have this mostly done. Implementation needs some cleaning up, may need some design changes, and still needs tests and semantic checks, but it all works. Aiming to get a PR up this weekend or next.
Progress in this branch.
iSazonov commentedon May 16, 2019
Patrick Meinecke (@SeeminglyScience) I have very old (2 year) implementation (90%) in the branch https://github.com/iSazonov/PowerShell/tree/classgetset-4
You can (must 😄) grab tests from the branch.
Also I quickly look your implementation and think you could find useful ideas in my branch too.
SeeminglyScience commentedon May 17, 2019
Ilya (@iSazonov) Hmm looking at your branch now, I don't think these tests have a ton of overlap. Your design is very clever, though I was looking for a more traditional implementation.
4 remaining items
iSazonov commentedon May 17, 2019
Thanks for clarify. I see you point. Your option is easier to implement. I tried it and refused for the same reasons (harder to understand :-) ). In my opinion, this requires more user training and makes more mistakes. Also your option gives users too much freedom and provokes side effects.
In general, I believe that this backfield should appear in an explicit form only when it is really impossible to do without it - but we can.
Patrick Meinecke (@SeeminglyScience) Have you other thoughts to share? I think we need to get a community feedback.
/cc sergei (@vors) Jason Shirk (@lzybkr) Michael Klement (@mklement0) Rob Holt (@rjmholt) Dongbo Wang (@daxian-dbw) Steve Lee (@SteveL-MSFT)
SeeminglyScience commentedon May 17, 2019
Seeing a setter that returns feels off. It took me a little bit to get what was happening, and I imagine it would be harder for other folks who aren't as familiar with the behind the scenes. Speculation of course, could just be me.
I think that type of freedom fits well in PowerShell. Even so, I don't think we need to be more strict than C#.
I can't think of many instances where I would implement an accessor that fits neatly into that mold. If it's not generated per call (where I wouldn't need backing field) or lazy init then I'm not likely to need accessors. I think your design is a really cool idea, and would be nice to have as an option, though it wouldn't be what I'd default to.
rjmholt commentedon May 17, 2019
Wow! Really amazing you guys have tackled this. Feel like I'm quite late to this discussion.
I personally found the usage of
$PSItemtook me a while to understand in the setter example above. Theget/setsyntax being basically C# I think creates the expectation of C#-like semantics where you have to explicitly create your own backing property if you want something more than just assignment and dereference of a backing field.The thing is that PowerShell classes don't really have fields — PS class properties with no
getorsetare equivalent to C# class properties with{ get; set; }— so explicitgetandsetin PowerShell classes only really make sense with non-trivial bodies. But not all getters and setters need backing fields (they might be what EF calls a "computed property"), so$PSItemdoesn't apply in all cases (not really a big problem -- this is true in other usages of $PSItem in PowerShell).I think part of the issue is that having syntax so close to C#'s creates an expectation of everything being like C#, but because .NET has getters and setters baked into it I think the syntax proposed is the most sensible (
get { ... }is not unlikebegin { ... }). Which basically means I think we should go with Patrick Meinecke (@SeeminglyScience)'s version where$PSItemonly applies as the value in a setter.ThomasNieto commentedon Jan 12, 2020
Patrick Meinecke (@SeeminglyScience) / Ilya (@iSazonov) good work on this. I've been wanting this feature for a while. Do either of you have any updates on the progress of this feature?
iSazonov commentedon Jan 12, 2020
I feel we don't get a progress until we design in-depth. Minor enhancements do not look so useful.
SeeminglyScience commentedon Jan 12, 2020
Thomas Nieto (@ThomasNieto) I stopped working on this awhile ago. The actual code is mostly done if anyone else wants to build off of it. I'm not going to have the spare time for the design debates/probably RFC, so anyone else who wants to take this on is welcome to.
JohnFAsh commentedon Sep 13, 2021
Forgive my ignorance of Powershell internals, but on the face of it could we not make use of the facts that (a) (hidden) get_ and set_ methods are automatically created for each property; (b) it is syntactically allowed to user-define the same methods, but (c) this seems to have no effect - the user definition does not override the system-generated one. If it did, that would allow as much flexibility as we could want; but I don't know what other consequences might flow from this.
SeeminglyScience commentedon Sep 14, 2021
Some change would still need to be made to enable that. The biggest consequence is just having to support that forever. Plus you would need some way to annotate that it's for a property, otherwise it would be a breaking change (imagine someone using a snake_case naming convention, while not particularly popular in pwsh it's not unheard of). At that point you might as well add proper language support.
JohnFAsh commentedon Sep 14, 2021
@ SeeminglyScience Thanks for the feedback.
"... otherwise it would be a breaking change...": I agree it's theoretically a breaking change, but in order for it to have any actual impact, someone would need to have written a get_/set_ method and left it there even though it hasn't ever worked (it's been masked by the system version) - not a likely occurrence, I would suggest.
"...having to support that forever...": surely there are lots of instances where a system default can be over-ridden by writing something with the same name; in fact that's more common than the reverse situation. What is different here?
Thanks for your patience.
SeeminglyScience commentedon Sep 15, 2021
I'm thinking it's not too unlikely that some folks happened to name a method
get_somethingin the same way one might name a methodinvoke_the_thing.So ideally it would be implemented inline, so you don't have to define a property and then separately define it's getters and setters as individual methods. If the proposed workaround were implemented then it would need to continue to be supported even after the ideal solution is also implemented.
JohnFAsh commentedon Sep 15, 2021
Patrick Meinecke (@SeeminglyScience) Thanks again.
So you're suggesting (are you?) that this might happen when there isn't a property called 'something'; and later the 'something' property gets added, and attempting to access it behaves oddly. That might be puzzling, but it doesn't actually break anything that worked before. Incidentally, I suppose I'm assuming that accessing a property via dot notation gets translated to a get_/set_ method call (because that's probably how I would do it, and the two behave the same at the moment); but I don't know whether that is true.
Agreed; and I take the point that there might be strange consequences if a user used both techniques on the same property. If necessary this could either be prevented as invalid syntax, dealt with on a 'defined priority' basis (like function definitions in different scopes), or just treated like other duplicate function definitions, i.e. "last one wins".
Incidentally, I made the suggestion simply because the good work you did seems to be in limbo for want of someone to take it forward, and I thought this might be related to the perceived complexity of your solution; so it seemed sensible to ask "what is the simplest thing that might work?" - and that is what came to mind.
RalfReddings commentedon Dec 19, 2023
what became of the plan to implement this feature for classes? I have been asking how to do this in PowerShell on Reddit and StackOverflow and I was reccomended to do it in C#, as PowerShell does not support.
Please consider adding this to PowerShell 7. I dont know any C# and I want to take advantage of this feature in Powershell.
iRon7 commentedon Jan 16, 2024
Despite the arguments from Patrick Meinecke (@SeeminglyScience) on the
get_/set_syntax suggestion from JohnFAsh, I (a PowerShell scripter who is not hindered by any C# knowledge 😊) would prefer his syntax suggestion as it has the benefit that it is downwards compatible from Windows PowerShell 5.1 (since PowerShell supports classes) where a C# like mutator will throw an error:Currently throws:
This probably means that whenever you try to load a future class that contains accessors-as-proposed in e.g. Windows PowerShell, it will cause an error even it could still be a useful class by means of its (hidden) getter/setter methods or even by creating a "
Use-ClassAccessors" cmdlet patch that implements the Script Properties in the concerned class, see StackOverflow: Is it possible to override the Getter/Setter functions in a powershell 5 class?I don't think that it is very likely that this will happen (also knowing that you might further narrow the selected method with constrains as parameterless). and even than; so what?: you might get an unexpected
somethingproperty...Also; from what I understand other programming languages (JavaScript?, Python?) have a similar implementation.
(It appears to me that PowerShell is already pretty good in avoiding conflicts: it will simply use multiple underscores if the member already exist, e.g.:
get__something)Anyways, I have opened a new issue (#21079) for this as the Enhancement request is still valid and was actually already in a
Up-for-Grapsstate.