Skip to content

Instantly share code, notes, and snippets.

@azrafe7
Last active October 27, 2018 17:57
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 azrafe7/8b65733f7b22fad3e35bcb4bbd2fc2d1 to your computer and use it in GitHub Desktop.
Save azrafe7/8b65733f7b22fad3e35bcb4bbd2fc2d1 to your computer and use it in GitHub Desktop.
[haxe] using python decorators
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return "<div>{0}</div>".format(func(name))
return func_wrapper
def get_text(name):
return "Hello {0}!".format(name)
@p_decorate
def get_p_text(name):
return "Hello {0}!".format(name)
def tags_decorate(*tags):
def real_decorator(func):
def func_wrapper(*args, **kwargs):
result = func(*args, **kwargs)
for tag in tags[::-1]:
result = "<{0}>{1}</{0}>".format(tag, result)
return result
return func_wrapper
return real_decorator
@tags_decorate("bold", "pre", "code")
def bold_code(code):
return code
def main():
print("-- from python")
print(get_text("Bob"))
print(get_p_text("Bob"))
print(p_decorate(get_text)("Bob"))
print(div_decorate(p_decorate(get_text))("Bob"))
print(tags_decorate("i", "span")(get_text)("Bob"))
print(bold_code("python code"))
if __name__ == "__main__":
main()

Output

-- from python
Hello Bob!
<p>Hello Bob!</p>
<p>Hello Bob!</p>
<div><p>Hello Bob!</p></div>
<i><span>Hello Bob!</span></i>
<bold><pre><code>python code</code></pre></bold>

-- from haxe
Hello Alice!
<p>Hello Alice!</p>
<p>Hello Alice!</p>
<div><p>Hello Alice!</p></div>
<i><span>Hello Alice!</span></i>
<bold><pre><code>haxe code</code></pre></bold>

References

import haxe.Constraints.Function;
import python.KwArgs;
import python.VarArgs;
@:pythonImport("decorator")
extern class Decorator {
@:native("main") // this means: you can use "pythonMain()" in haxe, but will be generated as "main()" in the python output
static function pythonMain():Void;
static function p_decorate(func:Function):Function;
static function div_decorate(func:Function):Function;
static function get_text(name:String):String;
static function get_p_text(name:String):String;
static function tags_decorate(tags:VarArgs<Dynamic>):Function;
static function bold_code(code:String):String;
}
class TestDecorator {
static function main() {
Decorator.pythonMain();
var D = Decorator; // alias Decorator to D, just so we can write shorter code below
Sys.println("");
trace("-- from haxe");
trace(D.get_text("Alice"));
trace(D.get_p_text("Alice"));
trace(D.p_decorate(D.get_text)("Alice"));
trace(D.div_decorate(D.p_decorate(D.get_text))("Alice"));
trace(D.tags_decorate(["i", "span"])(D.get_text)("Alice"));
trace(D.bold_code("haxe code"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment