Skip to content
This repository has been archived by the owner on Mar 23, 2023. It is now read-only.

Implement Decorators #177

Merged
merged 2 commits into from
Jan 21, 2017
Merged

Conversation

S-YOU
Copy link
Contributor

@S-YOU S-YOU commented Jan 20, 2017

This is for #72, but I guess this implementation may be more a like a hack, because Instead of generating Go code, I triggered AST to add more nodes while walking through.

  • Confirmed simple decorators working, not sure there is some complex use cases.
  • This is only for function decorators, class decorators not yet supported.
    (I don't get this syntax for class working yet. C = decorator(C))
% make run
def bold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def italic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@bold
@italic
def hello():
    return "hello world"

print hello()
<b><i>hello world</i></b>
import contextlib

@contextlib.contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

with tag("h1"):
  print "foo"
<h1>
foo
</h1>

@S-YOU S-YOU force-pushed the implement_decorators branch 2 times, most recently from 66321a5 to 25ceb40 Compare January 20, 2017 09:12
@S-YOU S-YOU force-pushed the implement_decorators branch from 8bb24ff to 462514c Compare January 20, 2017 13:10
Copy link
Contributor

@trotterdylan trotterdylan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for doing this! Comprehensions and generator expressions work this way so there is precedent for the approach. I like how neat and tidy it is. Good work!

I was trying to figure out if this will work with decorators that take arguments. I think it does, but just want to confirm. It would be good to have some test cases for that.

def testFunctionDecorator(self):
self.assertEqual((0, '<b>foo</b>\n'), _GrumpRun(textwrap.dedent("""\
def bold(fn):
def wrapped():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slightly shorter:

def bold(fn):
  return lambda: '<b>' + fn() + '</b>'

@S-YOU
Copy link
Contributor Author

S-YOU commented Jan 21, 2017

Sorry for late update, updated those. Hopefully CI is ok.

Copy link
Contributor

@trotterdylan trotterdylan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! Thanks for the update. Will merge shortly.

@trotterdylan trotterdylan merged commit 8cabc63 into google:master Jan 21, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants