Hướng dẫn python isinstance enum

I have an enum like this

@enum.unique
class TransactionTypes(enum.IntEnum):
    authorisation = 1
    balance_adjustment = 2
    chargeback = 3
    auth_reversal = 4

Now i am assigning a variable with this enum like this

a = TransactionTypes

I want to check for the type of 'a' and do something if its an enum and something else, if its not an enum

I tried something like this

if type(a) == enum:
    print "do enum related stuff"
else:
    print "do something else"

The problem is it is not working fine.

asked Jul 15, 2016 at 10:32

2

Now i am assigning a variable with this enum like this

a = TransactionTypes

I hope you aren't, because what you just assigned to a is the entire enumeration, not one of its members (such as TransactionTypes.chargeback) If that is really what you wanted to do, then the correct test would be:

if issubclass(a, enum.Enum)

However, if you actually meant something like:

a = TransactionTypes.authorisation

then the test you need is:

# for any Enum member
if isinstance(a, Enum):

or

# for a TransactionTypes Enum
if isinstance(a, TransactionTypes):

answered Jul 15, 2016 at 17:31

Ethan FurmanEthan Furman

59.4k18 gold badges146 silver badges220 bronze badges

0

reliable solution:

from enum import IntEnum
from collections import Iterable

def is_IntEnum(obj):
    try:
        return isinstance(obj, Iterable) and isinstance (next(iter(obj)), IntEnum)
    except:
        return False # Handle StopIteration, if obj has no elements

answered Feb 15, 2021 at 18:29

5

I thought I`ve got a ugly way. eg:

print(o.__class__.__class__) 

Output:


Hướng dẫn python isinstance enum

S.B

8,7787 gold badges19 silver badges40 bronze badges

answered Sep 20, 2021 at 14:40

1

as mentioned use isinstance method to check weather an instance is of enum.Enum type or not.

A small working code for demonstration of its usage:

import enum


class STATUS(enum.Enum):
    FINISHED = enum.auto()
    DELETED = enum.auto()
    CANCELLED = enum.auto()
    PENDING = enum.auto()


if __name__ == "__main__":
    instance = STATUS.CANCELLED

    if isinstance(instance, enum.Enum):
        print('name : ', instance.name, ' value : ', instance.value)
    else:
        print(str(instance))

Output:

name :  CANCELLED  value :  3

answered Feb 20 at 9:59

devpdevp

1,9532 gold badges11 silver badges23 bronze badges

Not the answer you're looking for? Browse other questions tagged python-2.7 enums typechecking or ask your own question.

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn delete list python

Nội dung chínhLấy ra và xóa phần tử của list theo index | phương thức pop()Xóa phần tử trong phạm vi chỉ định | lệnh delXóa phần tử đầu tiên trong list giống ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng query mongodb python

Lời nói đầu.Xin chào mọi người đã quay trở lại seria bài viết về python của mình . Ai cần đọc về bài viết về python phần 1, 2 và 3 của mình thì click ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng running def python

Function (hay còn gọi là Hàm): Là một khối lệnh được đóng gói lại thành một đơn vị độc lập, dùng để thực hiện một tác vụ trong chương trình.Nội dung ...

Hướng dẫn python isinstance enum

Hướng dẫn python multiprocessing array append

Source code: Lib/multiprocessing/Introduction¶multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng variable names python

Như bài trước thì mình đã đi tìm hiểu qua cơ bản về python và chạy chương trình đầu tiên, chương trình muôn thủa Hello world. Nếu bạn nào chưa xem thì xem ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng plotly subplots python

Simple Subplot¶Figures with subplots are created using the make_subplots function from the plotly.subplots module.Here is an example of creating a figure that includes two scatter traces which are ...

Hướng dẫn python isinstance enum

Kiểu dữ liệu xâu trong python

Lập trình Python1. Tìm hiểu kiểu dữ liệu xâu (str)– Xâu là dãy các ký tự được đặt trong cặp dấu nháy đơn ‘ và ‘ hoặc nháy kép “ và “.– Xâu rỗng ...

Hướng dẫn python isinstance enum

Python count if greater than

I have a list of numbers and I want to get the number of times a number appears in a list that meets a certain criteria. I can use a list comprehension (or a list comprehension in a function) but I ...

Hướng dẫn python isinstance enum

Python random 0 or 1

The problem is that your code generates a single value and then prints it repeatedly. A simplified version of the problem would be this:k = random.randint(0, 1) # decide on k once for _ in range(n): ...

Hướng dẫn python isinstance enum

Hướng dẫn .dtypes python

Pandas là một thư viện Python cung cấp các cấu trúc dữ liệu nhanh, mạnh mẽ, linh hoạt và mang hàm ý. Tên thư viện được bắt nguồn từ panel data (bảng dữ ...

Hướng dẫn python isinstance enum

Hướng dẫn base64 encode python

Chào mọi người, trong bài viết hôm nay mình xin cố gắng đi sâu vào một khái niệm mà có lẽ tất cả chúng ta đã từng gặp và sử dụng khá nhiều trong công ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng duplicate meaning python

If using a third-party package would be okay then you could use iteration_utilities.unique_everseen:>>> from iteration_utilities import unique_everseen >>> l = [{a: 123}, {b: ...

Hướng dẫn python isinstance enum

Multi-line comment in python shortcut

You are here: Home / Comments / Shortcut to comment out multiple lines in PythonWe often need to comment out block of codes in python while testing or debugging the code. When a block is turned ...

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn dùng srtings python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn dùng using python python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn python isinstance enum

Reaching ground floor in python assignment expert

You are on the top floor of a multiplex complex and want to go the ground floor,The lift is not working so you have to search for the staircase on each floor and go down to the exit.As you are new to ...

Hướng dẫn python isinstance enum

Hướng dẫn python union type

New in version 3.5.Source code: Lib/typing.pyNoteThe Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, ...

Hướng dẫn python isinstance enum

Hướng dẫn codecs python example

Source code: Lib/codecs.pyNội dung chínhCodec Base Classes¶Error Handlers¶Stateless Encoding and Decoding¶Incremental Encoding and Decoding¶Stream Encoding and Decoding¶Encodings and ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng dict definition python

Mục lục Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi ...

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Concatenate list of arrays python

numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting=same_kind)#Join a sequence of arrays along an existing axis.Parametersa1, a2, …sequence of array_likeThe arrays must have ...

Hướng dẫn python isinstance enum

Hướng dẫn vowel python

This works for me and also counts the consonants as well (think of it as a bonus) however, if you really dont want the consonant count all you have to do is delete the last for loop and the last ...

Hướng dẫn python isinstance enum

Hướng dẫn declare decimal python

In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and …): to repeat the example, you must type everything after the prompt, when the ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng python scan python

Trong bài viết này, mình sẽ hướng dẫn các bạn cách tạo Port Scanner (Trình quét cổng) bằng Python đơn giản nhất. Chương trình sẽ sử dụng 2 thư viện rất ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng git opencv python

I.OpenCV là gì?1. Giới ThiệuOpenCV là một thư viện mã nguồn mở hàng đầu cho thị giác máy tính (computer vision), xử lý ảnh và máy học, và các tính năng tăng ...

Hướng dẫn python isinstance enum

How do you log transform an image in python?

c = 255/log(1+Maximum pixel value from the input image).#----- Example Python program for logarithmic transformation of a Digital Image -----# import Pillow modulesfrom PIL import Imagefrom PIL ...

Hướng dẫn python isinstance enum

Can i concatenate strings in python?

❮ Python GlossaryString ConcatenationString concatenation means add strings together.Use the + character to add a variable to another variable:Example x = Python is y = awesomez = x + y ...

Hướng dẫn python isinstance enum

Hướng dẫn python iterable

Trang chủ Lập trình Python Iterator và Iterable trong Python Trong hướng dẫn này chúng ta cùng đi tìm hiểu về Iterator và Iterable trong lập trình Python. Iterator và ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng traingular python

Last update on August 19 2022 21:51:49 (UTC/GMT +8 hours)Python Basic: Exercise-60 with Solution Write a Python program to calculate the hypotenuse of a right angled triangle.From Wikipedia, A right ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng excel sequence python

Hàm SEQUENCElà một hàm hiện tại chỉ xuất hiện trong phiên bản Office 365. Hàm này cho phép bạn tạo một danh sách các số liên tiếp trong một mảng. Trong bài ...

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn python isinstance enum

Hướng dẫn dùng you wr python

In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and …): to repeat the example, you must type everything after the prompt, when the ...

Hướng dẫn python isinstance enum

How to test python code

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Test-Driven Development With PyTestThis ...

Hướng dẫn python isinstance enum

Python format float as int

A quick no-brainer:some_float = 1234.5678 print %02d % some_float # 1234 some_float = 1234.5678 print {WHAT?}.format(some_float) # I want 1234 here too Note: {:.0f} is not an option, because it ...

Hướng dẫn python isinstance enum

Hướng dẫn dùng printed definition python

Nội dung chínhNội dung chínhSự khác nhau giữa hàm xuất dữ liệu trong Python2 và Python3Hàm print() trong PythonHàm print() trong Python là gìCú pháp và cách sử dụng ...