Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GetAttribute trait #475

Open
mtshiba opened this issue Dec 26, 2023 · 0 comments
Open

Add GetAttribute trait #475

mtshiba opened this issue Dec 26, 2023 · 0 comments
Labels
enhancement New feature or request RFC New specifications of Erg

Comments

@mtshiba
Copy link
Member

mtshiba commented Dec 26, 2023

By nature, Python objects do not determine their instance attributes until runtime.
For example, a pandas.DataFrame reads a file at runtime and generates attributes.

Currently Erg provides __getattribute__ to access such dynamically generated attributes, but type information is lost.

By adding the GetAttribute trait, we allow customization of dot access. Of course, this is not recommended, but may be necessary for Python API static typing.

"""
This trait permits override of dot access.
Unless you are a developer of a library, you should not use this.
"""
GetAttribute = Trait {
    """
    When attribute resolution fails, Erg attempts to derive the attribute type using this function if the target type implements Dot.
    """
    GetAttributeType: (Attr: Str) -> Type or NoneType
}

C = Class()
C|<: GetAttribute|.
    GetAttributeType Attr =
        match Attr:
            "foo" -> Int
            _ -> None
C.
    bar = 1
    __getattribute__(self, attr) =
        if attr == "foo", do:
            C.__getattribute__::return 1
        super().__getattribute__(attr)

c = C.new()
assert c.bar == 1
assert c.foo == 1

Once GetAttribute and compile-time functions are implemented, it will be possible:

# compile-time function
FrameShape Path =
    src = open(Path).read()
    ...
    columns = ...
    index = ...
    (columns, index)

DataFrame = (Columns: {Str: Type}, Index: {Str: Type}) -> Type
DataFrame(Columns, _)|<: GetAttribute|.
    GetAttributeType Attr = Columns.get Attr
DataFrame(_, _).
    read_csv!: (|S: Str|(path: {P}) => DataFrame *FrameShape(P)) \
        and ((path: Str) => DataFrame _, _)
@mtshiba mtshiba added the enhancement New feature or request label Dec 26, 2023
@mtshiba mtshiba added the RFC New specifications of Erg label Jan 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request RFC New specifications of Erg
Projects
None yet
Development

No branches or pull requests

1 participant