Class: PyCall::WrapperObjectCache

Inherits:
Object
  • Object
show all
Defined in:
lib/pycall/wrapper_object_cache.rb

Defined Under Namespace

Classes: Key

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*restricted_pytypes) ⇒ WrapperObjectCache

Returns a new instance of WrapperObjectCache.



52
53
54
55
56
57
58
59
60
61
# File 'lib/pycall/wrapper_object_cache.rb', line 52

def initialize(*restricted_pytypes)
  unless restricted_pytypes.empty?
    restricted_pytypes.each do |pytype|
      next if pytype.kind_of? PyTypePtr
      raise TypeError, "unexpected type of object in the arguments (#{pytype.class} for PyCall::PyTypePtr)"
    end
  end
  @restricted_pytypes = restricted_pytypes
  @wrapper_object_table = ObjectSpace::WeakMap.new
end

Class Method Details

.get_key(pyptr) ⇒ Object



18
19
20
# File 'lib/pycall/wrapper_object_cache.rb', line 18

def self.get_key(pyptr)
  pyptr.__address__
end

Instance Method Details

#check_wrapper_object(wrapper_object) ⇒ Object



86
87
88
89
90
# File 'lib/pycall/wrapper_object_cache.rb', line 86

def check_wrapper_object(wrapper_object)
  unless wrapper_object.kind_of?(PyObjectWrapper)
    raise TypeError, "unexpected wrapper object (expected an object extended by PyObjectWrapper)"
  end
end

#lookup(pyptr) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pycall/wrapper_object_cache.rb', line 63

def lookup(pyptr)
  # TODO: check pytypeptr type
  unless pyptr.kind_of? PyPtr
    raise TypeError, "unexpected argument type #{pyptr.class} (expected PyCall::PyPtr)"
  end

  unless @restricted_pytypes.empty?
    unless @restricted_pytypes.any? {|pytype| pyptr.kind_of? pytype }
      raise TypeError, "unexpected argument Python type #{pyptr.__ob_type__.__name__} (expected either of them in [#{@restricted_pytypes.map(&:__tp_name__).join(', ')}])"
    end
  end

  key = self.class.get_key(pyptr)
  wrapper_object = @wrapper_object_table[key]
  unless wrapper_object
    wrapper_object = yield(pyptr)
    check_wrapper_object(wrapper_object)
    @wrapper_object_table[key] = wrapper_object
  end

  wrapper_object
end