Name | lazr.enum JSON |
Version |
1.2.2
JSON |
| download |
home_page | https://launchpad.net/lazr.enum |
Summary | Enums with zope.schema vocabulary support and database-friendly conveniences. |
upload_time | 2024-12-05 09:55:24 |
maintainer | LAZR Developers |
docs_url | https://pythonhosted.org/lazr.enum/ |
author | None |
requires_python | None |
license | LGPL v3 |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
..
This file is part of lazr.enum.
lazr.enum is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, version 3 of the License.
lazr.enum is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with lazr.enum. If not, see <http://www.gnu.org/licenses/>.
Enumerated Types
****************
Enumerated types are used primarily in two distinct places in the Launchpad
code: selector types; and database types.
Simple enumerated types do not have values, whereas database enumerated
types are a mapping from an integer value to something meaningful in the
code.
>>> from lazr.enum import (
... EnumeratedType, DBEnumeratedType, Item, DBItem, use_template)
The `enum` values of EnumeratedTypes are instances of Item.
>>> class Fruit(EnumeratedType):
... "A choice of fruit."
... APPLE = Item('Apple')
... PEAR = Item('Pear')
... ORANGE = Item('Orange')
===================
IVocabulary support
===================
Enumerated types support IVocabularyTokenized.
>>> from zope.interface.verify import verifyObject
>>> from zope.schema.interfaces import (
... ITitledTokenizedTerm, IVocabularyTokenized)
>>> verifyObject(IVocabularyTokenized, Fruit)
True
The items themselves do not support any interface. Items returned
by the methods for vocabularies return wrapped items that support
the ITitledTokenizedTerm interface.
The token used to identify terms in the vocabulary is the name of the
Item variable.
>>> item = Fruit.getTermByToken('APPLE')
>>> type(item)
<class 'lazr.enum...TokenizedItem'>
>>> verifyObject(ITitledTokenizedTerm, item)
True
TokenizedItems have three attributes (in order to support
ITitledTokenizedTerm):
>>> item.value
<Item Fruit.APPLE, Apple>
>>> item.token
'APPLE'
>>> item.title
'Apple'
>>> Fruit.getTermByToken('apple').value
<Item Fruit.APPLE, Apple>
The length of an EnumeratedType returns the number of items it has.
>>> print(len(Fruit))
3
===========================
The EnumeratedType registry
===========================
All enumerated types that are created are added to the
enumerated_type_registry.
>>> from lazr.enum import enumerated_type_registry
The enumerated_type_registry maps the name of the enumerated type to the type
itself.
>>> 'Fruit' in enumerated_type_registry
True
>>> enumerated_type_registry['Fruit']
<EnumeratedType 'Fruit'>
You cannot redefine an existing enumerated type, nor create another enumerated
type with the same name as an existing type.
>>> class BranchType(EnumeratedType):
... BAR = Item('Bar')
...
>>> BranchType.name = 'AltBranchType'
>>> class BranchType(EnumeratedType):
... FOO = Item('Foo')
Traceback (most recent call last):
...
TypeError: An enumerated type already exists with the name BranchType
(...AltBranchType).
======================
Enumerated Type basics
======================
An EnumeratedType has a name and a description. The name is the same as the
class name, and the description is the docstring for the class.
>>> print(Fruit.name)
Fruit
>>> print(Fruit.description)
A choice of fruit.
If you do not specify an explicit sort_order for the items of the
EnumeratedType one is created for you. This is tuple of the tokens.
>>> print(Fruit.sort_order)
('APPLE', 'PEAR', 'ORANGE')
The items of an enumerated type can be iterated over. However the type that
is returned by the iteration is the TokenizedItem, not the item itself.
>>> for item in Fruit:
... print(item.token, item.title)
APPLE Apple
PEAR Pear
ORANGE Orange
Items can also optionally have a url associated with them.
>>> class Guitar(EnumeratedType):
... FENDER = Item('Fender', url='http://www.fender.com')
... RICK = Item('Rickenbacker', url='http://www.rickenbacker.com')
... GIBSON = Item('Gibson', url='http://www.gibson.com')
... FRANKENBASS = Item('Home built')
>>> print(Guitar.FENDER.url)
http://www.fender.com
>>> print(Guitar.FRANKENBASS.url)
None
Items in an enumerator support comparison and equality checks. Comparison
is based on the sort order of the items.
>>> apple = Fruit.APPLE
>>> pear = Fruit.PEAR
>>> orange = Fruit.ORANGE
>>> apple < pear
True
>>> apple == pear
False
>>> apple == apple
True
>>> apple != pear
True
>>> apple > pear
False
>>> pear < orange
True
>>> apple < orange
True
Items which are not in an enumerator always compare as False.
>>> import warnings
>>> from lazr.enum import Item
>>> with warnings.catch_warnings():
... warnings.simplefilter('ignore', category=UserWarning)
... Item('a') == Item('b')
False
The string representation of an Item is the title, and the representation
also shows the enumeration that the Item is from.
>>> print(apple)
Apple
>>> print(repr(apple))
<Item Fruit.APPLE, Apple>
The `items` attribute of an enumerated type is not a list, but a class that
provides iteration over the items, and access to the Item attributes through
either the name of the Item, or the database value if there is one.
The primary use of this is to provide a backwards compatible accessor for
items, but it also provides a suitable alternative to getattr.
>>> name = 'APPLE'
>>> Fruit.items[name]
<Item Fruit.APPLE, Apple>
>>> getattr(Fruit, name)
<Item Fruit.APPLE, Apple>
=========================
Database Enumerated Types
=========================
A very common use of enumerated types are to give semantic meaning to integer
values stored in database columns. EnumeratedType Items themselves don't have
any integer values.
The DBEnumeratedType provides the semantic framework for a type that is used to
map integer values to python enumerated values.
>>> # Remove the existing reference to BranchType from the registry
>>> del enumerated_type_registry['BranchType']
>>> class BranchType(DBEnumeratedType):
... HOSTED = DBItem(1, """
... Hosted
...
... Hosted braches use the supermirror as the main repository
... for the branch.""")
...
... MIRRORED = DBItem(2, """
... Mirrored
...
... Mirrored branches are "pulled" from a remote location.""")
...
... IMPORTED = DBItem(3, """
... Imported
...
... Imported branches are natively maintained in CVS or SVN""")
Note carefully that the value of a DBItem is the integer representation. But
the value of the TokenizedItem is the DBItem itself.
>>> hosted = BranchType.HOSTED
>>> hosted.value
1
>>> hosted == BranchType.HOSTED
True
>>> tokenized_item = BranchType.getTermByToken('HOSTED')
>>> tokenized_item.value
<DBItem BranchType.HOSTED, (1) Hosted>
DBEnumeratedTypes also support IVocabularyTokenized
>>> verifyObject(IVocabularyTokenized, BranchType)
True
The items attribute of DBEnumeratedTypes provide a mapping from the database
values to the DBItems.
>>> BranchType.items[3]
<DBItem BranchType.IMPORTED, (3) Imported>
The items also support the url field.
>>> class Bass(DBEnumeratedType):
... FENDER = DBItem(10, 'Fender', url='http://www.fender.com')
... RICK = DBItem(20, 'Rickenbacker',
... url='http://www.rickenbacker.com')
... GIBSON = DBItem(30, 'Gibson', url='http://www.gibson.com')
... FRANKENBASS = DBItem(40, 'Home built')
>>> print(Bass.FENDER.url)
http://www.fender.com
>>> print(Bass.FRANKENBASS.url)
None
Items in a DBEnumeratedType class must be of type DBItem.
>>> class BadItemType(DBEnumeratedType):
... TESTING = Item("Testing")
Traceback (most recent call last):
...
TypeError: Items must be of the appropriate type for the DBEnumeratedType,
...builtin...BadItemType.TESTING
You are not able to define a DBEnumeratedType that has two different
DBItems that map to the same numeric value.
>>> class TwoMapping(DBEnumeratedType):
... FIRST = DBItem(42, 'First')
... SECOND = DBItem(42, 'Second')
Traceback (most recent call last):
...
TypeError: Two DBItems with the same value 42 (FIRST, SECOND)
=========================
Overriding the sort order
=========================
By default the sort order of the items in an enumerated type is defined by the
order in which the Items are declared. This my be overridden by specifying
a sort_order attribute in the class.
If a sort_order is specified, it has to specify every item in the enumeration.
>>> class AnimalClassification(EnumeratedType):
... sort_order = "REPTILE", "INSECT", "MAMMAL"
... INSECT = Item("Insect")
... MAMMAL = Item("Mammal")
... FISH = Item("Fish")
... REPTILE = Item("Reptile")
Traceback (most recent call last):
...
TypeError: sort_order for EnumeratedType must contain all and only Item instances ...
The sort_order may also appear anywhere in the definition of the class,
although convention has it that it appears first, before the Item instances.
>>> class AnimalClassification(EnumeratedType):
... sort_order = "REPTILE", "FISH", "INSECT", "MAMMAL"
... INSECT = Item("Insect")
... MAMMAL = Item("Mammal")
... FISH = Item("Fish")
... REPTILE = Item("Reptile")
The items attribute of the enumerated type is ordered based on the sort_order.
The items attribute is also used to control iteration using __iter__.
>>> for item in AnimalClassification.items:
... print(item.title)
Reptile
Fish
Insect
Mammal
The sort order also drives the comparison operations.
>>> reptile, fish, insect, mammal = AnimalClassification.items
>>> reptile < fish < insect < mammal
True
==========================
Extending enumerated types
==========================
The simplest way to extend a class is to derive from it.
>>> class AnimalClassificationExtended(AnimalClassification):
... INVERTEBRATE = Item("Invertebrate")
>>> for item in AnimalClassificationExtended:
... print(item.title)
Reptile
Fish
Insect
Mammal
Invertebrate
The use_template function inserts the items from the specified enumerated type
into the new enumerated type. The default case is to take all the enumerated
items.
>>> class UIBranchType(EnumeratedType):
... use_template(BranchType)
>>> for item in UIBranchType:
... print(item.title)
Hosted
Mirrored
Imported
You can also specify items to be excluded by referring to the attribute name
in the exclude parameter. This can be either a string referring to one name
or a tuple or list that refers to multiple attribute names.
>>> class UIBranchType2(EnumeratedType):
... use_template(BranchType, exclude='IMPORTED')
>>> for item in UIBranchType2:
... print(item.title)
Hosted
Mirrored
Or limit the items to those specified:
>>> class UIBranchType3(EnumeratedType):
... use_template(BranchType, include=('HOSTED', 'MIRRORED'))
>>> for item in UIBranchType3:
... print(item.title)
Hosted
Mirrored
================================================
Getting from an item back to the enumerated type
================================================
Each Item in an EnumeratedType has a reference back to the EnumeratedType.
>>> print(repr(apple))
<Item Fruit.APPLE, Apple>
>>> print(repr(apple.enum))
<EnumeratedType 'Fruit'>
>>> for item in apple.enum:
... print(item.title)
Apple
Pear
Orange
============
Item.sortkey
============
The sortkey attribute of the Items are defined by the sort_order that is
defined for the enumerated type. The value is often used as a hidden value
in columns in order to ensure appropriate sorting.
>>> for item in Fruit.items:
... print(item.title, item.sortkey)
Apple 0
Pear 1
Orange 2
>>> for item in BranchType.items:
... print(item.title, item.sortkey)
Hosted 0
Mirrored 1
Imported 2
============
JSON Support
============
Enumerated types instances can be serialised to/from json. This library provides the
necessary encode and decode classes which can be used directly or as part of the
lazr.json package where they are registered as default handlers for lazr enums.
A enum instance is serialised as a dict containing:
- the enumerated type name as per the enumerated_type_registry
- the enum instance name
>>> import json
>>> from lazr.enum import EnumJSONEncoder
>>> json_enum = json.dumps(
... Fruit.APPLE, cls=EnumJSONEncoder, sort_keys=True)
>>> print(json_enum)
{"name": "APPLE", "type": "Fruit"}
To deserialse, we can specify a json object_hook as follows.
This is done transparently when using the lazr.json package.
>>> def fruit_enum_decoder(value_dict):
... return EnumJSONDecoder.from_dict(Fruit, value_dict)
>>> from lazr.enum import EnumJSONDecoder
>>> json.loads(json_enum, object_hook=fruit_enum_decoder)
<Item Fruit.APPLE, Apple>
==================
NEWS for lazr.enum
==================
1.2.2 (2024-12-05)
==================
- Add support for Python 3.9, 3.10, 3.11, 3.12 and 3.13.
- Drop support for Python 3.7 and below
- Add basic pre-commit configuration.
- Publish documentation on Read the Docs.
1.2.1 (2021-09-13)
==================
- Adjust versioning strategy to avoid importing pkg_resources, which is slow
in large environments.
1.2 (2019-11-24)
================
- Switch from buildout to tox.
- Add Python 3 support.
1.1.4 (2012-04-18)
==================
- Support for serialising enums to/from json (lp:984549)
- Items which are not in an enumerator always compare as False (lp:524259)
- Fix the licence statement in _enum.py to be LGPLv3 not LGPLv3+ (lp:526484)
1.1.3 (2011-04-20)
==================
- added case insensitivity to getting the term by the token value (lp:154556)
1.1.2 (2009-08-31)
==================
- removed unnecessary build dependencies
1.1.1 (2009-08-06)
==================
- Removed sys.path hack from setup.py.
1.1 (2009-06-08)
================
- Added `url` argument to the BaseItem and DBItem constructors.
1.0 (2009-03-24)
================
- Initial release on PyPI
Raw data
{
"_id": null,
"home_page": "https://launchpad.net/lazr.enum",
"name": "lazr.enum",
"maintainer": "LAZR Developers",
"docs_url": "https://pythonhosted.org/lazr.enum/",
"requires_python": null,
"maintainer_email": "lazr-developers@lists.launchpad.net",
"keywords": null,
"author": null,
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/04/7f/57647073d890aadc5a95a86ded4144954bd33456c463c6d15893f0a25243/lazr_enum-1.2.2.tar.gz",
"platform": null,
"description": "..\n This file is part of lazr.enum.\n\n lazr.enum is free software: you can redistribute it and/or modify it\n under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, version 3 of the License.\n\n lazr.enum is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with lazr.enum. If not, see <http://www.gnu.org/licenses/>.\n\nEnumerated Types\n****************\n\nEnumerated types are used primarily in two distinct places in the Launchpad\ncode: selector types; and database types.\n\nSimple enumerated types do not have values, whereas database enumerated\ntypes are a mapping from an integer value to something meaningful in the\ncode.\n\n >>> from lazr.enum import (\n ... EnumeratedType, DBEnumeratedType, Item, DBItem, use_template)\n\nThe `enum` values of EnumeratedTypes are instances of Item.\n\n >>> class Fruit(EnumeratedType):\n ... \"A choice of fruit.\"\n ... APPLE = Item('Apple')\n ... PEAR = Item('Pear')\n ... ORANGE = Item('Orange')\n\n===================\nIVocabulary support\n===================\n\nEnumerated types support IVocabularyTokenized.\n\n >>> from zope.interface.verify import verifyObject\n >>> from zope.schema.interfaces import (\n ... ITitledTokenizedTerm, IVocabularyTokenized)\n >>> verifyObject(IVocabularyTokenized, Fruit)\n True\n\nThe items themselves do not support any interface. Items returned\nby the methods for vocabularies return wrapped items that support\nthe ITitledTokenizedTerm interface.\n\nThe token used to identify terms in the vocabulary is the name of the\nItem variable.\n\n >>> item = Fruit.getTermByToken('APPLE')\n >>> type(item)\n <class 'lazr.enum...TokenizedItem'>\n >>> verifyObject(ITitledTokenizedTerm, item)\n True\n\nTokenizedItems have three attributes (in order to support\nITitledTokenizedTerm):\n\n >>> item.value\n <Item Fruit.APPLE, Apple>\n >>> item.token\n 'APPLE'\n >>> item.title\n 'Apple'\n\n >>> Fruit.getTermByToken('apple').value\n <Item Fruit.APPLE, Apple>\n\nThe length of an EnumeratedType returns the number of items it has.\n\n >>> print(len(Fruit))\n 3\n\n===========================\nThe EnumeratedType registry\n===========================\n\nAll enumerated types that are created are added to the\nenumerated_type_registry.\n\n >>> from lazr.enum import enumerated_type_registry\n\nThe enumerated_type_registry maps the name of the enumerated type to the type\nitself.\n\n >>> 'Fruit' in enumerated_type_registry\n True\n >>> enumerated_type_registry['Fruit']\n <EnumeratedType 'Fruit'>\n\nYou cannot redefine an existing enumerated type, nor create another enumerated\ntype with the same name as an existing type.\n\n >>> class BranchType(EnumeratedType):\n ... BAR = Item('Bar')\n ...\n >>> BranchType.name = 'AltBranchType'\n >>> class BranchType(EnumeratedType):\n ... FOO = Item('Foo')\n Traceback (most recent call last):\n ...\n TypeError: An enumerated type already exists with the name BranchType\n (...AltBranchType).\n\n======================\nEnumerated Type basics\n======================\n\nAn EnumeratedType has a name and a description. The name is the same as the\nclass name, and the description is the docstring for the class.\n\n >>> print(Fruit.name)\n Fruit\n >>> print(Fruit.description)\n A choice of fruit.\n\nIf you do not specify an explicit sort_order for the items of the\nEnumeratedType one is created for you. This is tuple of the tokens.\n\n >>> print(Fruit.sort_order)\n ('APPLE', 'PEAR', 'ORANGE')\n\nThe items of an enumerated type can be iterated over. However the type that\nis returned by the iteration is the TokenizedItem, not the item itself.\n\n >>> for item in Fruit:\n ... print(item.token, item.title)\n APPLE Apple\n PEAR Pear\n ORANGE Orange\n\nItems can also optionally have a url associated with them.\n\n >>> class Guitar(EnumeratedType):\n ... FENDER = Item('Fender', url='http://www.fender.com')\n ... RICK = Item('Rickenbacker', url='http://www.rickenbacker.com')\n ... GIBSON = Item('Gibson', url='http://www.gibson.com')\n ... FRANKENBASS = Item('Home built')\n\n >>> print(Guitar.FENDER.url)\n http://www.fender.com\n >>> print(Guitar.FRANKENBASS.url)\n None\n\nItems in an enumerator support comparison and equality checks. Comparison\nis based on the sort order of the items.\n\n >>> apple = Fruit.APPLE\n >>> pear = Fruit.PEAR\n >>> orange = Fruit.ORANGE\n >>> apple < pear\n True\n >>> apple == pear\n False\n >>> apple == apple\n True\n >>> apple != pear\n True\n >>> apple > pear\n False\n >>> pear < orange\n True\n >>> apple < orange\n True\n\nItems which are not in an enumerator always compare as False.\n\n >>> import warnings\n >>> from lazr.enum import Item\n >>> with warnings.catch_warnings():\n ... warnings.simplefilter('ignore', category=UserWarning)\n ... Item('a') == Item('b')\n False\n\nThe string representation of an Item is the title, and the representation\nalso shows the enumeration that the Item is from.\n\n >>> print(apple)\n Apple\n >>> print(repr(apple))\n <Item Fruit.APPLE, Apple>\n\nThe `items` attribute of an enumerated type is not a list, but a class that\nprovides iteration over the items, and access to the Item attributes through\neither the name of the Item, or the database value if there is one.\n\nThe primary use of this is to provide a backwards compatible accessor for\nitems, but it also provides a suitable alternative to getattr.\n\n >>> name = 'APPLE'\n >>> Fruit.items[name]\n <Item Fruit.APPLE, Apple>\n >>> getattr(Fruit, name)\n <Item Fruit.APPLE, Apple>\n\n=========================\nDatabase Enumerated Types\n=========================\n\nA very common use of enumerated types are to give semantic meaning to integer\nvalues stored in database columns. EnumeratedType Items themselves don't have\nany integer values.\n\nThe DBEnumeratedType provides the semantic framework for a type that is used to\nmap integer values to python enumerated values.\n\n >>> # Remove the existing reference to BranchType from the registry\n >>> del enumerated_type_registry['BranchType']\n >>> class BranchType(DBEnumeratedType):\n ... HOSTED = DBItem(1, \"\"\"\n ... Hosted\n ...\n ... Hosted braches use the supermirror as the main repository\n ... for the branch.\"\"\")\n ...\n ... MIRRORED = DBItem(2, \"\"\"\n ... Mirrored\n ...\n ... Mirrored branches are \"pulled\" from a remote location.\"\"\")\n ...\n ... IMPORTED = DBItem(3, \"\"\"\n ... Imported\n ...\n ... Imported branches are natively maintained in CVS or SVN\"\"\")\n\nNote carefully that the value of a DBItem is the integer representation. But\nthe value of the TokenizedItem is the DBItem itself.\n\n >>> hosted = BranchType.HOSTED\n >>> hosted.value\n 1\n >>> hosted == BranchType.HOSTED\n True\n >>> tokenized_item = BranchType.getTermByToken('HOSTED')\n >>> tokenized_item.value\n <DBItem BranchType.HOSTED, (1) Hosted>\n\nDBEnumeratedTypes also support IVocabularyTokenized\n\n >>> verifyObject(IVocabularyTokenized, BranchType)\n True\n\nThe items attribute of DBEnumeratedTypes provide a mapping from the database\nvalues to the DBItems.\n\n >>> BranchType.items[3]\n <DBItem BranchType.IMPORTED, (3) Imported>\n\nThe items also support the url field.\n\n >>> class Bass(DBEnumeratedType):\n ... FENDER = DBItem(10, 'Fender', url='http://www.fender.com')\n ... RICK = DBItem(20, 'Rickenbacker',\n ... url='http://www.rickenbacker.com')\n ... GIBSON = DBItem(30, 'Gibson', url='http://www.gibson.com')\n ... FRANKENBASS = DBItem(40, 'Home built')\n\n >>> print(Bass.FENDER.url)\n http://www.fender.com\n >>> print(Bass.FRANKENBASS.url)\n None\n\nItems in a DBEnumeratedType class must be of type DBItem.\n\n >>> class BadItemType(DBEnumeratedType):\n ... TESTING = Item(\"Testing\")\n Traceback (most recent call last):\n ...\n TypeError: Items must be of the appropriate type for the DBEnumeratedType,\n ...builtin...BadItemType.TESTING\n\nYou are not able to define a DBEnumeratedType that has two different\nDBItems that map to the same numeric value.\n\n >>> class TwoMapping(DBEnumeratedType):\n ... FIRST = DBItem(42, 'First')\n ... SECOND = DBItem(42, 'Second')\n Traceback (most recent call last):\n ...\n TypeError: Two DBItems with the same value 42 (FIRST, SECOND)\n\n=========================\nOverriding the sort order\n=========================\n\nBy default the sort order of the items in an enumerated type is defined by the\norder in which the Items are declared. This my be overridden by specifying\na sort_order attribute in the class.\n\nIf a sort_order is specified, it has to specify every item in the enumeration.\n\n >>> class AnimalClassification(EnumeratedType):\n ... sort_order = \"REPTILE\", \"INSECT\", \"MAMMAL\"\n ... INSECT = Item(\"Insect\")\n ... MAMMAL = Item(\"Mammal\")\n ... FISH = Item(\"Fish\")\n ... REPTILE = Item(\"Reptile\")\n Traceback (most recent call last):\n ...\n TypeError: sort_order for EnumeratedType must contain all and only Item instances ...\n\nThe sort_order may also appear anywhere in the definition of the class,\nalthough convention has it that it appears first, before the Item instances.\n\n >>> class AnimalClassification(EnumeratedType):\n ... sort_order = \"REPTILE\", \"FISH\", \"INSECT\", \"MAMMAL\"\n ... INSECT = Item(\"Insect\")\n ... MAMMAL = Item(\"Mammal\")\n ... FISH = Item(\"Fish\")\n ... REPTILE = Item(\"Reptile\")\n\nThe items attribute of the enumerated type is ordered based on the sort_order.\nThe items attribute is also used to control iteration using __iter__.\n\n >>> for item in AnimalClassification.items:\n ... print(item.title)\n Reptile\n Fish\n Insect\n Mammal\n\nThe sort order also drives the comparison operations.\n\n >>> reptile, fish, insect, mammal = AnimalClassification.items\n >>> reptile < fish < insect < mammal\n True\n\n==========================\nExtending enumerated types\n==========================\n\nThe simplest way to extend a class is to derive from it.\n\n >>> class AnimalClassificationExtended(AnimalClassification):\n ... INVERTEBRATE = Item(\"Invertebrate\")\n\n >>> for item in AnimalClassificationExtended:\n ... print(item.title)\n Reptile\n Fish\n Insect\n Mammal\n Invertebrate\n\nThe use_template function inserts the items from the specified enumerated type\ninto the new enumerated type. The default case is to take all the enumerated\nitems.\n\n >>> class UIBranchType(EnumeratedType):\n ... use_template(BranchType)\n >>> for item in UIBranchType:\n ... print(item.title)\n Hosted\n Mirrored\n Imported\n\nYou can also specify items to be excluded by referring to the attribute name\nin the exclude parameter. This can be either a string referring to one name\nor a tuple or list that refers to multiple attribute names.\n\n >>> class UIBranchType2(EnumeratedType):\n ... use_template(BranchType, exclude='IMPORTED')\n >>> for item in UIBranchType2:\n ... print(item.title)\n Hosted\n Mirrored\n\nOr limit the items to those specified:\n\n >>> class UIBranchType3(EnumeratedType):\n ... use_template(BranchType, include=('HOSTED', 'MIRRORED'))\n >>> for item in UIBranchType3:\n ... print(item.title)\n Hosted\n Mirrored\n\n================================================\nGetting from an item back to the enumerated type\n================================================\n\nEach Item in an EnumeratedType has a reference back to the EnumeratedType.\n\n >>> print(repr(apple))\n <Item Fruit.APPLE, Apple>\n >>> print(repr(apple.enum))\n <EnumeratedType 'Fruit'>\n >>> for item in apple.enum:\n ... print(item.title)\n Apple\n Pear\n Orange\n\n============\nItem.sortkey\n============\n\nThe sortkey attribute of the Items are defined by the sort_order that is\ndefined for the enumerated type. The value is often used as a hidden value\nin columns in order to ensure appropriate sorting.\n\n >>> for item in Fruit.items:\n ... print(item.title, item.sortkey)\n Apple 0\n Pear 1\n Orange 2\n\n >>> for item in BranchType.items:\n ... print(item.title, item.sortkey)\n Hosted 0\n Mirrored 1\n Imported 2\n\n============\nJSON Support\n============\n\nEnumerated types instances can be serialised to/from json. This library provides the\nnecessary encode and decode classes which can be used directly or as part of the\nlazr.json package where they are registered as default handlers for lazr enums.\n\nA enum instance is serialised as a dict containing:\n- the enumerated type name as per the enumerated_type_registry\n- the enum instance name\n\n >>> import json\n >>> from lazr.enum import EnumJSONEncoder\n\n >>> json_enum = json.dumps(\n ... Fruit.APPLE, cls=EnumJSONEncoder, sort_keys=True)\n >>> print(json_enum)\n {\"name\": \"APPLE\", \"type\": \"Fruit\"}\n\nTo deserialse, we can specify a json object_hook as follows.\nThis is done transparently when using the lazr.json package.\n\n >>> def fruit_enum_decoder(value_dict):\n ... return EnumJSONDecoder.from_dict(Fruit, value_dict)\n\n >>> from lazr.enum import EnumJSONDecoder\n >>> json.loads(json_enum, object_hook=fruit_enum_decoder)\n <Item Fruit.APPLE, Apple>\n\n\n==================\nNEWS for lazr.enum\n==================\n\n1.2.2 (2024-12-05)\n==================\n\n- Add support for Python 3.9, 3.10, 3.11, 3.12 and 3.13.\n- Drop support for Python 3.7 and below\n- Add basic pre-commit configuration.\n- Publish documentation on Read the Docs.\n\n1.2.1 (2021-09-13)\n==================\n\n- Adjust versioning strategy to avoid importing pkg_resources, which is slow\n in large environments.\n\n1.2 (2019-11-24)\n================\n\n- Switch from buildout to tox.\n- Add Python 3 support.\n\n1.1.4 (2012-04-18)\n==================\n\n- Support for serialising enums to/from json (lp:984549)\n- Items which are not in an enumerator always compare as False (lp:524259)\n- Fix the licence statement in _enum.py to be LGPLv3 not LGPLv3+ (lp:526484)\n\n1.1.3 (2011-04-20)\n==================\n\n- added case insensitivity to getting the term by the token value (lp:154556)\n\n1.1.2 (2009-08-31)\n==================\n\n- removed unnecessary build dependencies\n\n1.1.1 (2009-08-06)\n==================\n\n- Removed sys.path hack from setup.py.\n\n1.1 (2009-06-08)\n================\n\n- Added `url` argument to the BaseItem and DBItem constructors.\n\n\n1.0 (2009-03-24)\n================\n\n- Initial release on PyPI\n",
"bugtrack_url": null,
"license": "LGPL v3",
"summary": "Enums with zope.schema vocabulary support and database-friendly conveniences.",
"version": "1.2.2",
"project_urls": {
"Documentation": "https://lazrenum.readthedocs.io/en/latest/",
"Download": "https://launchpad.net/lazr.enum/+download",
"Homepage": "https://launchpad.net/lazr.enum",
"Issue Tracker": "https://bugs.launchpad.net/lazr.enum",
"Source": "https://code.launchpad.net/lazr.enum"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "e70e7d81cf06c2d9548b405ebbc8a6df4c4d9570f3d36c22400bb3a1028a1057",
"md5": "26976c40a72e9aa370480a0c413f841d",
"sha256": "bac9884f951a656e99905e654f73cc2f59c38801bb308587fe6e80ff798785be"
},
"downloads": -1,
"filename": "lazr.enum-1.2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "26976c40a72e9aa370480a0c413f841d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 26052,
"upload_time": "2024-12-05T09:55:22",
"upload_time_iso_8601": "2024-12-05T09:55:22.565823Z",
"url": "https://files.pythonhosted.org/packages/e7/0e/7d81cf06c2d9548b405ebbc8a6df4c4d9570f3d36c22400bb3a1028a1057/lazr.enum-1.2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "047f57647073d890aadc5a95a86ded4144954bd33456c463c6d15893f0a25243",
"md5": "ad3345f638b2e91b928d8c19369d8f70",
"sha256": "a849dc3e730ec357358278bbef584229da2591a19dece79459d7fe3b5727069b"
},
"downloads": -1,
"filename": "lazr_enum-1.2.2.tar.gz",
"has_sig": false,
"md5_digest": "ad3345f638b2e91b928d8c19369d8f70",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 25234,
"upload_time": "2024-12-05T09:55:24",
"upload_time_iso_8601": "2024-12-05T09:55:24.815438Z",
"url": "https://files.pythonhosted.org/packages/04/7f/57647073d890aadc5a95a86ded4144954bd33456c463c6d15893f0a25243/lazr_enum-1.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-05 09:55:24",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "lazr.enum"
}