DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Python Class Attributes are Evaluated on Declaration

Python Class Attributes are Evaluated on Declaration

Chase Seibert user avatar by
Chase Seibert
·
Apr. 24, 12 · Interview
Like (0)
Save
Tweet
Share
4.26K 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

  • Getting a Private SSL Certificate Free of Cost
  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Keep Your Application Secrets Secret
  • 5 Common Firewall Misconfigurations and How to Address Them

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: