Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

4 Commits

Repository files navigation

Ext-Class

Adding fields/methods to existing classes.

A Python approach to method/field extensions like in C# and Kotlin, probably the closest.

How to use

pip install extclass 

Suppose you have a Person class in an already installed package:

fromdataclassesimportdataclass@dataclassclassPerson:
first_name: strlast_name: str

Then, you could add an extra method outside the source package somewhere in your project.

fromextclassimportextension@extensionclassPersonExt(Person):
age: int=10deffull_name(self):
returnf'{self.first_name}{self.last_name}'

With the help of the @extension decorator, new field age and full_name are added to the origin Person class. You can just call them as usual.

if__name__=='__main__':
person=Person(first_name='rick', last_name='sanchez')
print(person.full_name())
print(person.age)

which print as

rick sanchez
10

However, the IDE cannot know the dynamic informations of the added attributes, so there would be a warning message:

Unresolved attribute reference 'full_name' for class 'Person' 

And no autocomplete for the attributes in the IDE.

To handle the warnings also enabling autocomplete, you can simply typing.cast the origin object to the new extended type.

fromtypingimportcastperson=cast(PersonExt, person)

In this case, person is still the old object but only marked as the extended type in order to cheat the IDE for better programming experiences.

No Override

Same method/field name in the extending class will not affect the origin class. So this package is very safe in any use-cases.

Pydantic issues

Classes of pydantic.BaseModel can only attach new methods. Dynamic fields are internally forbidden by the pydantic package. So please do NOT extend fields for pydantic models, or an AttributeError would be raised during runtime.

Full examples

See test.py

About

A Python approach for class extensions like C# and Kotlin

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages