Skip to content

Commit

Permalink
Transform to single file module and:
Browse files Browse the repository at this point in the history
- add get() method with optional parameter for default value
- update tests
- change version to 0.3.0
  • Loading branch information
molejar committed Aug 18, 2019
1 parent f220893 commit 0f30807
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 120 deletions.
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ before_deploy:

deploy:
provider: pypi
user: "molejar"
user: molejar
password:
secure: Ar2cQYfCdTLIO76FpoEMHA+vDKS3qI4KhJSpRjDBOpg6NlG4t1lGhB2Iffsgeb5cc7CD+/KpyU0dDAEDPFePbi+sUlYdmWUFP8ounHCPiuxjZkKRfj0QK5WugIl34U37zKn9l5+WYjW1mLL0DR681UnGeY/+RwU88XmK8hrsBbKJIJS62S2ysn58eCPJMxC/6tD0iz9cPZGwk51N57+RzWLmvJsHUcBKimqAq1OPtcIAtZilyI25MxOxDDliv3LVksGliJib9jamTmPElgutLQ+9HGP32HEwZKdDeroJ3RwbVawt573WYZwl9mbDqxbNpznL8N49CI2tJ49NI5QQHSkzrTL9k99ggV/9jqTn+ZYC4mkQDuK+kizSDJ9BDYxT3b83a+DVhJMZXWFOQX2VZwJEuScncw9TwPmw670h/B3XFPdarkGKwbiu5KePsbO/s1mfw6Qw9LbM2dS2RBJ7Agyvq+gBPJ4UsZjpaaOcKH0W6SbT1ykwZsmk44LXG0mqSMmJxOfkAf6qdNTiLocO1edbQJ/Kanc/UcmHZjHOei0wmbIwc8lg8zdiRLy+NGqWok2kx/lM1h3Fe/XF5c4eW79QmiarJkudZaTbm2jMm/kwVMCSNTRvLQh2q41V9RjTFU1FHIajyH7aP3lvg6aEhQIIA/Xy/zMi5KbEzenGpOg=
distributions: "sdist bdist_wheel"
secure: "Ar2cQYfCdTLIO76FpoEMHA+vDKS3qI4KhJSpRjDBOpg6NlG4t1lGhB2Iffsgeb5cc7CD+/KpyU0dDAEDPFePbi+sUlYdmWUFP8ounHCPiuxjZkKRfj0QK5WugIl34U37zKn9l5+WYjW1mLL0DR681UnGeY/+RwU88XmK8hrsBbKJIJS62S2ysn58eCPJMxC/6tD0iz9cPZGwk51N57+RzWLmvJsHUcBKimqAq1OPtcIAtZilyI25MxOxDDliv3LVksGliJib9jamTmPElgutLQ+9HGP32HEwZKdDeroJ3RwbVawt573WYZwl9mbDqxbNpznL8N49CI2tJ49NI5QQHSkzrTL9k99ggV/9jqTn+ZYC4mkQDuK+kizSDJ9BDYxT3b83a+DVhJMZXWFOQX2VZwJEuScncw9TwPmw670h/B3XFPdarkGKwbiu5KePsbO/s1mfw6Qw9LbM2dS2RBJ7Agyvq+gBPJ4UsZjpaaOcKH0W6SbT1ykwZsmk44LXG0mqSMmJxOfkAf6qdNTiLocO1edbQJ/Kanc/UcmHZjHOei0wmbIwc8lg8zdiRLy+NGqWok2kx/lM1h3Fe/XF5c4eW79QmiarJkudZaTbm2jMm/kwVMCSNTRvLQh2q41V9RjTFU1FHIajyH7aP3lvg6aEhQIIA/Xy/zMi5KbEzenGpOg="
distributions: sdist
skip_existing: true
on:
tags: true
99 changes: 99 additions & 0 deletions easy_enum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Copyright 2019 Martin Olejar
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = "Martin Olejar"
__contact__ = "martin.olejar@gmail.com"
__version__ = "0.3.0"
__license__ = "Apache 2.0"
__status__ = "Development"
__all__ = ['Enum']


class MetaEnum(type):
""" Meta Class for Enum Type """

def __new__(mcs, name, bases, attrs):
cls = super().__new__(mcs, name, bases, attrs)
cls._items_ = list()
for attr, value in attrs.items():
if attr in set(dir(type(name, (object,), {}))) or (attr.startswith('_') and attr.endswith('_')):
continue
if isinstance(value, classmethod):
continue
if isinstance(value, tuple):
if len(value) == 2:
cls._items_.append((attr, value[0], value[1]))
else:
cls._items_.append((value[1], value[0], value[2]))
setattr(cls, attr, value[0])
else:
cls._items_.append((attr, value, ''))
return cls

def __getitem__(cls, key):
if isinstance(key, str):
for name, value, _ in cls._items_:
if key.upper() == name.upper():
return value
raise KeyError("\'%s\' has no item with name \'%s\'" % (cls.__name__, key))

elif isinstance(key, int):
for name, value, _ in cls._items_:
if key == value:
return name
raise KeyError("\'%s\' has no item with value \'%d\'" % (cls.__name__, key))

else:
raise TypeError("\'%s\' has no item with type \'%r\'" % (cls.__name__, type(key)))

def __iter__(cls):
return (item for item in cls._items_)

def __contains__(cls, item):
if isinstance(item, str) and item in (item[0] for item in cls._items_):
return True
if isinstance(item, int) and item in (item[1] for item in cls._items_):
return True
return False

def __len__(cls):
return len(cls._items_)


class Enum(metaclass=MetaEnum):
""" Enum Type Class """

@classmethod
def get(cls, key, default=None):
try:
return cls[key]
except KeyError:
return default

@classmethod
def desc(cls, key, default=''):
if isinstance(key, str):
for name, _, desc in cls._items_:
if key.upper() == name.upper():
return desc
return default

elif isinstance(key, int):
for _, value, desc in cls._items_:
if key == value:
return desc
return default

else:
raise TypeError("\'%s\' has no item with type \'%r\'" % (cls.__name__, type(key)))
23 changes: 0 additions & 23 deletions easy_enum/__init__.py

This file was deleted.

80 changes: 0 additions & 80 deletions easy_enum/base.py

This file was deleted.

3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ def long_description():
url='https://github.com/molejar/pyEnum',
description='User friendly implementation of Enum in Python',
long_description=long_description(),
packages=['easy_enum'],
py_modules=['easy_enum'],
test_suite="tests",
classifiers=[
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
Expand Down
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

29 changes: 16 additions & 13 deletions tests/test_pytest.py → tests/test_easy_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,24 @@ class TestEnum(Enum):
FOURTH_ITEM = (4, 'fourth', 'Description for fourth item')


def test_values():
def test_get_attr_value():
assert TestEnum.FIRST_ITEM == 1
assert TestEnum['FIRST_ITEM'] == 1
assert TestEnum['third'] == 3


def test_names():
def test_get_attr_name():
assert TestEnum[1] == 'FIRST_ITEM'
assert TestEnum[3] == 'third'


def test_get_default():
assert TestEnum.get('eleven') is None
assert TestEnum.get(11) is None
assert TestEnum.get('eleven', 11) == 11
assert TestEnum.get(11, 'eleven') == 'eleven'


def test_contains():
assert 3 in TestEnum
assert 0 not in TestEnum
Expand All @@ -54,21 +61,17 @@ def test_description():
assert TestEnum.desc(1) == ''
assert TestEnum.desc(4) == 'Description for fourth item'
assert TestEnum.desc('third') == ''
assert TestEnum.desc(11) == ''
assert TestEnum.desc('eleven') == ''
with pytest.raises(TypeError):
_ = TestEnum.desc((1, 2))


def test_basic_exceptions():
with pytest.raises(AttributeError):
def test_getitem_exceptions():
with pytest.raises(KeyError):
_ = TestEnum['second']
with pytest.raises(ValueError):
with pytest.raises(KeyError):
_ = TestEnum[10]
with pytest.raises(TypeError):
_ = TestEnum[(1, 2)]


def test_desc_exceptions():
with pytest.raises(AttributeError):
_ = TestEnum.desc('second')
with pytest.raises(ValueError):
_ = TestEnum.desc(10)
with pytest.raises(TypeError):
_ = TestEnum.desc((1, 2))

0 comments on commit 0f30807

Please sign in to comment.