1# Copyright 2024 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Enum-like object utilities 16 17This is a separate file to minimize transitive loads. 18""" 19 20def enum(methods = {}, **kwargs): 21 """Creates a struct whose primary purpose is to be like an enum. 22 23 Args: 24 methods: {type}`dict[str, callable]` functions that will be 25 added to the created enum object, but will have the enum object 26 itself passed as the first positional arg when calling them. 27 **kwargs: The fields of the returned struct. All uppercase names will 28 be treated as enum values and added to `__members__`. 29 30 Returns: 31 `struct` with the given values. It also has the field `__members__`, 32 which is a dict of the enum names and values. 33 """ 34 members = { 35 key: value 36 for key, value in kwargs.items() 37 if key.upper() == key 38 } 39 40 for name, unbound_method in methods.items(): 41 # buildifier: disable=uninitialized 42 kwargs[name] = lambda *a, **k: unbound_method(self, *a, **k) 43 44 self = struct(__members__ = members, **kwargs) 45 return self 46