Skip to content

Instantly share code, notes, and snippets.

@andyli

andyli/Extern.hx Secret

Last active November 8, 2015 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyli/fef1faac6dbd7acc2722 to your computer and use it in GitHub Desktop.
Save andyli/fef1faac6dbd7acc2722 to your computer and use it in GitHub Desktop.
PyCon Haxe Python
import python.Tuple;
@:pythonImport("inspect") extern class Inspect {
static public function getdoc(object:Dynamic):String;
static public function getmembers
(object:Dynamic, ?predicate:haxe.Constraints.Function)
:Array<Tuple2<String,Dynamic>>;
static public function signature
(obj:Dynamic, ?follow_wrapped:Bool = true)
:Dynamic;
}
class Extern {
static function main():Void {
var getdocdoc = Inspect.getdoc(Inspect.getdoc);
trace(getdocdoc); // "Get the documentation string for an object..."
}
}
# Generated by Haxe
import inspect as Inspect
class Extern:
__slots__ = ()
@staticmethod
def main():
getdocdoc = Inspect.getdoc(Inspect.getdoc)
print(str(getdocdoc))
Extern.main()
using Lambda; // static extension
import haxe.ds.*;
class Functional {
static function main() {
// Array comprehension
var evens:Array<Float> = [for (i in 0...15) if (i % 2 == 0) i];
trace(evens); // [ 0, 2, 4, 6, 8, 10, 12, 14 ]
// functional goodies from `using Lambda`
var maxMultipleOf4 = evens
.filter(function(i) return i % 4 == 0)
.fold(function(i, a) return Math.max(i, a), evens[0]);
trace(maxMultipleOf4); // 12
// enum (GADT) and pattern matching
function getAnyHigher(floats:Array<Float>, v:Float):Option<Float> {
for (f in floats)
if (f > v)
return Some(f);
return None;
}
switch (getAnyHigher(evens, 5)) {
case Some(value):
// string interpolation (not really FP, but still nice)
trace('In evens, $value is higher than 5');
case None:
trace("No value in evens is higher than 5");
}
}
}
# Generated by Haxe
import math as python_lib_Math
import math as Math
import inspect as python_lib_Inspect
class Enum:
_hx_class_name = "Enum"
__slots__ = ("tag", "index", "params")
_hx_fields = ["tag", "index", "params"]
_hx_methods = ["__str__"]
def __init__(self,tag,index,params):
self.tag = tag
self.index = index
self.params = params
def __str__(self):
if (self.params is None):
return self.tag
else:
return (((HxOverrides.stringOrNull(self.tag) + "(") + HxOverrides.stringOrNull(",".join([python_Boot.toString1(x1,'') for x1 in self.params]))) + ")")
class EnumValue:
_hx_class_name = "EnumValue"
class Functional:
_hx_class_name = "Functional"
__slots__ = ()
_hx_statics = ["main"]
@staticmethod
def main():
evens = None
_g = []
_g1 = 0
while (_g1 < 15):
i = _g1
_g1 = (_g1 + 1)
if (HxOverrides.mod(i, 2) == 0):
_g.append(i)
evens = _g
print(str(evens))
def _hx_local_0(i1):
return (HxOverrides.modf(i1, 4) == 0)
def _hx_local_1(i2,a):
if python_lib_Math.isnan(i2):
return i2
elif python_lib_Math.isnan(a):
return a
else:
return max(i2,a)
maxMultipleOf4 = Lambda.fold(list(filter(_hx_local_0,evens)),_hx_local_1,(evens[0] if 0 < len(evens) else None))
print(str(maxMultipleOf4))
def _hx_local_3(floats,v):
_g11 = 0
while (_g11 < len(floats)):
f = (floats[_g11] if _g11 >= 0 and _g11 < len(floats) else None)
_g11 = (_g11 + 1)
if (f > v):
return haxe_ds_Option.Some(f)
return haxe_ds_Option._hx_None
getAnyHigher = _hx_local_3
_g12 = getAnyHigher(evens,5)
if ((_g12.index) == 0):
value = _g12.params[0]
print(str((("In evens, " + str(value)) + " is higher than 5")))
elif ((_g12.index) == 1):
print("No value in evens is higher than 5")
else:
pass
class Lambda:
_hx_class_name = "Lambda"
__slots__ = ()
_hx_statics = ["fold"]
@staticmethod
def fold(it,f,first):
_hx_local_0 = HxOverrides.iterator(it)
while _hx_local_0.hasNext():
x = _hx_local_0.next()
first = f(x,first)
return first
class haxe_ds_Option(Enum):
__slots__ = ()
_hx_class_name = "haxe.ds.Option"
@staticmethod
def Some(v):
return haxe_ds_Option("Some", 0, [v])
haxe_ds_Option._hx_None = haxe_ds_Option("None", 1, list())
class python_Boot:
_hx_class_name = "python.Boot"
__slots__ = ()
_hx_statics = ["keywords", "toString1", "fields", "simpleField", "getInstanceFields", "getSuperClass", "getClassFields", "prefixLength", "unhandleKeywords"]
@staticmethod
def toString1(o,s):
if (o is None):
return "null"
if isinstance(o,str):
return o
if (s is None):
s = ""
if (len(s) >= 5):
return "<...>"
if isinstance(o,bool):
if o:
return "true"
else:
return "false"
if isinstance(o,int):
return str(o)
if isinstance(o,float):
try:
if (o == int(o)):
def _hx_local_1():
def _hx_local_0():
v = o
return Math.floor((v + 0.5))
return str(_hx_local_0())
return _hx_local_1()
else:
return str(o)
except Exception as _hx_e:
_hx_e1 = _hx_e
e = _hx_e1
return str(o)
if isinstance(o,list):
o1 = o
l = len(o1)
st = "["
s = (("null" if s is None else s) + "\t")
_g = 0
while (_g < l):
i = _g
_g = (_g + 1)
prefix = ""
if (i > 0):
prefix = ","
st = (("null" if st is None else st) + HxOverrides.stringOrNull(((("null" if prefix is None else prefix) + HxOverrides.stringOrNull(python_Boot.toString1((o1[i] if i >= 0 and i < len(o1) else None),s))))))
st = (("null" if st is None else st) + "]")
return st
try:
if hasattr(o,"toString"):
return o.toString()
except Exception as _hx_e:
_hx_e1 = _hx_e
pass
if (python_lib_Inspect.isfunction(o) or python_lib_Inspect.ismethod(o)):
return "<function>"
if hasattr(o,"__class__"):
if isinstance(o,_hx_AnonObject):
toStr = None
try:
fields = python_Boot.fields(o)
fieldsStr = None
_g1 = []
_g11 = 0
while (_g11 < len(fields)):
f = (fields[_g11] if _g11 >= 0 and _g11 < len(fields) else None)
_g11 = (_g11 + 1)
x = ((("" + ("null" if f is None else f)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f),(("null" if s is None else s) + "\t"))))
_g1.append(x)
fieldsStr = _g1
toStr = (("{ " + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr]))) + " }")
except Exception as _hx_e:
_hx_e1 = _hx_e
e2 = _hx_e1
return "{ ... }"
if (toStr is None):
return "{ ... }"
else:
return toStr
if isinstance(o,Enum):
o2 = o
l1 = len(o2.params)
hasParams = (l1 > 0)
if hasParams:
paramsStr = ""
_g2 = 0
while (_g2 < l1):
i1 = _g2
_g2 = (_g2 + 1)
prefix1 = ""
if (i1 > 0):
prefix1 = ","
paramsStr = (("null" if paramsStr is None else paramsStr) + HxOverrides.stringOrNull(((("null" if prefix1 is None else prefix1) + HxOverrides.stringOrNull(python_Boot.toString1((o2.params[i1] if i1 >= 0 and i1 < len(o2.params) else None),s))))))
return (((HxOverrides.stringOrNull(o2.tag) + "(") + ("null" if paramsStr is None else paramsStr)) + ")")
else:
return o2.tag
if hasattr(o,"_hx_class_name"):
if (o.__class__.__name__ != "type"):
fields1 = python_Boot.getInstanceFields(o)
fieldsStr1 = None
_g3 = []
_g12 = 0
while (_g12 < len(fields1)):
f1 = (fields1[_g12] if _g12 >= 0 and _g12 < len(fields1) else None)
_g12 = (_g12 + 1)
x1 = ((("" + ("null" if f1 is None else f1)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f1),(("null" if s is None else s) + "\t"))))
_g3.append(x1)
fieldsStr1 = _g3
toStr1 = (((HxOverrides.stringOrNull(o._hx_class_name) + "( ") + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr1]))) + " )")
return toStr1
else:
fields2 = python_Boot.getClassFields(o)
fieldsStr2 = None
_g4 = []
_g13 = 0
while (_g13 < len(fields2)):
f2 = (fields2[_g13] if _g13 >= 0 and _g13 < len(fields2) else None)
_g13 = (_g13 + 1)
x2 = ((("" + ("null" if f2 is None else f2)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f2),(("null" if s is None else s) + "\t"))))
_g4.append(x2)
fieldsStr2 = _g4
toStr2 = (((("#" + HxOverrides.stringOrNull(o._hx_class_name)) + "( ") + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr2]))) + " )")
return toStr2
if (o == str):
return "#String"
if (o == list):
return "#Array"
if callable(o):
return "function"
try:
if hasattr(o,"__repr__"):
return o.__repr__()
except Exception as _hx_e:
_hx_e1 = _hx_e
pass
if hasattr(o,"__str__"):
return o.__str__([])
if hasattr(o,"__name__"):
return o.__name__
return "???"
else:
return str(o)
@staticmethod
def fields(o):
a = []
if (o is not None):
if hasattr(o,"_hx_fields"):
fields = o._hx_fields
return list(fields)
if isinstance(o,_hx_AnonObject):
d = o.__dict__
keys = d.keys()
handler = python_Boot.unhandleKeywords
for k in keys:
a.append(handler(k))
elif hasattr(o,"__dict__"):
a1 = []
d1 = o.__dict__
keys1 = d1.keys()
for k in keys1:
a.append(k)
return a
@staticmethod
def simpleField(o,field):
if (field is None):
return None
field1 = None
if field in python_Boot.keywords:
field1 = ("_hx_" + field)
elif ((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95))):
field1 = ("_hx_" + field)
else:
field1 = field
if hasattr(o,field1):
return getattr(o,field1)
else:
return None
@staticmethod
def getInstanceFields(c):
f = None
if hasattr(c,"_hx_fields"):
f = c._hx_fields
else:
f = []
if hasattr(c,"_hx_methods"):
a = c._hx_methods
f = (f + a)
sc = python_Boot.getSuperClass(c)
if (sc is None):
return f
else:
scArr = python_Boot.getInstanceFields(sc)
scMap = set(scArr)
res = []
_g = 0
while (_g < len(f)):
f1 = (f[_g] if _g >= 0 and _g < len(f) else None)
_g = (_g + 1)
if (not f1 in scMap):
scArr.append(f1)
return scArr
@staticmethod
def getSuperClass(c):
if (c is None):
return None
try:
if hasattr(c,"_hx_super"):
return c._hx_super
return None
except Exception as _hx_e:
_hx_e1 = _hx_e
pass
return None
@staticmethod
def getClassFields(c):
if hasattr(c,"_hx_statics"):
x = c._hx_statics
return list(x)
else:
return []
@staticmethod
def unhandleKeywords(name):
if (HxString.substr(name,0,python_Boot.prefixLength) == "_hx_"):
real = HxString.substr(name,python_Boot.prefixLength,None)
if real in python_Boot.keywords:
return real
return name
class python_HaxeIterator:
_hx_class_name = "python.HaxeIterator"
__slots__ = ("it", "x", "has", "checked")
_hx_fields = ["it", "x", "has", "checked"]
_hx_methods = ["next", "hasNext"]
def __init__(self,it):
self.checked = False
self.has = False
self.x = None
self.it = it
def next(self):
if (not self.checked):
self.hasNext()
self.checked = False
return self.x
def hasNext(self):
if (not self.checked):
try:
self.x = self.it.__next__()
self.has = True
except Exception as _hx_e:
_hx_e1 = _hx_e
if isinstance(_hx_e1, StopIteration):
s = _hx_e1
self.has = False
self.x = None
else:
raise _hx_e
self.checked = True
return self.has
class _hx_AnonObject:
_hx_class_name = "_hx_AnonObject"
__slots__ = ()
class python_internal_ArrayImpl:
_hx_class_name = "python.internal.ArrayImpl"
__slots__ = ()
_hx_statics = ["_get"]
@staticmethod
def _get(x,idx):
if ((idx > -1) and ((idx < len(x)))):
return x[idx]
else:
return None
class HxOverrides:
_hx_class_name = "HxOverrides"
__slots__ = ()
_hx_statics = ["iterator", "eq", "stringOrNull", "modf", "mod"]
@staticmethod
def iterator(x):
if isinstance(x,list):
return python_HaxeIterator(x.__iter__())
return x.iterator()
@staticmethod
def eq(a,b):
if (isinstance(a,list) or isinstance(b,list)):
return a is b
return (a == b)
@staticmethod
def stringOrNull(s):
if (s is None):
return "null"
else:
return s
@staticmethod
def modf(a,b):
return float('nan') if (b == 0.0) else a % b if a >= 0 else -(-a % b)
@staticmethod
def mod(a,b):
return a % b if a >= 0 else -(-a % b)
class HxString:
_hx_class_name = "HxString"
__slots__ = ()
_hx_statics = ["substr"]
@staticmethod
def substr(s,startIndex,_hx_len = None):
if (_hx_len is None):
return s[startIndex:]
else:
if (_hx_len == 0):
return ""
return s[startIndex:(startIndex + _hx_len)]
Math.NEGATIVE_INFINITY = float("-inf")
Math.POSITIVE_INFINITY = float("inf")
Math.NaN = float("nan")
Math.PI = python_lib_Math.pi
python_Boot.keywords = set(["and", "del", "from", "not", "with", "as", "elif", "global", "or", "yield", "assert", "else", "if", "pass", "None", "break", "except", "import", "raise", "True", "class", "exec", "in", "return", "False", "continue", "finally", "is", "try", "def", "for", "lambda", "while"])
python_Boot.prefixLength = len("_hx_")
Functional.main()
package pycon.hk;
class HelloWorld {
static function main() {
var target = Sys.args()[0];
var speaker = {
first: "Andy",
last: "Li"
}
trace('${speaker.first} ${speaker.last}: Hello, $target!');
}
}
# Generated by Haxe
import sys as python_lib_Sys
class Sys:
__slots__ = ()
@staticmethod
def args():
argv = python_lib_Sys.argv
return argv[1:None]
class haxe_io_Eof:
__slots__ = ()
def toString(self):
return "Eof"
class pycon_hk_HelloWorld:
__slots__ = ()
@staticmethod
def main():
target = python_internal_ArrayImpl._get(Sys.args(), 0)
speaker_first = "Andy"
speaker_last = "Li"
print(str((((((("" + ("null" if speaker_first is None else speaker_first)) + " ") + ("null" if speaker_last is None else speaker_last)) + ": Hello, ") + ("null" if target is None else target)) + "!")))
class python_internal_ArrayImpl:
__slots__ = ()
@staticmethod
def _get(x,idx):
if ((idx > -1) and ((idx < len(x)))):
return x[idx]
else:
return None
class HxOverrides:
__slots__ = ()
@staticmethod
def stringOrNull(s):
if (s is None):
return "null"
else:
return s
pycon_hk_HelloWorld.main()
import python.KwArgs;
class Kw {
static function test(a:Float, b:Float, c:Float):Void {
trace('$a, $b, $c');
}
static function main():Void {
test(1.1, 1.2, 1.3);
var kw:KwArgs<Dynamic> = {a: 2.1, b: 2.2, c: 2.3};
(untyped test)(kw);
(untyped test)(({a: 3.1, b: 3.2, c: 3.3}:KwArgs<Dynamic>));
}
}
# Generated by Haxe
class _hx_AnonObject:
def __init__(self, fields):
self.__dict__ = fields
class Kw:
__slots__ = ()
@staticmethod
def test(a,b,c):
print(str(((((("" + str(a)) + ", ") + str(b)) + ", ") + str(c))))
@staticmethod
def main():
Kw.test(1.1,1.2,1.3)
kw = None
d = python_Lib.anonAsDict(_hx_AnonObject({'a': 2.1, 'b': 2.2, 'c': 2.3}))
kw = d
Kw.test(**kw)
def _hx_local_0():
d1 = python_Lib.anonAsDict(_hx_AnonObject({'a': 3.1, 'b': 3.2, 'c': 3.3}))
return d1
Kw.test(**_hx_local_0())
class python_Lib:
__slots__ = ()
@staticmethod
def anonAsDict(o):
if isinstance(o,_hx_AnonObject):
return o.__dict__
else:
return None
class HxOverrides:
__slots__ = ()
@staticmethod
def stringOrNull(s):
if (s is None):
return "null"
else:
return s
Kw.main()
import python.KwArgs;
using PyHelpers;
class Kw {
static function test(a:Float, b:Float, c:Float):Void {
trace('$a, $b, $c');
}
static function main():Void {
test(1.1, 1.2, 1.3);
var kw:KwArgs<Dynamic> = {a: 2.1, b: 2.2, c: 2.3};
(untyped test)(kw);
(untyped test)(({a: 3.1, b: 3.2, c: 3.3}:KwArgs<Dynamic>));
test.call(c => 4.3, a => 4.1, b => 4.2, d => 4.4);
}
}
class Point {
public var x:Float;
public var y:Float;
public function new(x:Float, y:Float):Void {
this.x = x;
this.y = y;
}
public function offset(dx:Float = 0, dy:Float = 0):Point {
return new Point(x + dx, y + dy);
}
}
class OOP {
static function main():Void {
var p = new Point(0, 0);
var p2 = p.offset(1, 2);
trace(p2.x); //1
}
}
# Generated by Haxe
class Point:
__slots__ = ("x", "y")
def __init__(self,x,y):
self.x = x
self.y = y
def offset(self,dx = 0,dy = 0):
if (dx is None):
dx = 0
if (dy is None):
dy = 0
return Point((self.x + dx), (self.y + dy))
class OOP:
__slots__ = ()
@staticmethod
def main():
p = Point(0, 0)
p2 = p.offset(1,2)
print(str(p2.x))
OOP.main()
import python.Syntax;
class PySyntax {
static function main():Void {
var string = Syntax.pythonCode('"abc" # type : str');
trace(string);
}
}
# Generated by Haxe
class PySyntax:
__slots__ = ()
@staticmethod
def main():
string = "abc" # type : str
print(str(string))
PySyntax.main()
class Typing {
static function main():Void {
var i = 123; // same as var i:Int = 123;
$type(i); // Int
// i = "123"; // error: String should be Int
var floats = [1.0, 1.1, 1.2];
$type(floats); // Array<Float>
$type(floats[0]); // Float
floats[0] = i;
trace(floats); // [ 123, 1.1, 1.2 ]
// floats[0] = "string"; // error: String should be Float
}
}
# Generated by Haxe
class Typing:
__slots__ = ()
@staticmethod
def main():
i = 123
i
floats = [1.0, 1.1, 1.2]
floats
(floats[0] if 0 < len(floats) else None)
python_internal_ArrayImpl._set(floats, 0, i)
print(str(floats))
class python_internal_ArrayImpl:
__slots__ = ()
@staticmethod
def _get(x,idx):
if ((idx > -1) and ((idx < len(x)))):
return x[idx]
else:
return None
@staticmethod
def _set(x,idx,v):
l = len(x)
while (l < idx):
x.append(None)
l = (l + 1)
if (l == idx):
x.append(v)
else:
x[idx] = v
return v
Typing.main()
class Untyped {
static function main():Void {
var l = untyped list("abc");
trace(l); // ['a', 'b', 'c']
}
}
# Generated by Haxe
class Untyped:
__slots__ = ()
@staticmethod
def main():
l = list("abc")
print(str(l))
Untyped.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment