예제 #1
0
def enumOf(baseType=int, enumName="", **kwArgs):
    '''
    Defines an anonymous class of Enum.
    Enumerated __value can be access by attribute.<br/>
    <pre>
    ex.)
    weekday = enumOf(SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDENSDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7)
    print "SUNDAY=" + weekday.SUNDAY # SUNDAY=SUNDAY
    print weekday.SUNDAY == weekday.MONDAY # true
    print weekday.valudOf("TUESDAY") == weekday.TUESDAY # true
    print weekday.hasEnum("WEDENSDAY") # true
    print isinstance(weekday, Enum) # true
    </pre>
    '''

    if baseType is None:
        baseType = object

    if len(enumName) == 0:
        enumName = "_".join(kwArgs.keys())
    enumType = type(enumName, (Enum, ), {})
    enumType.names = kwArgs.keys()
    enumType.values = []
    #enumType.__contains__ = staticmethod(lambda elementName: elementName in enumType.names)
    enumType.hasEnum = staticmethod(
        lambda elementName: elementName in enumType.names)
    enumType.valueOf = staticmethod(
        lambda elementName: getattr(enumType, elementName))
    order = 0
    for elementName, value in kwArgs.items():
        if not isinstance(value, baseType):
            raise ValueError(
                "name=%s __value=%s is not applicable for enum of %s" %
                tv.toStrTuple(elementName, value, baseType))
        if hasattr(enumType, elementName):
            raise ValueError("name=%s is already defined" % elementName)

        enumValue = type(
            "_EnumValue%d_" % acc.next(), (enumType, ), {
                "__init__": lambda self: None,
                "__str__": lambda self: self.enumName,
                "__repr__": lambda self: self.enumName,
                "__add__": lambda self, other: _enum_add_(self, other),
            })()

        enumValue.enumName = elementName
        enumValue.__eq__ = lambda self, other: isinstance(
            other, enumType) and other.order == order
        enumValue.__ne__ = lambda self, other: not self.__eq__(other)
        enumValue.__value = value
        enumValue.baseType = enumType
        enumValue.order = order
        enumType.values.append(enumValue)
        setattr(enumType, elementName, enumValue)
        order += 1

    return enumType
예제 #2
0
def enumOf(baseType = int, enumName = "", **kwArgs):
    '''
    Defines an anonymous class of Enum.
    Enumerated __value can be access by attribute.<br/>
    <pre>
    ex.)
    weekday = enumOf(SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDENSDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7)
    print "SUNDAY=" + weekday.SUNDAY # SUNDAY=SUNDAY
    print weekday.SUNDAY == weekday.MONDAY # true
    print weekday.valudOf("TUESDAY") == weekday.TUESDAY # true
    print weekday.hasEnum("WEDENSDAY") # true
    print isinstance(weekday, Enum) # true
    </pre>
    '''
    
    if baseType is None:
        baseType = object
    
    if len(enumName) == 0:
        enumName = "_".join(kwArgs.keys())
    enumType = type(enumName, (Enum, ), {})
    enumType.names = kwArgs.keys()
    enumType.values = []
    #enumType.__contains__ = staticmethod(lambda elementName: elementName in enumType.names)
    enumType.hasEnum = staticmethod(lambda elementName: elementName in enumType.names)
    enumType.valueOf = staticmethod(lambda elementName: getattr(enumType, elementName))
    order = 0
    for elementName, value in kwArgs.items():
        if not isinstance(value, baseType):
            raise ValueError("name=%s __value=%s is not applicable for enum of %s" % tv.toStrTuple(elementName, value, baseType))
        if hasattr(enumType, elementName):
            raise ValueError("name=%s is already defined" % elementName)
            
        enumValue = type("_EnumValue%d_" % acc.next(), (enumType,),
                        {
                            "__init__": lambda self: None,
                            "__str__": lambda self: self.enumName,
                            "__repr__": lambda self: self.enumName,
                            "__add__": lambda self, other: _enum_add_(self, other),
                        })()
        
        enumValue.enumName = elementName
        enumValue.__eq__ = lambda self, other: isinstance(other, enumType) and other.order == order
        enumValue.__ne__ = lambda self, other: not self.__eq__(other)
        enumValue.__value = value
        enumValue.baseType = enumType
        enumValue.order = order
        enumType.values.append(enumValue)
        setattr(enumType, elementName, enumValue)
        order += 1
    
    return enumType
예제 #3
0
class BinaryStream(Stream):
    @tv.forms(object, StreamDirection)
    def __init__(self, direction):
        super(BinaryStream, self).__init__(direction, bytearray)

    @tv.forms(object, tv.MoreThan(0, False))
    @tv.returns((bytearray, NoneType))
    @tv.raises(IOError)
    def read(self, bufferSize=1):
        raise Exception("Not implemented")

    @tv.forms(object, bytearray)
    @tv.raises(IOError)
    def write(self, contents):
        raise Exception("Not implemented")
예제 #4
0
파일: Stream.py 프로젝트: gnomeberry/pyth2
class Stream(object):
    '''
    Base class of stream
    '''
    @tv.forms(object, StreamDirection, type)
    def __init__(self, direction, manipulateType):
        self._direction = direction
        self._manipulateType = manipulateType

    @tv.returns((StreamDirection, tv.listOf(StreamDirection)))
    def direction(self):
        return self._direction

    @tv.returns(type)
    def manipulateType(self):
        return self._manipulateType
예제 #5
0
'''
Created on 2015/11/07

@author: _
'''
from pyth2.contracts import TypeValidator as tv
from types import NoneType

acc = tv.anonyClassCount()


class Enum(object):
    '''
    Base type of Enum<br />
    This class is not able to be instantiate directory.
    
    '''
    def __init__(self):
        raise Exception("Cannot instantiate directly Enum class")


@tv.forms(Enum, (Enum, tuple, list, set))
@tv.returns((tuple, list))
def _enum_add_(selv, other):
    if other is list:
        return other if selv in other else [selv] + other
    elif other is tuple:
        return other if selv in other else (selv, ) + other
    else:
        return (selv, other)
예제 #6
0
# -*- coding: utf-8 -*-
'''
Created on 2015/11/05

@author: _
'''

import os
from types import NoneType

import os.path as ospath
from pyth2.contracts import TypeValidator as tv
from pyth2.fs.Path import normalizeDirectorySeparator, DIRECTORY_SEP_UNICODE, Path

DEFAULT_TEXT_FILE_ENCODING = "utf-8"
Splittable = tv.hasattrTypeValidator("Splitable", "split")
Searchable = tv.hasattrTypeValidator("Searchable", "search")


class File(object):
    '''
    A class represents a file or directory in filesystem
    '''
    @tv.forms(object, (basestring, Path))
    def __init__(self, path):
        self._path = path if isinstance(path, Path) else Path(path)

    def __str__(self):
        return "File(%s)" % str(self._path.toUnicodePath())

    @tv.returns(Path)
예제 #7
0
파일: File.py 프로젝트: gnomeberry/pyth2
"""
Created on 2015/11/05

@author: _
"""

import os
from types import NoneType

import os.path as ospath
from pyth2.contracts import TypeValidator as tv
from pyth2.fs.Path import normalizeDirectorySeparator, DIRECTORY_SEP_UNICODE, Path


DEFAULT_TEXT_FILE_ENCODING = "utf-8"
Splittable = tv.hasattrTypeValidator("Splitable", "split")
Searchable = tv.hasattrTypeValidator("Searchable", "search")


class File(object):
    """
    A class represents a file or directory in filesystem
    """

    @tv.forms(object, (basestring, Path))
    def __init__(self, path):
        self._path = path if isinstance(path, Path) else Path(path)

    def __str__(self):
        return "File(%s)" % str(self._path.toUnicodePath())
예제 #8
0
'''
Created on 2015/11/07

@author: _
'''
from pyth2.contracts import TypeValidator as tv
from types import NoneType

acc = tv.anonyClassCount()

class Enum(object):
    '''
    Base type of Enum<br />
    This class is not able to be instantiate directory.
    
    '''
    
    def __init__(self):
        raise Exception("Cannot instantiate directly Enum class")

@tv.forms(Enum, (Enum, tuple, list, set))
@tv.returns((tuple, list))
def _enum_add_(selv, other):
    if other is list:
        return other if selv in other else [selv] + other
    elif other is tuple:
        return other if selv in other else (selv,) + other
    else:
        return (selv, other)

@tv.forms((type, NoneType), str)