0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python to RubyAdvent Calendar 2021

Day 12

[py2rb] wraps

Last updated at Posted at 2021-12-15

はじめに

移植やってます。

wraps (Python)

from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        print('Calling decorated function')
        return f(*args, **kwds)
    return wrapper

@my_decorator
def example():
    print('Called example function')

if __name__=="__main__":
  example()
  print("example関数名",example.__name__)
  print("example関数doc",example.__doc__)

# Calling decorated function
# Called example function
# example
# Docstring

公式ドキュメントのwrapsの使用例です。
fが定義されていないように見えるのですが、ここでは、f=example()f=exampleとして処理されています。

どうする? (Ruby)

def my_decorator(f)
  wraper = proc {
    puts "Calling decorated function"
    puts "Name: #{__method__}"
    f.call()
    puts "After decorated function"
  }
  wraper.call
end

def example()
  puts "Called example function"
end

my_decorator(method(:example))

# Calling decorated function
# Name: my_decorator      
# Called example function 
# After decorated function

引数が無いのならいけそう?
しかし、これだけだったら関数を渡すだけでもできてしまう。

def my_decorator(f)
  def wraper(f)
    puts "Calling decorated function"
    puts "Name: #{__method__}"
    f.call()
    puts "After decorated function"
  end
  wraper(f)
end

def example()
  puts "Called example function"
end

my_decorator(method(:example))

# Calling decorated function
# Name: wraper
# Called example function 
# After decorated function

これで、fwraperメソッドの中に入りました。
ここで、スコープやメモ化等の差異を出せれば意味があるものになるかも。

メモ

  • Python の wraps を学習した
  • 道のりは遠そう
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?