Python 2.7:如何针对指定的模式验证列表?

时间:2017-02-03 15:34:01

标签: python python-2.7

在这堂课中:

class message:
    def __init__(self, node_info = None):
       if node_info is None: node_info = []
       self.node_info = node_info

    @property
    def node_info(self):
        return self._node_info

    @node_info.setter
    def node_info(self, value):
        self._node_info = value

node_info的布局应与此类似:

sample_node_info = [
  'Node Name',
  'Node URL',
  status,
  ['Service1','ServiceURL1',status],
  ['Service2','ServiceURL2',status]
]

前两个元素是字符串,是必需的。后续元素是列表,并且是可选的。可选元素(如果包含)应包含三个必需元素:

 service_info = ['ServiceName','ServiceURL',status]

问题:如何在上面的类中针对此格式验证node_info?我是否必须解析列表或者是否有更好的方法,比如定义某些类型的模式/格式?

1 个答案:

答案 0 :(得分:1)

这是一种可能的解决方案,使用自定义验证器:

import sys
from private import private

class message:
    #status_t = ['offline', 'online']

    def __init__(self, node_info = None):
      if node_info is None:
         self.node_info = []
      else:
         self.__validate_node_info(node_info)
         self.node_info = node_info

    @property
    def node_info(self):
        return self.node_info

    @node_info.setter
    def node_info(self, value):
      self.__validate_node_info(value)
      self.node_info = value

    def toString(self):
      s = ''
      return s


    @private
    def __validate_node_info(self, lst, level=0):

      '''
      Validates the node_info list, against this schema:

      node_info = [
         required(str),
         required(str),
         required(int),
         optional(service_info),
         optional(service_info),...]

      service_info = [required(str),required(str),required(int)]

      Sample input:

      sample_node_info = [
         'Node Name',
         'Node URL',
         status,
         ['Service1','ServiceURL1',status],
         ['Service2','ServiceURL2',status]
       ]

      '''

      i = 0
      lstlen = len(lst)

      if lstlen < 2:
        raise TypeError("The list %s is too short" % (lst))
      if level > 0:
        if len(lst) != 3:
           raise TypeError("The list %s should contain exactly %d elements" % (lst,3))
      for e in lst:
        argval = lst[i]
        if i < 2:
           if not type(argval) is str:
              raise TypeError("type is %s, must be %s" % (type(argval), str))
        elif i == 2:
           if not type(argval) is int:
              raise TypeError("type is %s, must be %s" % (type(argval), int))
        else:
           self.__validate_node_info(lst[i],level+1)
        i=i+1


#message.node_info = ['node1', 'nodeurl1', 1, ['service1', 'serviceurl1', 0], ['service2', 'serviceurl2', 1] ]
#print(message.node_info)

private.py列在here