Skip to content
TheChatArchiveThe Chat Archive
Qwenqwq-32b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

Take a look at the following Enum class and a class used to describe a table with…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with chatgpt-4o-latest-20250326’s answer.
  1. User

    Take a look at the following Enum class and a class used to describe a table with SQLAlchemy:

    class Property(enum.Enum):
        residence = "residencia"
        health_post = "posto de saúde"
        pharmacy = "farmácia"
        warehouse = "armazem"
        supplier = "fornecedor"
    
    
    @final
    class Address(BaseModel):
        id: Mapped[int] = column(primary_key=True, autoincrement=True)
        street: Mapped[STRING] = column()
        number: Mapped[int | None] = column()
        complement: Mapped[STRING | None] = column()
        neighborhood_id = fk("neighborhood")
        postal_code = column(String(8), digits("postal_code"))
        type: Mapped[Property] = column()
    
        # Relationships
        neighborhood: Mapped["Neighborhood"] = relationship(
            back_populates="addresses"
        )
        residents: Mapped[list["Person"]] = relationship(back_populates="address")
        employees: Mapped[list["Employee"]] = relationship(
            back_populates="workplaces", secondary="workplaces_employee"
        )
        prescriptions: Mapped[list["Prescrition"]] = relationship(
            back_populates="health_post"
        )
        disposals: Mapped[list["Disposal"]] = relationship(
            back_populates="pharmacy"
        )
        medication_instances: Mapped[list["MedicationInstance"]] = relationship(
            backpopulates="location"
        )
    

    I'm finding it a bore to have to name a variable after each value an Enum class can assume. Is there a way that I could create an Enum class out of a list of sctrings, ina way that would be compatible with SQLAlchemy?

  2. Qwen Assistant

    Yes, you can create an Enum class dynamically from a list of strings (or tuples) to avoid manually defining each member. Here's how to do it while keeping compatibility with SQLAlchemy:

    Step 1: Define Your Values as a List of Tuples

    Instead of writing each Enum member individually, define a list of tuples where each tuple contains the member name and value:

    properties = [
        ('residence', 'residencia'),
        ('health_post', 'posto de saúde'),
        ('pharmacy', 'farmácia'),
        ('warehouse', 'armazem'),
        ('supplier', 'fornecedor'),
    ]
    

    Step 2: Dynamically Create the Enum

    Use Python's enum.Enum to generate the Enum class programmatically:

    from enum import Enum
    
    class Property(Enum):
        pass  # This is just a placeholder; we'll populate it dynamically
    
    # Populate the Enum using the list of tuples
    Property.__members__.clear()  # Clear any existing members
    for name, value in properties:
        Property[name] = value
    

    Alternatively, you can create the Enum directly from the list without the placeholder:

    from enum import Enum
    
    Property = Enum('Property', {name: value for name, value in properties})
    

    Step 3: Use the Enum in SQLAlchemy

    Ensure your SQLAlchemy column is configured to use the Property enum. For SQLAlchemy 2.0+ with type annotations:

    from sqlalchemy import Enum as SQLAlchemyEnum
    from sqlalchemy.orm import Mapped, mapped_column
    
    class Address(BaseModel):
        # ... other columns ...
    
        type: Mapped[Property] = mapped_column(
            SQLAlchemyEnum(Property),
            nullable=False  # Or any other constraints
        )
    
        # ... rest of your model ...
    

    Full Example

    Putting it all together:

    # Define the list of properties
    properties = [
        ('residence', 'residencia'),
        ('health_post', 'posto de saúde'),
        ('pharmacy', 'farmácia'),
        ('warehouse', 'armazem'),
        ('supplier', 'fornecedor'),
    ]
    
    # Create the Enum dynamically
    from enum import Enum
    Property = Enum('Property', {name: value for name, value in properties})
    
    # Use it in SQLAlchemy
    from sqlalchemy import Enum as SQLAlchemyEnum
    from sqlalchemy.orm import Mapped, mapped_column
    
    class Address(BaseModel):
        id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
        street: Mapped[str] = mapped_column(String)
        # ... other columns ...
    
        type: Mapped[Property] = mapped_column(
            SQLAlchemyEnum(Property),
            nullable=False
        )
    
        # ... relationships ...
    

    Key Points:

    1. Dynamic Enum Creation: The Enum('Property', {name: value}) syntax creates an Enum class from a dictionary of {member_name: member_value} pairs.
    2. SQLAlchemy Compatibility: Use SQLAlchemyEnum(Property) to map the Python Enum to an SQL ENUM type.
    3. Maintainability: If your list of values changes, you only need to update the properties list instead of modifying the Enum class directly.

    This approach reduces boilerplate and makes your code easier to maintain.

  3. User

    Ok, lets try again, is there a way that I can convert a list of integers int an Enum type?

  4. Qwen Assistant

    Yes, you can dynamically create an Enum class from a list of integers in Python, and use it with SQLAlchemy. Here's how to do it effectively, including compatibility with SQLAlchemy:


    Step 1: Define Your List of Integers (with Names)

    First, define your list of integers. You can either:

    1. Provide explicit names and values (recommended for clarity):

      members = [
          ('ACTIVE', 1),
          ('INACTIVE', 0),
          ('PENDING', 2),
          ('DELETED', 3),
      ]
      
    2. Auto-generate names from a list of integers (if you don't have names):

      values = [1, 0, 2, 3]
      members = [(f"VALUE_{v}", v) for v in values]  # Names like "VALUE_1", "VALUE_0", etc.
      

    Step 2: Dynamically Create the Enum Class

    Use Python's Enum to generate the Enum class programmatically:

    Explicit Names and Values

    from enum import Enum
    
    # Create the Enum dynamically
    Property = Enum('Property', {name: value for name, value in members})
    

    Auto-Generated Names

    from enum import Enum
    
    values = [1, 0, 2, 3]
    members = [(f"VALUE_{v}", v) for v in values]
    
    Property = Enum('Property', {name: value for name, value in members})
    

    Step 3: Use the Enum with SQLAlchemy

    Since the Enum values are integers, you do not use SQLAlchemy's ENUM type (which expects strings). Instead, map the Enum to an Integer column and let SQLAlchemy handle the conversion automatically.

    SQLAlchemy Column Definition

    from sqlalchemy import Integer
    from sqlalchemy.orm import Mapped, mapped_column
    
    class Address(BaseModel):
        # ... other columns ...
    
        status: Mapped[Property] = mapped_column(
            Integer,  # Use Integer column type
            nullable=False,
            default=Property.ACTIVE  # Use the Enum member
        )
    
        # ... rest of your model ...
    

    Full Example

    Here's a complete example using explicit names and values:

    # Step 1: Define your list of tuples (name, value)
    members = [
        ('ACTIVE', 1),
        ('INACTIVE', 0),
        ('PENDING', 2),
        ('DELETED', 3),
    ]
    
    # Step 2: Dynamically create the Enum
    from enum import Enum
    Property = Enum('Property', {name: value for name, value in members})
    
    # Step 3: Use it with SQLAlchemy
    from sqlalchemy import Integer
    from sqlalchemy.orm import Mapped, mapped_column
    
    class Address(BaseModel):
        id: Mapped[int] = mapped_column(primary_key=True)
        status: Mapped[Property] = mapped_column(
            Integer,
            nullable=False,
            default=Property.ACTIVE
        )
        # ... other columns ...
    

    Key Notes

    1. Enum Values as Integers:

      • The Enum members now have integer values (e.g., Property.ACTIVE.value == 1).
      • SQLAlchemy maps these to an Integer column in the database.
    2. Database Schema:

      • The column type is Integer, not an ENUM type (since ENUM in SQL typically expects strings).
      • This approach avoids database-specific ENUM types and uses a standard INT column.
    3. Validation:

      • The Enum ensures that only valid integer values are used in your code (e.g., Property.ACTIVE instead of raw 1).
    4. Auto-Generated Names:

      • If you auto-generate names from a list of integers (like ["VALUE_1", 1]), ensure the names are valid Python identifiers.

    Alternative: Using SQLAlchemy's ENUM Type (Strings Only)

    If you want to use the ENUM type in the database (which requires string values), you can still do this by converting integers to strings:

    # Define members as strings (e.g., "1", "0")
    members = [
        ('ACTIVE', '1'),
        ('INACTIVE', '0'),
        ('PENDING', '2'),
        ('DELETED', '3'),
    ]
    
    Property = Enum('Property', {name: value for name, value in members})
    
    # Use SQLAlchemy's ENUM type (for string values)
    from sqlalchemy import Enum as SQLAlchemyEnum
    
    class Address(BaseModel):
        status: Mapped[Property] = mapped_column(
            SQLAlchemyEnum(Property),
            nullable=False,
            default=Property.ACTIVE
        )
    

    Why This Works

    • Type Safety: The Enum ensures only valid values are used in your Python code.
    • Database Compatibility: Using an Integer column avoids SQL ENUM type limitations and works across all databases.
    • Maintainability: You can update the list of values in one place instead of modifying the Enum class manually.

    This approach is clean, scalable, and fully compatible with SQLAlchemy!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.