From 54a17fb005d2d93cf4c8293177085f20f6bbd447 Mon Sep 17 00:00:00 2001 From: Ayoub Kaanich Date: Sun, 5 Aug 2018 18:43:17 +0100 Subject: [PATCH] Allow creating enum from their names. --- Src/IronPython/Runtime/Types/PythonType.cs | 16 ++++++++++++++++ Tests/test_enum.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Src/IronPython/Runtime/Types/PythonType.cs b/Src/IronPython/Runtime/Types/PythonType.cs index 354cccd4d..247682062 100644 --- a/Src/IronPython/Runtime/Types/PythonType.cs +++ b/Src/IronPython/Runtime/Types/PythonType.cs @@ -647,6 +647,22 @@ public PythonType this[params Type[] args] { } } + public object this[string member] { + get { + if (!UnderlyingSystemType.IsEnum) { + throw PythonOps.TypeError("'type' object is not subscriptable"); + } + if (member == null) { + throw PythonOps.KeyError(member); + } + try { + return Enum.Parse(UnderlyingSystemType, member); + } catch (ArgumentException) { + throw PythonOps.KeyError(member); + } + } + } + [SpecialName, PropertyMethod, WrapperDescriptor] public static object Get__module__(CodeContext/*!*/ context, PythonType self) { PythonTypeSlot pts; diff --git a/Tests/test_enum.py b/Tests/test_enum.py index 8dbc9ca68..a613d61a5 100644 --- a/Tests/test_enum.py +++ b/Tests/test_enum.py @@ -37,4 +37,22 @@ def test_constructor(self): for value in invalid_values: self.assertRaises(ValueError, EnumType, value) + @skipUnlessIronPython() + def test_from_str(self): + """check that enum could be constructed from str names""" + from IronPythonTest import DaysInt, DaysShort, DaysLong, DaysSByte, DaysByte, DaysUShort, DaysUInt, DaysULong + + enum_types = [DaysInt, DaysShort, DaysLong, DaysSByte, DaysByte, DaysUShort, DaysUInt, DaysULong] + + for EnumType in enum_types: + + self.assertEqual(EnumType['None'], EnumType.None) + self.assertEqual(EnumType['Mon'], EnumType.Mon) + self.assertEqual(EnumType['Weekend'], EnumType.Weekend) + + self.assertRaises(SystemError, lambda: EnumType[DaysInt]) + self.assertRaises(TypeError, lambda: EnumType[None]) + self.assertRaises(TypeError, lambda: EnumType[self]) + self.assertRaises(KeyError, lambda: EnumType['invalid']) + run_test(__name__)