Skip to content

Commit

Permalink
fix(python): self as property name leads to assignment error (#1330)
Browse files Browse the repository at this point in the history
When a property with the name `self` exists in a class, it leads to
a runtime error. This slugifies the conventional `self` parameter
as needed to avoid this problem without compromising on the
developer experience.

---

By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license].

[Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0
  • Loading branch information
skorfmann authored May 25, 2020
1 parent 7e9250c commit a877f34
Show file tree
Hide file tree
Showing 22 changed files with 1,859 additions and 678 deletions.
14 changes: 14 additions & 0 deletions packages/@jsii/python-runtime/tests/test_compliance.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@
AnonymousImplementationProvider,
UpcasingReflectable,
)
from jsii_calc.python_self import (
ClassWithSelf,
ClassWithSelfKwarg,
)
from scope.jsii_calc_lib import IFriendly, EnumFromScopedModule, Number
from scope.jsii_calc_lib.submodule import IReflectable, ReflectableEntry

Expand Down Expand Up @@ -1182,3 +1186,13 @@ def test_load_submodules():
from jsii_calc.submodule import nested_submodule
import jsii_calc.submodule


def test_parameter_named_self_ClassWithSelf():
subject = ClassWithSelf('Howdy!')
assert subject.self == 'Howdy!'
assert subject.method(1337) == '1337'


def test_parameter_named_self_ClassWithSelfKwarg():
subject = ClassWithSelfKwarg(self='Howdy!')
assert subject.props.self == 'Howdy!'
25 changes: 25 additions & 0 deletions packages/jsii-calc/lib/compliance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,31 @@ export class PythonReservedWords {
public yield() {}
}

// "self" is technically not a keyword in Python. It's the conventional name of
// the "this instance" reference. We can slugify this to our heart's content,
// without much impact on the developer experience - but it needs to happen!
export namespace PythonSelf {
export class ClassWithSelf {
public constructor(public readonly self: string) { }

public method(self: number): string {
return self.toString();
}
}

export class ClassWithSelfKwarg {
public constructor(public readonly props: StructWithSelf) { }
}

export interface StructWithSelf {
readonly self: string;
}

export interface IInterfaceWithSelf {
method(self: number): string;
}
}

export interface UnionProperties {
readonly foo?: string | number;
readonly bar: AllTypes | string | number;
Expand Down
Loading

0 comments on commit a877f34

Please sign in to comment.