Skip to content

Commit

Permalink
cleaner display of ArrayLike types in docs
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerflex committed Jul 6, 2023
1 parent 9712bbf commit ca23dfe
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- Point-like objects correctly appear as single points using `plt.scatter`.
### Changed
- Source validation happens before simulation upload and raises an error if no source is present.
- Cleaner display of `ArrayLike` in docs.

## [2.3.0] - 2023-6-30

Expand Down
24 changes: 24 additions & 0 deletions tests/test_components/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,30 @@ class MyClass(Tidy3dBaseModel):
my_obj.json()


def test_array_like_field_name():
class MyClass(Tidy3dBaseModel):

a: ArrayLike # can be any array-like thing
b: constrained_array(ndim=2) # must be 2D
c: constrained_array(dtype=float) # must be float-like
d: constrained_array(ndim=1, dtype=complex) # 1D complex
e: constrained_array(ndim=3, shape=(1, 2, 3)) # must have certain shape
f: ArrayLike = None

fields = MyClass.__fields__

def correct_field_display(field_name, display_name):
"""Make sure the field has the expected name."""
assert fields[field_name]._type_display() == display_name

correct_field_display("a", "ArrayLike")
correct_field_display("b", "ArrayLike[ndim=2]")
correct_field_display("c", "ArrayLike[dtype=float]")
correct_field_display("d", "ArrayLike[dtype=complex, ndim=1]")
correct_field_display("e", "ArrayLike[ndim=3, shape=(1, 2, 3)]")
correct_field_display("f", "Optional[ArrayLike]")


def test_hash():
class MyClass(Tidy3dBaseModel):

Expand Down
10 changes: 7 additions & 3 deletions tidy3d/components/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,16 @@ def constrained_array(

# note, a unique name is required for each subclass of ArrayLike with constraints
type_name = "ArrayLike"

meta_args = []
if dtype is not None:
type_name += f"_dtype={dtype}"
meta_args.append(f"dtype={dtype.__name__}")
if ndim is not None:
type_name += f"_ndim={ndim}"
meta_args.append(f"ndim={ndim}")
if shape is not None:
type_name += f"_shape={shape}"
meta_args.append(f"shape={shape}")
type_name += "[" + ", ".join(meta_args) + "]"

return type(type_name, (ArrayLike,), dict(dtype=dtype, ndim=ndim, shape=shape))


Expand Down

0 comments on commit ca23dfe

Please sign in to comment.