Sha256: 3e94b3bd5ecf559b7c35e944954acc06f6095b214ed1e9d77a984f57341a3301

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

module PyCall
  class Dict
    include PyObjectWrapper

    def self.new(init=nil)
      case init
      when PyObject
        super
      when nil
        new(LibPython.PyDict_New())
      when Hash
        new.tap do |dict|
          init.each do |key, value|
            dict[key] = value
          end
        end
      else
        raise TypeError, "the argument must be a PyObject or a Hash"
      end
    end

    def initialize(pyobj)
      super(pyobj, LibPython.PyDict_Type)
    end

    def [](key)
      key = key.to_s if key.is_a? Symbol
      if key.is_a? String
        LibPython.PyDict_GetItemString(__pyobj__, key).to_ruby
      else
        LibPython.PyDict_GetItem(__pyobj__, key).to_ruby
      end
    end

    def []=(key, value)
      key = key.to_s if key.is_a? Symbol
      value = Conversions.from_ruby(value)
      if key.is_a? String
        LibPython.PyDict_SetItemString(__pyobj__, key, value)
      else
        LibPython.PyDict_SetItem(__pyobj__, key, value)
      end
      value
    end

    def delete(key)
      key = key.to_s if key.is_a? Symbol
      if key.is_a? String
        value = LibPython.PyDict_GetItemString(__pyobj__, key).to_ruby
        LibPython.PyDict_DelItemString(__pyobj__, key)
      else
        value = LibPython.PyDict_GetItem(__pyobj__, key).to_ruby
        LibPython.PyDict_DelItem(__pyobj__, key)
      end
      value
    end

    def size
      LibPython.PyDict_Size(__pyobj__)
    end

    def keys
      LibPython.PyDict_Keys(__pyobj__).to_ruby
    end

    def values
      LibPython.PyDict_Values(__pyobj__).to_ruby
    end

    def has_key?(key)
      key = Conversions.from_ruby(key)
      value = LibPython.PyDict_Contains(__pyobj__, key)
      raise PyError.fetch if value == -1
      1 == value
    end

    def default=(val)
      # TODO: PYDict_SetDefault
    end

    def dup
      # TODO: PyDict_Copy
    end

    def to_a
      LibPython.PyDict_Items(__pyobj__).to_ruby
    end

    def to_hash
      # TODO: PyDict_Next
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pycall-0.1.0.alpha.20170302 lib/pycall/dict.rb
pycall-0.1.0.alpha.20170226 lib/pycall/dict.rb