GithubHelp home page GithubHelp logo

prasxanth / defstruct Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 18 KB

Simple class declaration with automatic property definitions and type validation

License: BSD 3-Clause "New" or "Revised" License

Hy 99.39% Python 0.61%

defstruct's Introduction

defstruct

Simple class declaration with automatic property definitions and type validation

Installation

Install using setup.py (--user is optional)

python3 setup.py install --user

or in development mode,

python3 setup.py develop --user

API

This package provides the defstruct macro for simple class declarations. It aims to reduce boilerplate code by automatically defining properties. It also provides type validation through pydantic.validate_arguments.

Usage

The typical use of defstruct resembles the simplest form of dataclasses, attrs or pydantic,

(require [defstruct.defs [defstruct]])

(defstruct struct []  (^(of float) data 
                        ^int x 
                        &optional ^(of str) [s None]
                        &kwonly ^float [f 0.5]))
(setv test-struct (struct 0.3 2 "pqr"))
test-struct
(struct :data 0.3 :x 2 :s 'pqr' :f 0.5)

As seen above, the __repr__ method is provided for displaying a nicely formatted string representation of defstruct objects.

defproperty

Properties associated with each input are defined automatically. The convention is to represent "internal" (private) class variables by surrounding them with double underscores. So the variable data in the struct above would have the following, automatically defined, property

(with-decorator property
  (defn data [self]
    return __self.data__))

The objective is to have read-only properties, so setters are not automatically defined.

A defproperty macro is provided for defining custom properties,

(defmacro defproperty [attribute &optional docstring &rest body]
  `(with-decorator property
     (defn ~(HySymbol attribute) [self]
       ~docstring
       (do ~@body)
       (return (getattr self (+ "__" ~attribute "__"))))))

defproperty is used to automatically define the properties in defstruct.

Customization

defstruct is flexible allowing for definition of custom properties, methods and even changing the automatically defined properties.

(require [defstruct.defs [defproperty]])

(defstruct struct-custom [] (^(of float) data 
                              ^(of int) x 
                              ^(of str) doc) 
           
    "Documentation for custom struct."

    (defproperty "info"
        (setattr self "__info__" (+ self.data self.x))))
(setv test-struct-custom (struct-custom 2.0 3 "abc"))
test-struct-custom
(struct_custom :data 2.0 :x 3 :doc 'abc' :info 5.0)

A __post-init__ method allows for implementating functionality after __init__,

(defstruct struct-post-init [] (^(of float) data ^(of int) x ^(of str) doc) "some doc"

    (defproperty "info")

    (defn __post-init__ [self]
      (setattr self "__info__" (+ self.data self.x))))
(setv test-struct-post-init (struct-post-init 2.0 3 "abc"))
struct-post-init
(struct_post_init :data 2.0 :x 3 :doc 'abc' :info 5.0)

Of course one the __init__ method can be overwritten if needed.

Type validation

Basic type validation is provided by pydantic.validate_arguments,

(setv test-struct-type-validate (struct 0.3 ["wrong type"] "pqr"))
�[0;31mTraceback (most recent call last):
  File "/home/prashanth/.local/lib/python3.6/site-packages/calysto_hy/kernel.py", line 145, in do_execute_direct
    eval(exec_code, self.locals)
  File "In [28]", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pydantic/decorator.py", line 39, in wrapper_function
    return vd.call(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/pydantic/decorator.py", line 132, in call
    m = self.init_model_instance(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/pydantic/decorator.py", line 129, in init_model_instance
    return self.model(**values)
  File "/usr/local/lib/python3.6/dist-packages/pydantic/main.py", line 406, in __init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Init
x
  value is not a valid integer (type=type_error.integer)

�[0m

Tests

Ensure hy is in the executable path. Tests are written using the hyprovo library. Run the tests.hy command line script from inside the tests directory,

./tests.hy

A log file with the start timestamp will be created in the logs subdirectory.

defstruct's People

Contributors

prasxanth avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.