How to Test If an Enum Member With a Certain Name Exists

How to test if an Enum member with a certain name exists?

You could use Enum.__members__ - an ordered dictionary mapping names to members:

In [12]: 'One' in Constants.__members__
Out[12]: True

In [13]: 'Four' in Constants.__members__
Out[13]: False

How do I test if int value exists in Python Enum without using try/catch?

test for values

variant 1

note that an Enum has a member called _value2member_map_ (which is undocumented and may be changed/removed in future python versions):

print(Fruit._value2member_map_)
# {4: <Fruit.Apple: 4>, 5: <Fruit.Orange: 5>, 6: <Fruit.Pear: 6>}

you can test if a value is in your Enum against this map:

5 in Fruit._value2member_map_  # True
7 in Fruit._value2member_map_ # False

variant 2

if you do not want to rely on this feature this is an alternative:

values = [item.value for item in Fruit]  # [4, 5, 6]

or (probably better): use a set; the in operator will be more efficient:

values = set(item.value for item in Fruit)  # {4, 5, 6}

then test with

5 in values  # True
7 in values # False

add has_value to your class

you could then add this as a method to your class:

class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6

@classmethod
def has_value(cls, value):
return value in cls._value2member_map_

print(Fruit.has_value(5)) # True
print(Fruit.has_value(7)) # False
test for keys

if you want to test for the names (and not the values) i would use _member_names_:

'Apple' in Fruit._member_names_  # True
'Mango' in Fruit._member_names_ # False

Check if enum exists in Java

I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:

public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}

Edit: As Jon Skeet notes, values() works by cloning a private backing array every time it is called. If performance is critical, you may want to call values() only once, cache the array, and iterate through that.

Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.

How to check if string exists in Enum of strings?

I just bumped into this problem today; I had to change a number of subpackages for Python 3.8.

Perhaps an alternative to the other solutions here is the following, inspired by the excellent answer here to a similar question, as well as @MadPhysicist's answer on this page:

from enum import Enum, EnumMeta


class MetaEnum(EnumMeta):
def __contains__(cls, item):
try:
cls(item)
except ValueError:
return False
return True


class BaseEnum(Enum, metaclass=MetaEnum):
pass


class Stuff(BaseEnum):
foo = 1
bar = 5

Tests (either in py37 or 38):

>>> 1 in Stuff
True

>>> Stuff.foo in Stuff
True

>>> 2 in Stuff
False

>>> 2.3 in Stuff
False

>>> 'zero' in Stuff
False

Check if value exists in enum in TypeScript

If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value) because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:

enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}

becomes:

{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}

So you just need to do:

if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}

If you get an error for: Property 'values' does not exist on type 'ObjectConstructor', then you are not targeting ES2017. You can either use this tsconfig.json config:

"compilerOptions": {
"lib": ["es2017"]
}

Or you can just do an any cast:

if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}

How to check If a Enum contain a number?

The IsDefined method requires two parameters. The first parameter is the type of the enumeration to be checked. This type is usually obtained using a typeof expression. The second parameter is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.

enum Status
{
OK = 0,
Warning = 64,
Error = 256
}

static void Main(string[] args)
{
bool exists;

// Testing for Integer Values
exists = Enum.IsDefined(typeof(Status), 0); // exists = true
exists = Enum.IsDefined(typeof(Status), 1); // exists = false

// Testing for Constant Names
exists = Enum.IsDefined(typeof(Status), "OK"); // exists = true
exists = Enum.IsDefined(typeof(Status), "NotOK"); // exists = false
}

SOURCE

How to check if a given string key exists in Enum?

You could use the in operator:

if ('value4' in someEnum) {
// ...
}

How to check if enum value exists in a list of objects

If using java8, it can be done via lambda expression

for(catType ct : catType.values()) {
boolean exist = zoos.stream()
.anyMatch(zoo -> zoo.getAnimal().equals(ct.toString()));

}

how to check if string value is in the Enum list?

You can use:

 Enum.IsDefined(typeof(Age), youragevariable)


Related Topics



Leave a reply



Submit