Git Product home page Git Product logo

moshmosh's Introduction

Notes

This project is now under inactive development.

Want to take over? Email me.

Moshmosh

Build Support codecov

An advanced syntax extension system implemented in pure python.

pip install -U moshmosh-base --no-compile

Note that --no-compile is required.

Preview

Working with IPython

You should copy moshmosh_ipy.py to $USER/.ipython/profile_default/startup/.

If this directory does not exist, use command ipython profile create to instantiate.

Some examples about pattern matching, pipelines and quick lambdas:

IPython example 1

Some examples about the scoped operators:

IPython example 2

Working with regular Python files

Import moshmosh in your main module:

Main.py

Then, in mypackage.py, start coding with a pragma comment # moshmosh?, then you can use moshmosh extension system.

Upack.py

Case Study : Pattern Matching

The matching protocol which stems from Python-ideas mailing list is introduced in, which means you can define your own patterns conveniently. The link is here.

# moshmosh?
# +pattern-matching

class GreaterThan:
    def __init__(self, v):
        self.v = v

    def __match__(self, cnt: int, to_match):
        if isinstance(to_match, int) and cnt is 0 and to_match > self.v:
            return () # matched
        # 'return None' indicates 'unmatched'

with match(114, 514):
    if (GreaterThan(42)() and a, b):
        print(b, a)
# 514 114

Note that the matching clauses should be exhaustive, otherwise, a moshmosh.extensions.pattern_matching.runtime.NotExhaustive might get raised.

The supported Patterns are listed here, which is of course much more powerful than most programming languages.

  • And pattern: pat1 and pat2 and pat3 ...
  • Or pattern: pat1 or pat2 or pat3...
  • Pin pattern: pin(value), this is quite useful. See Elixir Pin Operator
  • Literal pattern: 1, "str", 1+2j, (1, 2)
  • As pattern: a, var
  • Wildcard: _
  • Guard: when(cond1, cond2, cond3)
  • Nested patterns:
    • Tuple: (pat1, pat2, pat3), (pat1, *pat2, pat3)
    • List: [pat1, pat2, pat3], [pat1, *pat2, pat3]
    • Recogniser: Cons(pat1, pat2, pat3), note that, the function Cons.__match__(<n arg>, value_to_match) is exact the protocol.

The pattern matching should be more efficient than those hand-written codes without ugly optimizations.

Besides, Moshmosh's pattern matching is orders of magnitude faster than any other alternatives.

Case Study : Template-Python

This is relatively a simple quasiquote implementation, inspired by MetaOCaml. It does not support manual splices or nested quotations, but the function arguments are automatically spliced.

# moshmosh?
# +template-python

@quote
def f(x):
    x + 1
    x = y + 1

from moshmosh.ast_compat import ast
from astpretty import pprint

stmts = f(ast.Name("a"))
pprint(ast.fix_missing_locations(stmts[0]))
pprint(ast.fix_missing_locations(stmts[1]))

# =>
Expr(
    lineno=7,
    col_offset=4,
    value=BinOp(
        lineno=7,
        col_offset=4,
        left=Name(lineno=7, col_offset=4, id='a', ctx=Load()),
        op=Add(),
        right=Num(lineno=7, col_offset=8, n=1),
    ),
)
Assign(
    lineno=8,
    col_offset=4,
    targets=[Name(lineno=8, col_offset=4, id='a', ctx=Store())],
    value=BinOp(
        lineno=8,
        col_offset=8,
        left=Name(lineno=8, col_offset=8, id='y', ctx=Load()),
        op=Add(),
        right=Num(lineno=8, col_offset=12, n=1),
    ),
)

Case Study: Lazy Import

# moshmosh?
# +lazy-import
import numpy as np
# -lazy-import

# in fact numpy is not imported here,
# and once you use it, it gets imported.

def arr10():
    # The first time call
    # arr10 will enforce the import of numpy.
    return np.zeros(10)

After the lazy modules are actually imported, there's no overhead to access their members.

However, please only import modules when using lazy-import.

The use case is about the necessary cross-import when you want to organise your codebase in a more fine-grained way.

Acknowledgements

moshmosh's People

Contributors

aloxaf avatar thautwarm avatar z-shang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

moshmosh's Issues

scala-like lambdas

Will make this tomorrow:

# moshmosh?
# +quick-lambda
 
list(map(1 + _, [1, 2, 3]))
# => [2, 3, 4]

list(map(_(1), [lambda x: x + 1, lambda x: x + 2])
# => [2, 3]

# -quick-lambda
_ = lambda x: x
list(map(_(1), [lambda x: x + 1, lambda x: x + 2])
# => [1, 1]

Support for Python 3.4

uses of some essential syntax like unpacking are not supported in Python 3.4, thus initially supporting Py34 considered harmful.

Recompilation

Suppose distutils already compiled source code with triggering moshmosh extensions, we can use module level constants(which can be unmarshalled and accessed without evaluating code), to indicate if this module is compiled under moshmosh, and if not, recompile.

APIs for using REPL

The enabled/disabled extensions must be maintained in a same object during the whole REPL session unless reset by users.

Incompatible with Python 3.8

  1. SyntaxWarning: "is not" with a literal

https://docs.python.org/3.8/whatsnew/3.8.html#changes-in-python-behavior

The compiler now produces a SyntaxWarning when identity checks (is and is not) are used with certain types of literals (e.g. strings, numbers). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (== and !=) instead. (Contributed by Serhiy Storchaka in bpo-34850.)

  1. TypeError: arguments field "args" must be a list, not a NoneType

It seems that there is something wrong with quick-lambda

In [1]: # +quick-lambda
/home/aloxaf/.local/lib/python3.8/site-packages/moshmosh/extensions/pattern_matching/core.py:345: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if n2 is 0:

In [2]: map(_0)
File /usr/lib/python3.8/site-packages/IPython/core/interactiveshell.py, line 3247, in run_ast_nodes
    code = compiler(mod, cell_name, mode)
File /usr/lib/python3.8/codeop.py, line 133, in __call__
    132  def __call__(self, source, filename, symbol):
--> 133      codeob = compile(source, filename, symbol, self.flags, 1)
    134      for feature in _features:
    ..................................................
     self = <IPython.core.compilerop.CachingCompiler object at 0x7f0c3a7
             e7430>
     source = <_ast.Interactive object at 0x7f0c25b4a850>
     filename = '<ipython-input-2-852728e0de5a>'
     symbol = 'single'
     self.flags = 512
     _features = [_Feature((2, 1, 0, 'beta', 1), (2, 2, 0, 'alpha', 0), 16),
                  _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 0), _
                  Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192),
                   _Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0), 1638
                  4), _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 3
                  2768), _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)
                  , 65536), _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha',
                   0), 131072), _Feature((3, 1, 0, 'alpha', 2), (4, 0, 0, 'alp
                  ha', 0), 262144), _F...
    ..................................................

TypeError: required field "args" missing from arguments

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.