DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Python Class Attributes are Evaluated on Declaration

Python Class Attributes are Evaluated on Declaration

Chase Seibert user avatar by
Chase Seibert
·
Apr. 24, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
4.05K Views

Join the DZone community and get the full member experience.

Join For Free

In Python, class attributes are evaluated and put into memory when the class is defined (or imported). For example, if you run the following code in an interactive interpreter, it will print out "Something __init__() called":

class Something:
    def __init__(self):
        print "Something __init__() called"

class UsesSomething:
    field = Something()

This surprised me, even though I've been coding almost entirely in Python for two years. I expected the print statement to execute if I instantiated a UsesSomething object, but I did not expect it to execute by simply declaring the class definition. In practice, the declaration is likely to be when you import the module containing the code.

This came up in a real world scenario when my Django app suddenly began taking a lot longer to start up. On a hunch, I started removing imports from urls.py until I found the one that was causing the slowness. Then I started removing code in that module, until I traced the problem to something like the following:

class MyForm(ModelForm):
    class Meta:
        model = MyModel
    field1 = MyChoiceField()

class MyChoiceField(ChoiceField):
    def __init__(self, choices=(), required=True, widget=None, label=None,
             initial=None, help_text=None, *args, **kwargs):
    super(ChoiceField, self).__init__(required, widget, label, initial,
                                      help_text, *args, **kwargs)     
    self.choices = [(m.id, m.name) for m in ReallyLargeTableModel.objects.all()] 

For me, this was a pretty standard pattern. I had a custom field that was pulling its set of valid choices from the database. As the full ReallyLargeTableModel data set got larger and larger, it eventually got larger than the maximum size our caching back-end would store, and thus the query started getting run every time the run time started up.

In this case, it's not hard to work around. Simply removing the list comprehension will allow Django to hold off on running the query until it actually requests the choices property (ie, when the field is displayed to the user). Alternatively, you could pass the data in from the MyForm constructor, which I gather is more idiomatic anyway.

Solutions are besides the point. In this case, the important take away is to be aware that class attributes will be evaluated on import, NOT when they are instantiated. So you want to avoid heavy weight operations or external dependencies in class attribute definitions.

 

Attribute (computing) Python (language)

Published at DZone with permission of Chase Seibert, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Hashtable, HashMap, ConcurrentHashMap: Performance Impact
  • DZone's Article Submission Guidelines
  • Don't Underestimate Documentation
  • OPC-UA, MQTT, and Apache Kafka: The Trinity of Data Streaming in IoT

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo