Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 932423
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T20:39:58+00:00 2026-05-15T20:39:58+00:00

I have a code like: class Ordered(object): x = 0 z = 0 b

  • 0

I have a code like:

class Ordered(object):
    x = 0
    z = 0
    b = 0
    a = 0

print(dir(Ordered))

it prints:

[ ......., a, b, x, z]

How can I get fields in an original order: x, z, b, a?
I’ve seen similar behavior in Django Models.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T20:39:58+00:00Added an answer on May 15, 2026 at 8:39 pm

    As mentioned above, if you want to keep things simple, just use a eg _ordering attribute, which manually keeps track of ordering. Otherwise, here is a metaclass approach (like the one Django uses), which creates an ordering attribute automatically.

    Recording the original ordering

    Classes don’t keep track of the ordering of the attributes. You can however keep track of which order the field instances were created. For that, you’ll have to use your own class for fields (not int). The class keeps track of how many instances have already been made and each instance takes note of its position. Here is how you would do it for your example (storing integers):

    class MyOrderedField(int):
      creation_counter = 0
    
      def __init__(self, val):
        # Set the instance's counter, to keep track of ordering
        self.creation_counter = MyOrderedField.creation_counter
        # Increment the class's counter for future instances
        MyOrderedField.creation_counter += 1
    

    Creating an ordered_items attribute automatically

    Now that your fields have a number which can be used to order them, your parent class needs to use that somehow. You can do this a variety of ways, if I remember correctly, Django uses Metaclasses to do this, which is a bit wild for a simple class.

    class BaseWithOrderedFields(type):
      """ Metaclass, which provides an attribute "ordered_fields", being an ordered
          list of class attributes that have a "creation_counter" attribute. """
    
      def __new__(cls, name, bases, attrs):
        new_class = super(BaseWithOrderedFields, cls).__new__(cls, name, bases, attrs)
        # Add an attribute to access ordered, orderable fields
        new_class._ordered_items = [(name, attrs.pop(name)) for name, obj in attrs.items()
                                        if hasattr(obj, "creation_counter")]
        new_class._ordered_items.sort(key=lambda item: item[1].creation_counter)
        return new_class
    

    Using this metaclass

    So, how do you use this? First, you need to use our new MyOrderedField class when defining your attributes. This new class will keep track of the order in which the fields were created:

    class Ordered(object):
      __metaclass__ = BaseWithOrderedFields
    
      x = MyOrderedField(0)
      z = MyOrderedField(0)
      b = MyOrderedField(0)
      a = MyOrderedField(0)
    

    Then you can access the ordered fields in our automatically created attribute ordered_fields:

    >>> ordered = Ordered()
    >>> ordered.ordered_fields
    [('x', 0), ('z', 0), ('b', 0), ('a', 0)]
    

    Feel free to change this to an ordered dict or just return the names or whatever you need. Additionally, you can define an empty class with the __metaclass__ and inherit from there.

    Don’t use this!

    As you can see, this approach is a little overcomplicated and probably not suitable for most tasks or python developers. If you’re newish to python, you’ll probably spend more time and effort developing your metaclass than you would have if you just defined the ordering manually. Defining your own ordering manually is almost always going to be the best approach. Django do it automatically because the complicated code is hidden from the end developer, and Django is used far more often than it itself is written/maintained. So only if you’re developing a framework for other developers, then metaclasses may be useful for you.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 535k
  • Answers 535k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Use the object initializer syntax: button1.Tag = new Posicion() {… May 17, 2026 at 1:09 am
  • Editorial Team
    Editorial Team added an answer Even if you said you looked already into "graph/chart" libraries.… May 17, 2026 at 1:09 am
  • Editorial Team
    Editorial Team added an answer From https://support.microsoft.com/en-us/kb/812425: In Visual C# .NET or Visual C# 2005,… May 17, 2026 at 1:09 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

i have code like this public class People { public string name { get;
i have code like below. Base is the base class and D1, D2, D3
I have an enum class like the following: public enum Letter { OMEGA_LETTER(Omega), GAMMA_LETTER(Gamma),
I have code like this in a Rails 3 app I'm working on <%
I have some code like this if ($('.lblpricefrom > strong').html() == '£'){ $('.lblpricefrom').parents(div.resultsitem).hide();} But
I have theses models: class Year(models.Model): name = models.CharField(max_length=15) date = models.DateField() class Period(models.Model):
I have an object in a list that I need to rank several different
How can I position the numbers of an ordered list when the only element
i have this code <div id=aggregate style=display:inline> <%=Html.RadioButton(a, 1, true, new {id = meRadio})%><label>Me</label>
i have a Web App coded in ABAP / BSP. I´m interested to deliver

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.