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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Efficient String Formatting With Python f-Strings
  • Python F-Strings
  • Python Variables Declaration
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Trending

  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Ensuring Configuration Consistency Across Global Data Centers
  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Unlocking the Benefits of a Private API in AWS API Gateway
  1. DZone
  2. Coding
  3. Languages
  4. New in Python: Syntax for Variable Annotations

New in Python: Syntax for Variable Annotations

Time to take a look at a new feature in Python, namely ''syntax for variable annotations.'' We'll take a look at what this is along with some examples.

By 
Mike Driscoll user avatar
Mike Driscoll
·
Jan. 17, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.9K Views

Join the DZone community and get the full member experience.

Join For Free

Python 3.6 added another interesting new feature that is known as Syntax for variable annotations. This new feature is outlined in PEP 526. The basic premise of this PEP is to take the idea of Type Hinting (PEP 484) to its next logical step, which is basically adding option type definitions to Python variables, including class variables and instance variables. Please note that adding these annotations or definitions does not suddenly make Python a statically typed language. The interpreter still doesn’t care what type the variable is. However, a Python IDE or other utility like pylint could have an annotation checker added to them that could highlight when you use a variable that you have annotated as one type and then used incorrectly by changing its type mid-function.

Let’s look at a simple example so we can see how this works:

# annotate.py
name: str = 'Mike'


What we have here is a Python file that we have named annotate.py. In it, we have created a variable, name, and annotated it to indicate it is a string. This is done by adding a colon after the variable name and then specifying what type it should be. You don’t have to assign anything to the variable if you don’t want to. The following is just as valid:

# annotate.py
name: str


When you annotate a variable, it will get added to the module’s or class’s __annotations__ attribute. Let’s try importing the first version of our annotate module and access that attribute:

>>> import annotate
>>> annotate.__annotations__
{'name': <class 'str'>}
>>> annotate.name
'Mike'


As you can see, the __annotations__ attribute returns a Python dict with the variable name as the key and the type as the value. Let’s add a couple of other annotations to our module and see how the __annotations__ attribute updates.

# annotate2.py
name: str = 'Mike'

ages: list = [12, 20, 32]

class Car:
    variable: dict


In this code, we add an annotated list variable and a class with an annotated class variable. Now let’s import our new version of the annotate module and check out its __annotations__ attribute:

>>> import annotate
>>> annotate.__annotations__
{'name': <class 'str'>, 'ages': <class 'list'>}
>>> annotate.Car.__annotations__
{'variable': <class 'dict'>}
>>> car = annotate.Car()
>>> car.__annotations__
{'variable': <class 'dict'>}


This time around, we see that the annotations dictionary contains two items. You will note that the module level __annotations__ attribute does not contain the annotated class variable. To get access to that, we need to access the Car class directly or create a Car instance and access the attribute that way.

Wrapping Up

I found this new feature to be really interesting. While I love Python’s dynamic nature, I can also see the value in knowing what type a variable should be after working with C++ for the past couple of years. Of course, due to Python’s excellent introspection support, figuring out an object’s type is trivial. But this new feature could make static checkers better and also make your code more obvious, especially when you have to go back and update a piece of software you haven’t worked with in a few months or years.

Additional Reading

  • PEP 526 – Syntax for variable annotations
  • PEP 484 – Type Hinting
  • Python 3.6: What’s New
Python (language) Annotation Syntax (programming languages)

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Efficient String Formatting With Python f-Strings
  • Python F-Strings
  • Python Variables Declaration
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: