PyYAML parsed into an arbitrary object

I have the following Python 2.6 program and a YAML definition (using PyYAML ):

import yaml

x = yaml.load(
    """
        product:
           name     : 'Product X'
           sku      : 123
           features :
             - size    :  '10x30cm'
               weight  :  '10kg'

         """
    )

print type(x)
print x


This leads to the following result:
<type 'dict'>
{'product': {'sku': 123, 'name': 'Product X', 'features': [{'weight': '10kg', 'size': '10x30cm'}]}}

Can I create an object with fields from x?

I would like to:

print x.features[0].size

I know that you can create an instance from an existing class, but this is not what I want for this particular scenario.

Edit:

  • The confusing part about the "strongly typed object" has been updated.
  • Access to the featuresindexer changed as suggested by Alex Martelli
+3
source share
1 answer

, , , , , , dict " " "- , " " , , .features(0) , .features[0] ( !), , , . , :

def wrap(datum):
  # don't wrap strings
  if isinstance(datum, basestring):
    return datum
  # don't wrap numbers, either
  try: return datum + 0
  except TypeError: pass
  return Fourie(datum)

class Fourie(object):
  def __init__(self, data):
    self._data = data
  def __getattr__(self, n):
    return wrap(self._data[n])
  def __call__(self, n):
    return wrap(self._data[n])

, x = wrap(x['product']) ( , , , x.product.features(0).size, , , , - factory, ).

: OP , features[0], features(0),

  def __getitem__(self, n):
    return wrap(self._data[n])

i.e. __getitem__ ( , ) __call__ ( , ).

" " ( Fourie) " ", dict - , -, , - , .

, " ", , , .., , (, , , - ;-). " ", , , , , , ! -)

+6

Source: https://habr.com/ru/post/1736895/


All Articles