python optional variable assignment

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python Optional Arguments: A How-To Guide

A Python optional argument is a type of argument with a default value. You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement.

There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

Find your bootcamp match

In this guide, we talk about what optional arguments are and how they work.

We’ll walk you through an example of optional arguments so you can learn how to use them in your programs. We’ll also discuss how to use the **kwargs method to accept variable numbers of arguments.

What is a Python Argument?

An argument is a value that is accepted by a Python function . This value becomes its own Python variable that can be used within a function. Consider the following code:

In this code, “day” is an argument. Whatever value you specify in parentheses when you call the show_the_day function will become “day”. In this case, “Thursday” is “day”.

The number of values we specify in a function call must be equal to the number of arguments that a function accepts. This is unless we use optional arguments. In which case, we can specify fewer arguments than a function accepts because some arguments are optional.

Python Optional Arguments

A Python optional argument is an argument with a default value. You can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when you call a function. This is because the default value will be used if one is not specified.

Arguments can have default values. This makes an argument optional. If an argument has a default value, then it will use that default value if no other value is specified.

Default arguments are assigned using the assignment operator:

This user-defined function accepts two arguments: student and grade. Grade is an optional function argument which means we do not need to specify a value for it when we call the print_student() function.

Optional Arguments Python Example

We’re going to write a program that counts how many of a particular coffee was sold at a coffee shop on a Thursday morning. To start, define a list of coffees that were sold that morning:

Next, write a function that counts how many of a particular coffee was sold:

This function accepts two arguments: coffees and to_find.

The first argument is the list of coffees. Our second argument is the name of the coffee whose total sales we want to calculate. The Python count() method counts how many instances of the coffee for which we are looking exists in the “coffees” list.

The second argument is optional. If we don’t specify a value for the “to_find” argument, that argument will become equal to “Espresso”. Next, let’s call the function:

This function call will make the value of “to_find” equal to “Latte” in our code. Let’s run the program and see what happens:

The code tells us that two lattes were sold. Now, call our function without a second value:

Our code returns:

We specified no value for “to_find” so, by default, its value became “Espresso”. We can see that if we specify no value for an argument, its default value is used. Otherwise, the value we specify is used for the argument.

Python Function Optional Arguments Error

Optional parameters must appear after required arguments when you define a function. Required arguments are those that do not have a default value assigned.

Required arguments are often called “required positional arguments” because they must be assigned at a particular position in a function call. If you specify an optional argument before a required argument, Python returns an error that looks like this:

positional argument follows keyword argument

This is because if optional arguments came before required arguments then it will eliminate the purpose of optional arguments. How would Python know what values to assign to what arguments if the optional ones came first?

Optional Arguments Python: **kwargs

The **kwargs keyword passes arguments to a function that are assigned to a particular keyword. **kwags represents an aribitrary number of keywords, whether that is zero, one, or more keywords. So, you can use **kwargs to use an optional argument with a function.

Let’s write a program that prints out information about the grades a student has earned on their tests to the console. To start, define a dictionary with some information about a student:

Our dictionary contains four keys and values. We’re going to write a function that prints out values from this dictionary to the console:

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

This function prints out a message stating “Student record for X”, where X is equal to the name of a student.

Next, our program prints out all the items in the “grades” variable to the console. “grades” uses the “**” syntax which means it contains a dictionary of keys and values over which we can iterate in our program.

Let’s call our function:

We have specified two arguments: the name of the student and the score they earned on their second test. The second argument needs to have a keyword because **kwargs represents keyword arguments. 

Let’s run our code and see if it works:

Our program informs us about the grade Amy, a student, earned in their second test. Try to pass another test score through our function as an argument:

Our function now accepts three arguments. The last two arguments are keyword arguments. Let’s run our program:

Our program shows us the grades that Amy earned in both her first and second test. This is because the **kwargs keyword accepts a variable number of arguments.

Our program also works if we do not specify any keyword arguments:

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

To learn more about coding in Python, read our How to Learn Python guide .

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

Master Python Optional Arguments Usage [Tutorial]

Bashir Alam

December 1, 2021

An argument is a value that is passed to the function when it is called. Sometimes, we need to have optional arguments as well, which means even if we will not pass the values, the program shouldn't return any error. In this tutorial, we will learn about Python optional arguments. We will discuss how we can pass Python optional arguments to the methods using various ways. We will cover default arguments, keyword arguments, and keyword arguments using different examples.

In this comprehensive guide, we will delve into everything you need to know about optional arguments in Python—from the basics like default and keyword arguments to advanced techniques like using *args and **kwargs . By the end of this article, you'll gain an in-depth understanding of Python optional arguments and how to use them effectively in various scenarios.

Getting Started with Python Optional Arguments

In Python, optional arguments allow for more flexible and dynamic function calls. Whether you're a beginner or an experienced developer, understanding Python optional arguments can add another tool to your programming toolbox. Let's dive into the basics.

Syntax of Python Arguments

The syntax for declaring an optional argument is straightforward. When defining a function, you assign a default value to the parameter, using the equals ( = ) sign.

In this example, name is an optional argument with a default value of "World".

There are different methods to implement optional arguments in Python, each with its own use case.

  • Default Value Arguments : By specifying a default value, you make the argument optional during a function call.
  • Keyword Arguments : You can also provide arguments by explicitly naming each one, allowing you to skip some optional arguments.
  • Variable-length Arguments : Using *args and **kwargs , you can accept a variable number of positional and keyword arguments, respectively.

1. Using Default Values

Here, b is an optional argument.

2. Using Keyword Arguments

With keyword arguments, you can specify values in any order.

Here when we can call power(base=3) and it will return 9 because the exponent defaults to 2.

3. Using *args and **kwargs

The *args and **kwargs syntax lets you pass a variable number of arguments to a function:

We can call this function with any number of positional and keyword arguments. For instance, func(1, 2, x=3, y=4) would print both (1, 2) for args and {'x': 3, 'y': 4} for kwargs .

Intermediate Techniques for Using Optional Arguments

1. leveraging *args for python optional positional arguments.

One of the powerful features of Python is the use of *args for optional positional arguments. This allows you to pass a variable number of non-keyword arguments to a function. Let's delve into how to use *args effectively in Python optional arguments.

Example 1: Variable-length tuple arguments

Example 2: Combining *args with normal arguments

2. Utilizing **kwargs in Python for Optional Keyword Arguments

The use of **kwargs in Python opens up even more possibilities for optional arguments , specifically for optional keyword arguments. In this section, we'll explore the syntax and functionality of **kwargs and see how it enriches your Python optional arguments toolkit.

2.1 Syntax and Functionality of **kwargs in Python Optional Arguments

The **kwargs syntax in Python allows you to pass a variable number of keyword arguments to a function. Essentially, it collects additional keyword arguments passed to a function into a dictionary. Here's a basic example:

In the example above, kwargs will be a dictionary containing the items {'name': 'Alice', 'age': 30, 'profession': 'Engineer'} .

2.2 Combining **kwargs with Positional Arguments and *args

You can combine **kwargs with positional arguments and *args . However, **kwargs must appear last in the function definition.

2.3 Using **kwargs to Extend Functionality

One common use of **kwargs is to extend the functionality of a function, allowing it to accept future optional keyword arguments without changing its interface.

Advanced Approaches to Python Optional Arguments

1. mixing positional and keyword arguments effectively.

Understanding how to mix positional and keyword arguments effectively is crucial for leveraging the full power of Python optional arguments. While Python offers considerable flexibility in how you call functions , there are certain rules and best practices that help you combine these types of arguments seamlessly.

1.1 Rules for Combining Types of Arguments in Python Optional Arguments

When it comes to function definitions in Python, the general rule for combining various types of arguments is:

  • Positional arguments must come before *args
  • *args must come before keyword arguments
  • Keyword arguments must come before **kwargs

Here is a simple example to demonstrate the rules:

In this example, arg1 and arg2 are positional arguments, *args catches additional optional positional arguments, kwarg1 is a keyword argument with a default value, and **kwargs captures additional optional keyword arguments.

1.2 Real-world Python Examples of Mixing Positional and Keyword Arguments

Dynamic Function Calls

Combining positional and keyword arguments allows for more dynamic function calls, as seen in the Python built-in print function .

In this example, print uses positional arguments to define what to print, and keyword arguments sep and end to customize the output.

Flexible Database Connection

Let's say you are working on a function that connects to a database. Using a combination of positional and keyword arguments makes the function extremely flexible.

In this example, host and port are positional arguments, *queries captures optional SQL queries, username and password are keyword arguments with default values, and **config_options captures additional optional configuration settings.

2. Argument Unpacking with * and ** in Python Functions

Argument unpacking using * and ** in Python functions serves as a powerful feature for handling Python optional arguments. It allows you to pass multiple arguments easily and adds flexibility to how functions are called. In this section, we will explore the use of these unpacking operators in the context of Python optional arguments.

2.1 How Unpacking Enhances Optional Arguments in Python

Using the * and ** operators allows you to unpack iterable and mapping objects like lists and dictionaries into function arguments. This mechanism makes it easier to work with python optional arguments in dynamic scenarios. You can handle varying numbers of arguments more conveniently, improving the flexibility of your Python code.

Here's an example to highlight the use of argument unpacking in function calls:

2.2 Python Code Examples for Argument Unpacking in Optional Args

Unpacking Lists into Positional Arguments

You can unpack a list or a tuple into positional arguments using the * operator.

Unpacking Dictionaries into Keyword Arguments

Dictionaries can be unpacked into keyword arguments using the ** operator.

Combining Positional and Keyword Argument Unpacking

You can combine both positional and keyword argument unpacking in a single function call for maximum flexibility.

3. Implementing None as a Smart Default Value

In Python, using None as a default value for function arguments offers a versatile approach to handle python optional arguments. This practice has distinct advantages, especially when you want to signal that a function parameter is optional. In this section, we will discuss why and when to use None as a default value, along with Python best practices.

3.1 Why and When to Use None in Python Optional Arguments

Utilizing None as a default value in function parameters allows you to distinguish between a caller who has not provided a value for an argument and a caller who has explicitly provided a None value. This makes None a smart choice for default values in python optional arguments.

When should you use None ?

  • When you want to make the argument optional without assuming any default behavior.
  • When the actual default value is mutable, and you want to avoid the potential pitfalls associated with mutable default values.

Here's a simple example:

3.2 Python Best Practices for Using None in Optional Args

Use Immutable Default Values : In Python, default values are evaluated only once, so using mutable default values like lists or dictionaries can lead to unexpected behavior. Using None avoids this issue.

Explicitly Check for None : Always use is None or is not None to check if an optional argument has been provided.

Using Optional Parameters in Popular Python Libraries

The use of optional parameters is widespread in many popular Python libraries, offering both flexibility and functionality to end-users. In this section, we explore how python optional arguments are implemented in three such libraries: NumPy, pandas , and Django.

1. NumPy Optional Arguments

NumPy, a library for numerical computations, makes extensive use of Python optional arguments to provide flexibility in functions.

Here, start and stop are mandatory arguments, while num and endpoint are optional.

In this example, array2 will contain 20 evenly spaced values from 0 to 1, not including the endpoint because we set endpoint=False .

2. pandas Optional Arguments

The pandas library, popular for data manipulation and analysis, also employs Python optional arguments effectively.

Here, filepath is a mandatory argument, and delimiter and header are optional.

In df2 , we specify a tab delimiter and indicate that there is no header row.

3. Django Optional Arguments

Django, a high-level Python web framework , allows for optional arguments in various functionalities, such as model and form definitions.

In this Django model field, max_length is required, while blank and null are optional.

In this example, the bio field is optional due to the blank=True optional argument.

Frequently Asked Questions on Python Optional Arguments

What are Python Optional Arguments?

Optional arguments in Python are function parameters that have default values specified. These arguments are optional during a function call, meaning if you don't provide a value for such an argument, the default value will be used.

How do I Declare an Optional Argument in Python?

To declare an optional argument, you assign a default value to a parameter while defining the function. For example, in the function definition def greet(name="World") , name is an optional argument with a default value of "World".

What's the Difference Between Positional and Keyword Arguments?

Positional arguments are the most common and must be passed in order from left to right. Keyword arguments, often used for optional parameters, can be passed in any order by explicitly naming each argument in the function call.

What Are *args and **kwargs ?

*args is used to pass a variable-length list of positional arguments. **kwargs is used for passing a variable-length list of keyword arguments. These are often used to make functions more flexible and can be combined with standard positional and keyword arguments.

Can I Use Mutable Default Values Like Lists or Dictionaries?

It's generally not recommended to use mutable default values like lists or dictionaries because they can lead to unexpected behavior. Instead, you can use None and initialize the mutable object within the function.

How Do I Make My Function Accept Any Number of Arguments?

You can use *args to accept any number of positional arguments and **kwargs to accept any number of keyword arguments. For example, the function definition def example(*args, **kwargs) can accept any number of positional and keyword arguments.

What Is Argument Unpacking?

Argument unpacking allows you to pass multiple arguments to a function by unpacking a list or tuple using * or a dictionary using ** . For instance, if you have a list args = [1, 2, 3] and a function def sum(a, b, c) , you can call sum(*args) to pass all values in the list as separate arguments.

How Do Popular Libraries Like NumPy and Pandas Use Optional Arguments?

Libraries like NumPy and pandas use Python optional arguments to offer more flexible interfaces. For instance, in NumPy's linspace function, you can optionally specify the number of points you want between a range or whether to include the endpoint. Similarly, in pandas' read_csv , you can optionally specify delimiters, headers, and many other reading options.

What Are the Best Practices for Using Optional Arguments?

Some best practices include using immutable types like None for default values, clearly documenting the function's behavior with Python optional arguments, and being cautious when combining *args and **kwargs with positional and keyword arguments.

Understanding Python optional arguments is critical for writing flexible and efficient code. In this comprehensive guide, we've delved into the basics of optional arguments, the syntax, and best practices. We've also looked at advanced techniques involving *args and **kwargs , as well as practical examples from popular Python libraries like NumPy, pandas, and Django. These concepts serve as essential tools for both beginners and experienced Python developers to write versatile functions that can adapt to various needs.

Additional Resources

  • Python Official Documentation on Function Arguments: Python 3 Function Arguments
  • NumPy Official Documentation: NumPy User Guide
  • pandas Official Documentation: pandas User Guide
  • Django Official Documentation: Django Models

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

Save my name and email in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

Exam certifications.

Certified Kubernetes Application Developer (CKAD)

CompTIA PenTest+ (PT0-002)

Red Hat EX407 (Ansible)

Hacker Rank Python

Privacy Policy

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Python Optional Arguments | Guide (With Examples)

Python script with optional parameters question marks checkboxes logo

Are you finding it challenging to work with optional arguments in Python? You’re not alone. Many developers find themselves in a similar situation, but there’s a tool that can make this process a breeze.

Think of Python’s optional arguments as a Swiss army knife – they can make your Python functions more flexible and powerful, providing a versatile and handy tool for various tasks.

This guide will walk you through the use of optional arguments in Python, from basic usage to advanced techniques. We’ll cover everything from defining and using optional arguments, handling different types of arguments, to troubleshooting common issues.

So, let’s dive in and start mastering Python optional arguments!

TL;DR: How Do I Use Optional Arguments in Python?

In Python, you can make function arguments optional by assigning them a default value, such as def greet(name='World'): . This allows the function to be called with fewer arguments than it is defined to allow.

Here’s a simple example:

In this example, the function greet is defined with one argument name that has a default value of ‘World’. When greet() is called without any argument, it uses the default value. When we call greet('Python') , it overrides the default value with the provided argument.

This is just a basic introduction to using optional arguments in Python. There’s much more to learn, including advanced usage and best practices. So, let’s dive deeper!

Table of Contents

Grasping the Basics of Python Optional Arguments

Mixing optional arguments with positional arguments, exploring alternative methods for optional arguments, navigating common challenges with python optional arguments, unraveling the fundamentals of python function arguments, the power of optional arguments in larger python projects, wrapping up: mastering python optional arguments.

At its core, an optional argument in Python is a function argument that assumes a default value if a value is not provided in the function call for that argument. It’s a powerful tool that can make your functions more versatile and easier to use.

Defining and Using Optional Arguments

Defining optional arguments in Python is straightforward. You simply assign a default value to the argument in the function definition. Let’s take a look at a simple example:

In this example, we defined a function greet with one argument name . The name argument has a default value of ‘World’. When we call greet() without any arguments, it uses the default value and prints ‘Hello, World!’. When we call greet('Python') , it overrides the default value with the provided argument and prints ‘Hello, Python!’.

Advantages and Potential Pitfalls

Using optional arguments in Python can make your functions more flexible. They allow you to create functions that can handle a varying number of arguments, making your code more reusable and easier to maintain.

However, there are some potential pitfalls to be aware of. One common mistake is forgetting that the default value is only evaluated once, at the point of function definition.

This can lead to unexpected behavior when using mutable default values, like lists or dictionaries.

For instance, consider the following code:

You might expect the function to return [1] and then [2] but it doesn’t. This is because the default value for target is evaluated once and the same list is used in each successive call.

To avoid this pitfall, it’s recommended to use None as the default value and create a new object inside the function, if necessary.

Python allows you to use optional arguments alongside positional arguments. Positional arguments are those whose values are assigned based on their order in the function call. Let’s look at an example:

In this example, the greet function has two arguments: greeting (positional argument) and name (optional argument). When we call greet('Hello') , it assigns ‘Hello’ to greeting and uses the default value for name . When we call greet('Hello', 'Python') , it assigns ‘Hello’ to greeting and ‘Python’ to name .

Combining Optional Arguments with Variable-Length Arguments

Python also gives you the ability to define functions with a variable number of arguments. These are known as variable-length arguments and are defined using *args for positional arguments and **kwargs for keyword arguments. Here’s how you can use them with optional arguments:

In this example, func has a required argument, an optional argument, and a variable-length argument. The variable-length argument *args collects any additional positional arguments and packs them into a tuple. The optional_arg uses its default value unless specified otherwise in the function call.

Best Practices

While Python’s flexibility with arguments can be powerful, it’s important to use these tools judiciously to keep your code clear and maintainable. Here are a few best practices:

  • Keep the number of arguments reasonable. Too many can make your function calls difficult to read and understand.

Use optional arguments to provide sensible defaults but remember that the default value is only evaluated once, at the point of function definition.

When using a mix of positional, optional, and variable-length arguments, order them correctly in the function definition: required positional arguments, then optional arguments, and finally *args and/or **kwargs .

Python’s flexibility doesn’t stop at basic optional arguments. There are more advanced techniques you can use to make your functions even more powerful and flexible. Two such techniques involve the use of *args and **kwargs .

Using *args and **kwargs

*args and **kwargs are special syntaxes in Python used in function definitions to allow for variable numbers of arguments. *args is used to pass a non-keyworded, variable-length argument list, while **kwargs allows you to pass keyworded, variable-length arguments. Let’s see how this works in practice:

In this example, func takes any number of non-keyworded and keyworded arguments. *args collects the non-keyworded arguments into a tuple, and **kwargs collects the keyworded arguments into a dictionary.

Advantages and Disadvantages

Using *args and **kwargs can make your functions incredibly flexible, as they can handle any number of arguments. This can be especially useful when you’re not sure how many arguments your function might need, or when you’re working with APIs or libraries that require such functionality.

However, there are also disadvantages to consider. Functions that accept *args and **kwargs can be more difficult to understand and debug, as it’s not immediately clear what arguments they accept. They can also lead to less explicit and self-documenting code, which can be an issue in large codebases or collaborative environments.

Recommendations

While *args and **kwargs are powerful tools, they should be used judiciously. Use them when they provide clear benefits, but avoid overusing them, as they can make your code harder to understand and maintain. Always strive to write clear, explicit code that other developers (or you in the future) can easily understand and work with.

While optional arguments in Python can be extremely beneficial, they also come with a few potential pitfalls. Let’s discuss some common issues you might encounter and how to overcome them.

Incorrect Argument Order

One common issue is incorrect argument order. In Python, positional arguments must always precede keyword arguments (including optional arguments). Failing to adhere to this order will result in a SyntaxError:

In the above example, we incorrectly placed the positional argument ‘Hello’ after the keyword argument name='Python' . To correct this, simply ensure that all positional arguments precede keyword arguments:

Missing Arguments

Another common issue is missing arguments. If a function expects an argument (whether positional or optional) and you forget to provide it, Python will raise a TypeError:

In this example, we forgot to provide the required positional argument greeting when calling the function greet() . To fix this, make sure to provide all required arguments in your function calls.

Remember, Python optional arguments can make your code more flexible and powerful, but they require careful handling. Always keep track of your argument order and make sure all required arguments are provided to avoid these common issues.

To fully grasp the concept of optional arguments in Python, it’s crucial to understand the fundamentals of function arguments in Python, including positional and keyword arguments, and the concept of default values.

Python Function Arguments

In Python, a function argument is a value that is passed into a function when it’s called. There are two types of function arguments in Python: positional arguments and keyword arguments.

In the above example, ‘Hello’ and ‘Python’ are positional arguments. They are called ‘positional’ because their values are assigned based on their position in the function call.

Positional vs Keyword Arguments

The main difference between positional and keyword arguments lies in how they are passed to a function. Positional arguments are passed in the order in which they are defined, while keyword arguments are passed by explicitly naming each argument and its value.

In this example, ‘Hello’ and ‘Python’ are keyword arguments. Notice that we can change the order of the arguments in the function call, because we are explicitly naming each argument.

Understanding Default Values

In Python, you can assign a default value to a function argument. This makes the argument optional, because the function can be called without providing a value for this argument. The function will then use the default value.

In this example, both greeting and name have default values. The greet() function can be called without any arguments, in which case it uses the default values. Alternatively, we can override the default values by providing our own arguments.

By understanding these fundamentals, you’ll have a solid foundation for mastering the use of optional arguments in Python.

Python optional arguments are not just for small scripts or simple functions. They play a crucial role in larger Python projects and libraries as well. They can make your code more flexible, easier to read, and maintain.

Optional Arguments in Python Libraries

Many popular Python libraries make extensive use of optional arguments. For example, libraries like Pandas and NumPy, which are widely used for data analysis and manipulation, have numerous functions with optional arguments. This allows these libraries to provide a high level of flexibility and customization, while keeping their APIs clean and easy to use.

Exploring Related Concepts

Once you’ve mastered Python optional arguments, there are many related concepts to explore. For instance, function overloading allows you to define multiple functions with the same name but different arguments. Python doesn’t support function overloading in the same way as languages like C++ or Java, but you can achieve similar functionality using optional arguments, *args , and **kwargs .

Decorators are another powerful feature in Python that can work with optional arguments. A decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. This can be particularly useful when you want to modify the behavior of a function based on its arguments.

Further Resources for Mastering Python Optional Arguments

If you’re interested in diving deeper into Python optional arguments and related concepts, here are some resources you might find useful:

  • Python’s official documentation on defining functions provides a thorough overview of function arguments, including optional arguments.

Real Python’s guide on function arguments offers an in-depth look at positional arguments, keyword arguments, *args , and **kwargs .

Python’s official documentation on decorators provides a concise explanation of decorators and how they work.

By understanding and mastering Python optional arguments, you’ll be well-equipped to write more flexible, maintainable, and powerful Python code.

In this comprehensive guide, we’ve delved into the world of optional arguments in Python. We’ve explored their basic usage, how they can be used alongside positional arguments, and even more advanced techniques involving *args and **kwargs .

We began with the basics, explaining how to define and use optional arguments in Python functions. We then moved on to more advanced territory, discussing how to use optional arguments with positional arguments and variable-length arguments.

We also explored alternative approaches, such as using *args and **kwargs , providing you with a wide range of tools to make your Python functions more flexible and powerful.

Along the way, we tackled common challenges you might face when using optional arguments, such as incorrect argument order and missing arguments, providing you with solutions and workarounds for each issue.

Here’s a quick comparison of the methods we’ve discussed:

Whether you’re just starting out with Python or you’re looking to level up your skills, we hope this guide has given you a deeper understanding of optional arguments and their capabilities.

Mastering Python optional arguments can make your code more flexible, robust, and easier to maintain. With the knowledge you’ve gained from this guide, you’re well-equipped to tackle any challenge that comes your way. Happy coding!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

java_lang_noclassdeffounderror_red_check_error_screen

5 Best Ways to Make an Argument Optional in Python

💡 Problem Formulation: In Python programming, defaults for function arguments enable the creation of more flexible and forgiving interfaces. Take, for example, a function intended to greet a user. In some cases, the name of the user may not be supplied, and the function should still operate, providing a generic greeting such as “Hello, Guest!”. This article discusses methods that allow arguments to be optional, with a focus on how they improve code reusability and readability.

Method 1: Using Default Parameters

Specifying default parameters in a function is the simplest way to make arguments optional in Python. By providing a default value during function definition, the argument becomes non-mandatory. If the caller doesn’t supply the argument, the function uses the default value.

Here’s an example:

In this example, the greet() function is defined with a default parameter where name defaults to "Guest" . When no argument is passed, “Guest” is used, and when an argument is provided, it replaces the default value.

Method 2: Using *args

The *args parameter allows a function to accept an arbitrary number of positional arguments. This can be used to make arguments optional by not requiring a positional argument to be passed at all. The function can then check if args is empty or not and act accordingly.

In this snippet, greet() captures all positional arguments in args . It checks if args is non-empty to choose the first item, otherwise defaults to “Guest”.

Method 3: Using **kwargs

Similarly, **kwargs allows for an arbitrary number of keyword arguments, which can be leveraged to provide optional arguments. This method capitalizes on the flexibility of keyword arguments enabling optional or additional context parameters.

With kwargs , the greet() function uses .get() to attempt to retrieve the “name” key, providing “Guest” as the default value if the key is not found.

Method 4: Using Type Annotations with Default Values

Python’s type annotations introduced in PEP 484 can also be combined with default values to signal the intended data type and default value of an optional parameter.

Type annotations add clarity to the expected type of the argument, and the provided default value makes it optional. This method is both explicit and readable.

Bonus One-Liner Method 5: Using a Lambda Function

Lambda functions provide a quick, one-liner approach to create small anonymous functions in Python. While less conventional for defining defaults, they can be used to create a function with optional arguments.

This lambda function behaves similarly to the other examples, where name is an optional parameter with a default value. It’s short and concise, best for simple functions.

Summary/Discussion

  • Method 1: Default Parameters. Easy to understand and implement. Might become less manageable with functions having a large number of arguments.
  • Method 2: *args. Versatile for an undefined number of positional arguments. Can be slightly less clear when reading the code, as it implies additional processing to access values.
  • Method 3: **kwargs. Great for optional keyword arguments with the flexibility to add more parameters. It may lead to unreadable function calls if overused.
  • Method 4: Type Annotations with Default Values. Enhances code readability and clarity on data types. Requires familiarity with type annotations to be fully appreciated.
  • Method 5: Lambda Functions. Great for simple, one-off functions with minimal complexity. Not suitable for complex functions or those requiring multi-line definitions.

Emily Rosemary Collins is a tech enthusiast with a strong background in computer science, always staying up-to-date with the latest trends and innovations. Apart from her love for technology, Emily enjoys exploring the great outdoors, participating in local community events, and dedicating her free time to painting and photography. Her interests and passion for personal growth make her an engaging conversationalist and a reliable source of knowledge in the ever-evolving world of technology.

Python Optional Arguments: A Complete Guide

Posted in PROGRAMMING LANGUAGE /   PYTHON

Python Optional Arguments: A Complete Guide

Vinay Khatri Last updated on April 15, 2024

Table of Content

In Python, if a function has a default parameter value at function definition, then during the function call, it will have an optional argument. Although there is only one way to define a default parameter and optional argument, in Python, we can also use the *args and **kwargs for optional arguments.

There are two ways to pass an argument value during function calling positional and keyword . In positional argument passing, we pass the argument in the same order as the parameters are defined in the function definition.

In keyword argument, we specify the parameter name in the function calling and assign the argument values to them, and here the order of parameters or arguments does not matter.

But in both the function calling statements, we have an equal number of arguments passed to the function calling as the number of parameters defined in the function definition. In the function definition, we can also specify default values to the parameters using the assignment operator. By doing so, the argument values for the default parameters become optional.

In this Python tutorial, we will discuss the Optional argument or default parameters. And learn how it works in Python. We will also discuss how we can use optional arguments without even defining a default parameter, using *args and **kwargs parameters.

What are the Arguments in Python?

Arguments are the values passed inside the parenthesis () and separated with commas , during the function calling. When the function is called Python, assign all those argument values to the function definition parameters, and those values become the local scope values for the function body.

Behind the code

In this example, when we define the function using def keyword there we defined the function name show_data(para1, para2) with two parameters para1 and para2 . And when we call the function show_data(arg1, arg2) there we pass the two arguments values arg1 and arg2 . When the Python executes the show_data(arg1, arg2) statement, it passed the values of arg1 to para1 and arg2 to para2 , and execute the function body. The values of arguments are assigned to the parameters in the same order.

Python Optional Argumnets

If there are three parameters defined in the function definition, then we need to pass three argument values during the function call. Else, we will receive the TypeError: missing required positional argument . But there are three scenarios when the number of arguments can be optional, and it does not need to be the same as the number of parameters.

  • If we have a default parameter value.
  • If we use the *args as the parameter.
  • If we use the **kwagrs as the parameter.

An optional argument is a type of argument that may or may not be passed during the function call.

1. Optional Argument using Default Parameter

The easiest way to create an optional argument is by defining a default parameter. During the function definitions, we can assign default values to the parameters, and the argument for those parameters becomes optional.

In this example, we have defined the default parameter gender='Man' during the function definition. This means we have an optional argument for this parameter, and we may or may not decide to pass that optional argument during the function call. If we decide to pass a value for the optional argument, it will override the value of the default parameter.

Note: The defualt parameter must be defined after all the required or positional parameter, else you will encouter the SyntaxError: non-default argument follows default argument . Note: Python does not define the term "parameter" for the names defined in the function definition parenthesis. It refers to both parameters and arguments as arguments. Just to simplify this tutorial we are using the term parameters for the arguments defined during the function definition.

2. Optional Argument using *args

Using the *args as the parameter in the function definition, we can specify n number of optional arguments. Unlike default parameters with *args we do not have default values for all the arguments. But it makes sure that we do have an option for an arbitrary number of arguments. The *args accept all the arguments as a tuple object, and we can access them in our function body with the name args (The name args in *args is optional, but it is a conventional name and you will find the same name in all the Python programs)

In this example, we could have also omitted the age , gender and status , arguments because they are optional. The *args parameters accept them as a tuple object.  But the name parameter was required and positional. We have to pass it in any case. we could have also called the show_data() function without the optional arguments.

Note: Like default parameters the *args also must specify after all the positonal parameter.

3. Optional Argument using **kwargs

In the above section, we learned how we can define optional arguments using *args , but while using *args,  we do not have the label for the argument values. The *args is good when we are collecting arbitrary arguments from the function call. But when we require a labeled argument, then we should use **kwargs instead of *args . The **kwargs is similar to *args , as *args accept all the positional argument values as the tuple elements, the **kwargs accept keyword arguments as the dictionary key:value pairs. With **kwargs we can accept the arbitrary number of keyword arguments from the function call.

The optional argument is one of the important concepts of Python programming. Many Python functions and methods use default parameters, *args and **kargs to implement optional arguments. Defining an optional argument is very easy, and for many programs, it also becomes essential to define them.

People are also reading:

  • Top Python Libraries
  • Best Python Interpreters
  • Online Python Compiler
  • Multiple Inheritance in Python
  • Python Iterators
  • Inheritance in Python
  • Python Generators
  • Class and Objects in Python
  • How to run a python script?
  • How to become a Python Developer?

Vinay

Vinay Khatri I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Related Blogs

7 Most Common Programming Errors Every Programmer Should Know

7 Most Common Programming Errors Every Programmer Should Know

Every programmer encounters programming errors while writing and dealing with computer code. They m…

Carbon Programming Language - A Successor to C++

Carbon Programming Language - A Successor to C++

A programming language is a computer language that developers or programmers leverage to …

Introduction to Elixir Programming Language

Introduction to Elixir Programming Language

We know that website development is at its tipping point, as most businesses aim to go digital nowa…

Leave a Comment on this Post

  • Optional Arguments in Python
  • Python How-To's

Python Function With Multiple Optional Arguments

Make arguments optional in python.

Optional Arguments in Python

In python, there is something called a default argument. It is also known as optional argument or optional parameter in Python. An argument or a parameter both mean the same thing. You can use these words interchangeably. An argument or a parameter is an input that a function takes.

Whenever you call a function, you have to pass some arguments to that function depending upon whether a function takes any arguments or not. It’s not mandatory to pass an argument to a function. A function can take no argument or can take any number of arguments (depending upon how the function is defined). There are two ways in which we can pass in multiple arguments.

Use *args (Non-Keyword Arguments)

Use **kargs (keyword arguments).

The *args and **kargs both are variable-length arguments that are used to pass the variable number of arguments to a function.

When you create a function, you have to define how many parameters or arguments it will take as input. These are called formal arguments. And whenever you call that function, you have to pass some values to that function, and those values are called actual arguments.

Let’s say you have a function that takes three arguments or parameters name , number , and age as an input.

If you want to call the function personalDetails , you must pass all the 3 parameters as an input to that function.

Here, while calling a function, If you missed or forget to pass any of the parameters, you can get an error ( TypeError: personalDetails missing a required positional argument ).

If you don’t want to pass your Age to the above function as an argument, you can use something called an optional argument . You can make any number of arguments or parameters optional in Python. To make an argument optional, you have to assign some default value to that argument.

Here, to make the age argument optional, you can add a default value to the argument age in the function definition to make it optional. In this case, let’s initialize it with 0 or any other value which you want. Now Python will consider this argument as an optional argument. So, Even though if you don’t pass any value to the age parameter, the function will work, and it will use the default value, which in this case is 0 .

Even if you want to specify the value of the age argument while calling the function personalDetails , you can do that. And now it will consider the new value which you have specified instead of the default value.

Whenever you initialize any argument with a default value, it is known as a default argument. This eventually makes that argument optional, too, as now it’s not mandatory to pass in a value to that argument while calling the function. This is known as an optional argument or optional parameter in Python.

But if you have passed some value into the optional argument while calling the function, then the function will take that new value instead of the default value.

Sahil Bhosale avatar

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article - Python Function

  • How to Exit a Function in Python
  • How to Fit a Step Function in Python
  • Built-In Identity Function in Python
  • Arguments in the main() Function in Python
  • Python Functools Partial Function
  • Python »
  • 3.12.3 Documentation »
  • The Python Standard Library »
  • Development Tools »
  • typing — Support for type hints
  • Theme Auto Light Dark |

typing — Support for type hints ¶

New in version 3.5.

Source code: Lib/typing.py

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers , IDEs, linters, etc.

This module provides runtime support for type hints.

Consider the function below:

The function moon_weight takes an argument expected to be an instance of float , as indicated by the type hint earth_weight: float . The function is expected to return an instance of str , as indicated by the -> str hint.

While type hints can be simple classes like float or str , they can also be more complex. The typing module provides a vocabulary of more advanced type hints.

New features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python.

A quick overview of type hints (hosted at the mypy docs)

The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.)

Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.

Specification for the Python Type System ¶

The canonical, up-to-date specification of the Python type system can be found at “Specification for the Python type system” .

Type aliases ¶

A type alias is defined using the type statement, which creates an instance of TypeAliasType . In this example, Vector and list[float] will be treated equivalently by static type checkers:

Type aliases are useful for simplifying complex type signatures. For example:

The type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment:

Or marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment:

Use the NewType helper to create distinct types:

The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

You may still perform all int operations on a variable of type UserId , but the result will always be of type int . This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

Note that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType('Derived', Base) will make Derived a callable that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce much overhead beyond that of a regular function call.

More precisely, the expression some_value is Derived(some_value) is always true at runtime.

It is invalid to create a subtype of Derived :

However, it is possible to create a NewType based on a ‘derived’ NewType :

and typechecking for ProUserId will work as expected.

See PEP 484 for more details.

Recall that the use of a type alias declares two types to be equivalent to one another. Doing type Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original , which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

New in version 3.5.2.

Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function.

Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.

Annotating callable objects ¶

Functions – or other callable objects – can be annotated using collections.abc.Callable or typing.Callable . Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str .

For example:

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a ParamSpec , Concatenate , or an ellipsis. The return type must be a single type.

If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:

Callable cannot express complex signatures such as functions that take a variadic number of arguments, overloaded functions , or functions that have keyword-only parameters. However, these signatures can be expressed by defining a Protocol class with a __call__() method:

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec . Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate . See PEP 612 for more details.

The documentation for ParamSpec and Concatenate provides examples of usage in Callable .

Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.

Generic functions and classes can be parameterized by using type parameter syntax :

Or by using the TypeVar factory directly:

Changed in version 3.12: Syntactic support for generics is new in Python 3.12.

Annotating tuples ¶

For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example:

list only accepts one type argument, so a type checker would emit an error on the y assignment above. Similarly, Mapping only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.

Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. tuple accepts any number of type arguments:

To denote a tuple which could be of any length, and in which all elements are of the same type T , use tuple[T, ...] . To denote an empty tuple, use tuple[()] . Using plain tuple as an annotation is equivalent to using tuple[Any, ...] :

The type of class objects ¶

A variable annotated with C may accept a value of type C . In contrast, a variable annotated with type[C] (or typing.Type[C] ) may accept values that are classes themselves – specifically, it will accept the class object of C . For example:

Note that type[C] is covariant:

The only legal parameters for type are classes, Any , type variables , and unions of any of these types. For example:

type[Any] is equivalent to type , which is the root of Python’s metaclass hierarchy .

User-defined generic types ¶

A user-defined class can be defined as a generic class.

This syntax indicates that the class LoggedVar is parameterised around a single type variable T . This also makes T valid as a type within the class body.

Generic classes implicitly inherit from Generic . For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from Generic to indicate a generic class:

Generic classes have __class_getitem__() methods, meaning they can be parameterised at runtime (e.g. LoggedVar[int] below):

A generic type can have any number of type variables. All varieties of TypeVar are permissible as parameters for a generic type:

Each type variable argument to Generic must be distinct. This is thus invalid:

Generic classes can also inherit from other classes:

When inheriting from generic classes, some type parameters could be fixed:

In this case MyDict has a single parameter, T .

Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any] :

User-defined generic type aliases are also supported. Examples:

For backward compatibility, generic type aliases can also be created through a simple assignment:

Changed in version 3.7: Generic no longer has a custom metaclass.

Changed in version 3.12: Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from Generic or contain a type variable in one of their bases.

User-defined generics for parameter expressions are also supported via parameter specification variables in the form [**P] . The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a ParamSpec :

Classes generic over a ParamSpec can also be created using explicit inheritance from Generic . In this case, ** is not used:

Another difference between TypeVar and ParamSpec is that a generic with only one parameter specification variable will accept parameter lists in the forms X[[Type1, Type2, ...]] and also X[Type1, Type2, ...] for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:

Note that generics with ParamSpec may not have correct __parameters__ after substitution in some cases because they are intended primarily for static type checking.

Changed in version 3.10: Generic can now be parameterized over parameter expressions. See ParamSpec and PEP 612 for more details.

A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

The Any type ¶

A special kind of type is Any . A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.

This means that it is possible to perform any operation or method call on a value of type Any and assign it to any variable:

Notice that no type checking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

Furthermore, all functions without a return type or parameter types will implicitly default to using Any :

This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

Contrast the behavior of Any with the behavior of object . Similar to Any , every type is a subtype of object . However, unlike Any , the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object , a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

Nominal vs structural subtyping ¶

Initially PEP 484 defined the Python static type system as using nominal subtyping . This means that a class A is allowed where a class B is expected if and only if A is a subclass of B .

This requirement previously also applied to abstract base classes, such as Iterable . The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to PEP 484 :

PEP 544 allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing Bucket to be implicitly considered a subtype of both Sized and Iterable[int] by static type checkers. This is known as structural subtyping (or static duck-typing):

Moreover, by subclassing a special class Protocol , a user can define new custom protocols to fully enjoy structural subtyping (see examples below).

Module contents ¶

The typing module defines the following classes, functions and decorators.

Special typing primitives ¶

Special types ¶.

These can be used as types in annotations. They do not support subscription using [] .

Special type indicating an unconstrained type.

Every type is compatible with Any .

Any is compatible with every type.

Changed in version 3.11: Any can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

A constrained type variable .

Definition:

AnyStr is meant to be used for functions that may accept str or bytes arguments but cannot allow the two to mix.

Note that, despite its name, AnyStr has nothing to do with the Any type, nor does it mean “any string”. In particular, AnyStr and str | bytes are different from each other and have different use cases:

Special type that includes only literal strings.

Any string literal is compatible with LiteralString , as is another LiteralString . However, an object typed as just str is not. A string created by composing LiteralString -typed objects is also acceptable as a LiteralString .

LiteralString is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.

See PEP 675 for more details.

New in version 3.11.

The bottom type , a type that has no members.

This can be used to define a function that should never be called, or a function that never returns:

New in version 3.11: On older Python versions, NoReturn may be used to express the same concept. Never was added to make the intended meaning more explicit.

Special type indicating that a function never returns.

NoReturn can also be used as a bottom type , a type that has no values. Starting in Python 3.11, the Never type should be used for this concept instead. Type checkers should treat the two equivalently.

New in version 3.6.2.

Special type to represent the current enclosed class.

This annotation is semantically equivalent to the following, albeit in a more succinct fashion:

In general, if something returns self , as in the above examples, you should use Self as the return annotation. If Foo.return_self was annotated as returning "Foo" , then the type checker would infer the object returned from SubclassOfFoo.return_self as being of type Foo rather than SubclassOfFoo .

Other common use cases include:

classmethod s that are used as alternative constructors and return instances of the cls parameter.

Annotating an __enter__() method which returns self.

You should not use Self as the return annotation if the method is not guaranteed to return an instance of a subclass when the class is subclassed:

See PEP 673 for more details.

Special annotation for explicitly declaring a type alias .

TypeAlias is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:

See PEP 613 for more details.

New in version 3.10.

Deprecated since version 3.12: TypeAlias is deprecated in favor of the type statement, which creates instances of TypeAliasType and which natively supports forward references. Note that while TypeAlias and TypeAliasType serve similar purposes and have similar names, they are distinct and the latter is not the type of the former. Removal of TypeAlias is not currently planned, but users are encouraged to migrate to type statements.

Special forms ¶

These can be used as types in annotations. They all support subscription using [] , but each has a unique syntax.

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y.

To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended. Details:

The arguments must be types and there must be at least one.

Unions of unions are flattened, e.g.:

Unions of a single argument vanish, e.g.:

Redundant arguments are skipped, e.g.:

When comparing unions, the argument order is ignored, e.g.:

You cannot subclass or instantiate a Union .

You cannot write Union[X][Y] .

Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.

Changed in version 3.10: Unions can now be written as X | Y . See union type expressions .

Optional[X] is equivalent to X | None (or Union[X, None] ).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

Changed in version 3.10: Optional can now be written as X | None . See union type expressions .

Special form for annotating higher-order functions.

Concatenate can be used in conjunction with Callable and ParamSpec to annotate a higher-order callable which adds, removes, or transforms parameters of another callable. Usage is in the form Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable] . Concatenate is currently only valid when used as the first argument to a Callable . The last parameter to Concatenate must be a ParamSpec or ellipsis ( ... ).

For example, to annotate a decorator with_lock which provides a threading.Lock to the decorated function, Concatenate can be used to indicate that with_lock expects a callable which takes in a Lock as the first argument, and returns a callable with a different type signature. In this case, the ParamSpec indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:

PEP 612 – Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate )

  • Annotating callable objects

Special typing form to define “literal types”.

Literal can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals.

Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...] , but type checkers may impose restrictions. See PEP 586 for more details about literal types.

New in version 3.8.

Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparisons of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not hashable .

Special type construct to mark class variables.

As introduced in PEP 526 , a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

ClassVar accepts only types and cannot be further subscribed.

ClassVar is not a class itself, and should not be used with isinstance() or issubclass() . ClassVar does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:

New in version 3.5.3.

Special typing construct to indicate final names to type checkers.

Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.

There is no runtime checking of these properties. See PEP 591 for more details.

Special typing construct to mark a TypedDict key as required.

This is mainly useful for total=False TypedDicts. See TypedDict and PEP 655 for more details.

Special typing construct to mark a TypedDict key as potentially missing.

See TypedDict and PEP 655 for more details.

Special typing form to add context-specific metadata to an annotation.

Add metadata x to a given type T by using the annotation Annotated[T, x] . Metadata added using Annotated can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a __metadata__ attribute.

If a library or tool encounters an annotation Annotated[T, x] and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as T . As such, Annotated can be useful for code that wants to use annotations for purposes outside Python’s static typing system.

Using Annotated[T, x] as an annotation still allows for static typechecking of T , as type checkers will simply ignore the metadata x . In this way, Annotated differs from the @no_type_check decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.

The responsibility of how to interpret the metadata lies with the tool or library encountering an Annotated annotation. A tool or library encountering an Annotated type can scan through the metadata elements to determine if they are of interest (e.g., using isinstance() ).

Here is an example of how you might use Annotated to add metadata to type annotations if you were doing range analysis:

Details of the syntax:

The first argument to Annotated must be a valid type

Multiple metadata elements can be supplied ( Annotated supports variadic arguments):

It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.

Annotated must be subscripted with at least two arguments ( Annotated[int] is not valid)

The order of the metadata elements is preserved and matters for equality checks:

Nested Annotated types are flattened. The order of the metadata elements starts with the innermost annotation:

Duplicated metadata elements are not removed:

Annotated can be used with nested and generic aliases:

Annotated cannot be used with an unpacked TypeVarTuple :

This would be equivalent to:

where T1 , T2 , etc. are TypeVars . This would be invalid: only one type should be passed to Annotated.

By default, get_type_hints() strips the metadata from annotations. Pass include_extras=True to have the metadata preserved:

At runtime, the metadata associated with an Annotated type can be retrieved via the __metadata__ attribute:

The PEP introducing Annotated to the standard library.

New in version 3.9.

Special typing construct for marking user-defined type guard functions.

TypeGuard can be used to annotate the return type of a user-defined type guard function. TypeGuard only accepts a single type argument. At runtime, functions marked this way should return a boolean.

TypeGuard aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a “type guard”:

Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use TypeGuard[...] as its return type to alert static type checkers to this intention.

Using -> TypeGuard tells the static type checker that for a given function:

The return value is a boolean.

If the return value is True , the type of its argument is the type inside TypeGuard .

If is_str_list is a class or instance method, then the type in TypeGuard maps to the type of the second parameter after cls or self .

In short, the form def foo(arg: TypeA) -> TypeGuard[TypeB]: ... , means that if foo(arg) returns True , then arg narrows from TypeA to TypeB .

TypeB need not be a narrower form of TypeA – it can even be a wider form. The main reason is to allow for things like narrowing list[object] to list[str] even though the latter is not a subtype of the former, since list is invariant. The responsibility of writing type-safe type guards is left to the user.

TypeGuard also works with type variables. See PEP 647 for more details.

Typing operator to conceptually mark an object as having been unpacked.

For example, using the unpack operator * on a type variable tuple is equivalent to using Unpack to mark the type variable tuple as having been unpacked:

In fact, Unpack can be used interchangeably with * in the context of typing.TypeVarTuple and builtins.tuple types. You might see Unpack being used explicitly in older versions of Python, where * couldn’t be used in certain places:

Unpack can also be used along with typing.TypedDict for typing **kwargs in a function signature:

See PEP 692 for more details on using Unpack for **kwargs typing.

Building generic types and type aliases ¶

The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.

These objects can be created through special syntax ( type parameter lists and the type statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.

Abstract base class for generic types.

A generic type is typically declared by adding a list of type parameters after the class name:

Such a class implicitly inherits from Generic . The runtime semantics of this syntax are discussed in the Language Reference .

This class can then be used as follows:

Here the brackets after the function name indicate a generic function .

For backwards compatibility, generic classes can also be declared by explicitly inheriting from Generic . In this case, the type parameters must be declared separately:

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions , generic classes , and generic type aliases :

This syntax can also be used to create bound and constrained type variables:

However, if desired, reusable type variables can also be constructed manually, like so:

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See Generic for more information on generic types. Generic functions work as follows:

Note that type variables can be bound , constrained , or neither, but cannot be both bound and constrained.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax or when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True . By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

Bound type variables and constrained type variables have different semantics in several important ways. Using a bound type variable means that the TypeVar will be solved using the most specific type possible:

Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:

Using a constrained type variable, however, means that the TypeVar can only ever be solved as being exactly one of the constraints given:

At runtime, isinstance(x, T) will raise TypeError .

The name of the type variable.

Whether the type var has been explicitly marked as covariant.

Whether the type var has been explicitly marked as contravariant.

Whether the type variable’s variance should be inferred by type checkers.

New in version 3.12.

The bound of the type variable, if any.

Changed in version 3.12: For type variables created through type parameter syntax , the bound is evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation ).

A tuple containing the constraints of the type variable, if any.

Changed in version 3.12: For type variables created through type parameter syntax , the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation ).

Changed in version 3.12: Type variables can now be declared using the type parameter syntax introduced by PEP 695 . The infer_variance parameter was added.

Type variable tuple. A specialized form of type variable that enables variadic generics.

Type variable tuples can be declared in type parameter lists using a single asterisk ( * ) before the name:

Or by explicitly invoking the TypeVarTuple constructor:

A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example:

Note the use of the unpacking operator * in tuple[T, *Ts] . Conceptually, you can think of Ts as a tuple of type variables (T1, T2, ...) . tuple[T, *Ts] would then become tuple[T, *(T1, T2, ...)] , which is equivalent to tuple[T, T1, T2, ...] . (Note that in older versions of Python, you might see this written using Unpack instead, as Unpack[Ts] .)

Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables:

Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:

Type variable tuples can be happily combined with normal type variables:

However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:

Finally, an unpacked type variable tuple can be used as the type annotation of *args :

In contrast to non-unpacked annotations of *args - e.g. *args: int , which would specify that all arguments are int - *args: *Ts enables reference to the types of the individual arguments in *args . Here, this allows us to ensure the types of the *args passed to call_soon match the types of the (positional) arguments of callback .

See PEP 646 for more details on type variable tuples.

The name of the type variable tuple.

Changed in version 3.12: Type variable tuples can now be declared using the type parameter syntax introduced by PEP 695 .

Parameter specification variable. A specialized version of type variables .

In type parameter lists , parameter specifications can be declared with two asterisks ( ** ):

For compatibility with Python 3.11 and earlier, ParamSpec objects can also be created as follows:

Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in Concatenate , or as the first argument to Callable , or as parameters for user-defined Generics. See Generic for more information on generic types.

For example, to add basic logging to a function, one can create a decorator add_logging to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:

Without ParamSpec , the simplest way to annotate this previously was to use a TypeVar with bound Callable[..., Any] . However this causes two problems:

The type checker can’t type check the inner function because *args and **kwargs have to be typed Any .

cast() may be required in the body of the add_logging decorator when returning the inner function, or the static type checker must be told to ignore the return inner .

Since ParamSpec captures both positional and keyword parameters, P.args and P.kwargs can be used to split a ParamSpec into its components. P.args represents the tuple of positional parameters in a given call and should only be used to annotate *args . P.kwargs represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate **kwargs . Both attributes require the annotated parameter to be in scope. At runtime, P.args and P.kwargs are instances respectively of ParamSpecArgs and ParamSpecKwargs .

The name of the parameter specification.

Parameter specification variables created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar . However the actual semantics of these keywords are yet to be decided.

Changed in version 3.12: Parameter specifications can now be declared using the type parameter syntax introduced by PEP 695 .

Only parameter specification variables defined in global scope can be pickled.

Concatenate

Arguments and keyword arguments attributes of a ParamSpec . The P.args attribute of a ParamSpec is an instance of ParamSpecArgs , and P.kwargs is an instance of ParamSpecKwargs . They are intended for runtime introspection and have no special meaning to static type checkers.

Calling get_origin() on either of these objects will return the original ParamSpec :

The type of type aliases created through the type statement.

The name of the type alias:

The module in which the type alias was defined:

The type parameters of the type alias, or an empty tuple if the alias is not generic:

The type alias’s value. This is lazily evaluated , so names used in the definition of the alias are not resolved until the __value__ attribute is accessed:

Other special directives ¶

These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.

Typed version of collections.namedtuple() .

This is equivalent to:

To give a field a default value, you can assign to it in the class body:

Fields with a default value must come after any fields without a default.

The resulting class has an extra attribute __annotations__ giving a dict that maps the field names to the field types. (The field names are in the _fields attribute and the default values are in the _field_defaults attribute, both of which are part of the namedtuple() API.)

NamedTuple subclasses can also have docstrings and methods:

NamedTuple subclasses can be generic:

Backward-compatible usage:

Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

Changed in version 3.6.1: Added support for default values, methods, and docstrings.

Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict .

Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.

Changed in version 3.11: Added support for generic namedtuples.

Helper class to create low-overhead distinct types .

A NewType is considered a distinct type by a typechecker. At runtime, however, calling a NewType returns its argument unchanged.

The module in which the new type is defined.

The name of the new type.

The type that the new type is based on.

Changed in version 3.10: NewType is now a class rather than a function.

Base class for protocol classes.

Protocol classes are defined like this:

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:

See PEP 544 for more details. Protocol classes decorated with runtime_checkable() (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

Protocol classes can be generic, for example:

In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:

Mark a protocol class as a runtime protocol.

Such a protocol can be used with isinstance() and issubclass() . This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in collections.abc such as Iterable . For example:

runtime_checkable() will check only the presence of the required methods or attributes, not their type signatures or types. For example, ssl.SSLObject is a class, therefore it passes an issubclass() check against Callable . However, the ssl.SSLObject.__init__ method exists only to raise a TypeError with a more informative message, therefore making it impossible to call (instantiate) ssl.SSLObject .

An isinstance() check against a runtime-checkable protocol can be surprisingly slow compared to an isinstance() check against a non-protocol class. Consider using alternative idioms such as hasattr() calls for structural checks in performance-sensitive code.

Changed in version 3.12: The internal implementation of isinstance() checks against runtime-checkable protocols now uses inspect.getattr_static() to look up attributes (previously, hasattr() was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.

Changed in version 3.12: The members of a runtime-checkable protocol are now considered “frozen” at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on isinstance() checks comparing objects to the protocol. See “What’s new in Python 3.12” for more details.

Special construct to add type hints to a dictionary. At runtime it is a plain dict .

TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

To allow using this feature with older versions of Python that do not support PEP 526 , TypedDict supports two additional equivalent syntactic forms:

Using a literal dict as the second argument:

Using keyword arguments:

Deprecated since version 3.11, will be removed in version 3.13: The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13. It may also be unsupported by static type checkers.

The functional syntax should also be used when any of the keys are not valid identifiers , for example because they are keywords or contain hyphens. Example:

By default, all keys must be present in a TypedDict . It is possible to mark individual keys as non-required using NotRequired :

This means that a Point2D TypedDict can have the label key omitted.

It is also possible to mark all keys as non-required by default by specifying a totality of False :

This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body required.

Individual keys of a total=False TypedDict can be marked as required using Required :

It is possible for a TypedDict type to inherit from one or more other TypedDict types using the class-based syntax. Usage:

Point3D has three items: x , y and z . It is equivalent to this definition:

A TypedDict cannot inherit from a non- TypedDict class, except for Generic . For example:

A TypedDict can be generic:

To create a generic TypedDict that is compatible with Python 3.11 or lower, inherit from Generic explicitly:

A TypedDict can be introspected via annotations dicts (see Annotations Best Practices for more information on annotations best practices), __total__ , __required_keys__ , and __optional_keys__ .

Point2D.__total__ gives the value of the total argument. Example:

This attribute reflects only the value of the total argument to the current TypedDict class, not whether the class is semantically total. For example, a TypedDict with __total__ set to True may have keys marked with NotRequired , or it may inherit from another TypedDict with total=False . Therefore, it is generally better to use __required_keys__ and __optional_keys__ for introspection.

Point2D.__required_keys__ and Point2D.__optional_keys__ return frozenset objects containing required and non-required keys, respectively.

Keys marked with Required will always appear in __required_keys__ and keys marked with NotRequired will always appear in __optional_keys__ .

For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same TypedDict . This is done by declaring a TypedDict with one value for the total argument and then inheriting from it in another TypedDict with a different value for total :

If from __future__ import annotations is used or if annotations are given as strings, annotations are not evaluated when the TypedDict is defined. Therefore, the runtime introspection that __required_keys__ and __optional_keys__ rely on may not work properly, and the values of the attributes may be incorrect.

See PEP 589 for more examples and detailed rules of using TypedDict .

Changed in version 3.11: Added support for marking individual keys as Required or NotRequired . See PEP 655 .

Changed in version 3.11: Added support for generic TypedDict s.

Protocols ¶

The following protocols are provided by the typing module. All are decorated with @runtime_checkable .

An ABC with one abstract method __abs__ that is covariant in its return type.

An ABC with one abstract method __bytes__ .

An ABC with one abstract method __complex__ .

An ABC with one abstract method __float__ .

An ABC with one abstract method __index__ .

An ABC with one abstract method __int__ .

An ABC with one abstract method __round__ that is covariant in its return type.

ABCs for working with IO ¶

Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open() .

Functions and decorators ¶

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

Ask a static type checker to confirm that val has an inferred type of typ .

At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.

When a static type checker encounters a call to assert_type() , it emits an error if the value is not of the specified type:

This function is useful for ensuring the type checker’s understanding of a script is in line with the developer’s intentions:

Ask a static type checker to confirm that a line of code is unreachable.

Here, the annotations allow the type checker to infer that the last case can never execute, because arg is either an int or a str , and both options are covered by earlier cases.

If a type checker finds that a call to assert_never() is reachable, it will emit an error. For example, if the type annotation for arg was instead int | str | float , the type checker would emit an error pointing out that unreachable is of type float . For a call to assert_never to pass type checking, the inferred type of the argument passed in must be the bottom type, Never , and nothing else.

At runtime, this throws an exception when called.

Unreachable Code and Exhaustiveness Checking has more information about exhaustiveness checking with static typing.

Ask a static type checker to reveal the inferred type of an expression.

When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example:

This can be useful when you want to debug how your type checker handles a particular piece of code.

At runtime, this function prints the runtime type of its argument to sys.stderr and returns the argument unchanged (allowing the call to be used within an expression):

Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.

Most type checkers support reveal_type() anywhere, even if the name is not imported from typing . Importing the name from typing , however, allows your code to run without runtime errors and communicates intent more clearly.

Decorator to mark an object as providing dataclass -like behavior.

dataclass_transform may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of @dataclass_transform() tells a static type checker that the decorated object performs runtime “magic” that transforms a class in a similar way to @dataclasses.dataclass .

Example usage with a decorator function:

On a base class:

On a metaclass:

The CustomerModel classes defined above will be treated by type checkers similarly to classes created with @dataclasses.dataclass . For example, type checkers will assume these classes have __init__ methods that accept id and name .

The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the @dataclasses.dataclass decorator: init , eq , order , unsafe_hash , frozen , match_args , kw_only , and slots . It must be possible for the value of these arguments ( True or False ) to be statically evaluated.

The arguments to the dataclass_transform decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:

eq_default ( bool ) – Indicates whether the eq parameter is assumed to be True or False if it is omitted by the caller. Defaults to True .

order_default ( bool ) – Indicates whether the order parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

kw_only_default ( bool ) – Indicates whether the kw_only parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

Indicates whether the frozen parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

field_specifiers ( tuple [ Callable [ ... , Any ] , ... ] ) – Specifies a static list of supported classes or functions that describe fields, similar to dataclasses.field() . Defaults to () .

**kwargs ( Any ) – Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.

Type checkers recognize the following optional parameters on field specifiers:

At runtime, this decorator records its arguments in the __dataclass_transform__ attribute on the decorated object. It has no other runtime effect.

See PEP 681 for more details.

Decorator for creating overloaded functions and methods.

The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload -decorated definitions must be followed by exactly one non- @overload -decorated definition (for the same function/method).

@overload -decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non- @overload -decorated definition. The non- @overload -decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an @overload -decorated function directly will raise NotImplementedError .

An example of overload that gives a more precise type than can be expressed using a union or a type variable:

See PEP 484 for more details and comparison with other typing semantics.

Changed in version 3.11: Overloaded functions can now be introspected at runtime using get_overloads() .

Return a sequence of @overload -decorated definitions for func .

func is the function object for the implementation of the overloaded function. For example, given the definition of process in the documentation for @overload , get_overloads(process) will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, get_overloads() returns an empty sequence.

get_overloads() can be used for introspecting an overloaded function at runtime.

Clear all registered overloads in the internal registry.

This can be used to reclaim the memory used by the registry.

Decorator to indicate final methods and final classes.

Decorating a method with @final indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with @final indicates that it cannot be subclassed.

Changed in version 3.11: The decorator will now attempt to set a __final__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__final__", False) can be used at runtime to determine whether an object obj has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

Decorator to indicate that annotations are not type hints.

This works as a class or function decorator . With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.

@no_type_check mutates the decorated object in place.

Decorator to give another decorator the no_type_check() effect.

This wraps the decorator with something that wraps the decorated function in no_type_check() .

Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.

Type checkers should emit an error if a method decorated with @override does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.

There is no runtime checking of this property.

The decorator will attempt to set an __override__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__override__", False) can be used at runtime to determine whether an object obj has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

See PEP 698 for more details.

Decorator to mark a class or function as unavailable at runtime.

This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:

Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.

Introspection helpers ¶

Return a dictionary containing type hints for a function, method, module or class object.

This is often the same as obj.__annotations__ . In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. For a class C , return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.

The function recursively replaces all Annotated[T, ...] with T , unless include_extras is set to True (see Annotated for more information). For example:

get_type_hints() does not work with imported type aliases that include forward references. Enabling postponed evaluation of annotations ( PEP 563 ) may remove the need for most forward references.

Changed in version 3.9: Added include_extras parameter as part of PEP 593 . See the documentation on Annotated for more information.

Changed in version 3.11: Previously, Optional[t] was added for function and method annotations if a default value equal to None was set. Now the annotation is returned unchanged.

Get the unsubscripted version of a type: for a typing object of the form X[Y, Z, ...] return X .

If X is a typing-module alias for a builtin or collections class, it will be normalized to the original class. If X is an instance of ParamSpecArgs or ParamSpecKwargs , return the underlying ParamSpec . Return None for unsupported objects.

Get type arguments with all substitutions performed: for a typing object of the form X[Y, Z, ...] return (Y, Z, ...) .

If X is a union or Literal contained in another generic type, the order of (Y, Z, ...) may be different from the order of the original arguments [Y, Z, ...] due to type caching. Return () for unsupported objects.

Check if a type is a TypedDict .

Class used for internal typing representation of string forward references.

For example, List["SomeClass"] is implicitly transformed into List[ForwardRef("SomeClass")] . ForwardRef should not be instantiated by a user, but may be used by introspection tools.

PEP 585 generic types such as list["SomeClass"] will not be implicitly transformed into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass] .

New in version 3.7.4.

A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime.

The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.

If from __future__ import annotations is used, annotations are not evaluated at function definition time. Instead, they are stored as strings in __annotations__ . This makes it unnecessary to use quotes around the annotation (see PEP 563 ).

Deprecated aliases ¶

This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using [] . However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [] (see PEP 585 ).

The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.

If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the typing module without deprecation warnings until at least Python 3.14.

Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.

Aliases to built-in types ¶

Deprecated alias to dict .

Note that to annotate arguments, it is preferred to use an abstract collection type such as Mapping rather than to use dict or typing.Dict .

This type can be used as follows:

Deprecated since version 3.9: builtins.dict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to list .

Note that to annotate arguments, it is preferred to use an abstract collection type such as Sequence or Iterable rather than to use list or typing.List .

This type may be used as follows:

Deprecated since version 3.9: builtins.list now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to builtins.set .

Note that to annotate arguments, it is preferred to use an abstract collection type such as AbstractSet rather than to use set or typing.Set .

Deprecated since version 3.9: builtins.set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to builtins.frozenset .

Deprecated since version 3.9: builtins.frozenset now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias for tuple .

tuple and Tuple are special-cased in the type system; see Annotating tuples for more details.

Deprecated since version 3.9: builtins.tuple now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to type .

See The type of class objects for details on using type or typing.Type in type annotations.

Deprecated since version 3.9: builtins.type now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Aliases to types in collections ¶

Deprecated alias to collections.defaultdict .

Deprecated since version 3.9: collections.defaultdict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.OrderedDict .

New in version 3.7.2.

Deprecated since version 3.9: collections.OrderedDict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.ChainMap .

New in version 3.6.1.

Deprecated since version 3.9: collections.ChainMap now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.Counter .

Deprecated since version 3.9: collections.Counter now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.deque .

Deprecated since version 3.9: collections.deque now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Aliases to other concrete types ¶

Deprecated since version 3.8, will be removed in version 3.13: The typing.io namespace is deprecated and will be removed. These types should be directly imported from typing instead.

Deprecated aliases corresponding to the return types from re.compile() and re.match() .

These types (and the corresponding functions) are generic over AnyStr . Pattern can be specialised as Pattern[str] or Pattern[bytes] ; Match can be specialised as Match[str] or Match[bytes] .

Deprecated since version 3.8, will be removed in version 3.13: The typing.re namespace is deprecated and will be removed. These types should be directly imported from typing instead.

Deprecated since version 3.9: Classes Pattern and Match from re now support [] . See PEP 585 and Generic Alias Type .

Deprecated alias for str .

Text is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode .

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

Deprecated since version 3.11: Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use str instead of Text .

Aliases to container ABCs in collections.abc ¶

Deprecated alias to collections.abc.Set .

Deprecated since version 3.9: collections.abc.Set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

This type represents the types bytes , bytearray , and memoryview of byte sequences.

Deprecated since version 3.9, will be removed in version 3.14: Prefer collections.abc.Buffer , or a union like bytes | bytearray | memoryview .

Deprecated alias to collections.abc.Collection .

New in version 3.6.

Deprecated since version 3.9: collections.abc.Collection now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Container .

Deprecated since version 3.9: collections.abc.Container now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.ItemsView .

Deprecated since version 3.9: collections.abc.ItemsView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.KeysView .

Deprecated since version 3.9: collections.abc.KeysView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Mapping .

Deprecated since version 3.9: collections.abc.Mapping now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.MappingView .

Deprecated since version 3.9: collections.abc.MappingView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.MutableMapping .

Deprecated since version 3.9: collections.abc.MutableMapping now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.MutableSequence .

Deprecated since version 3.9: collections.abc.MutableSequence now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.MutableSet .

Deprecated since version 3.9: collections.abc.MutableSet now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Sequence .

Deprecated since version 3.9: collections.abc.Sequence now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.ValuesView .

Deprecated since version 3.9: collections.abc.ValuesView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Aliases to asynchronous ABCs in collections.abc ¶

Deprecated alias to collections.abc.Coroutine .

The variance and order of type variables correspond to those of Generator , for example:

Deprecated since version 3.9: collections.abc.Coroutine now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.AsyncGenerator .

An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType] . For example:

Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator , the SendType behaves contravariantly.

If your generator will only yield values, set the SendType to None :

Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType] :

Deprecated since version 3.9: collections.abc.AsyncGenerator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.AsyncIterable .

Deprecated since version 3.9: collections.abc.AsyncIterable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.AsyncIterator .

Deprecated since version 3.9: collections.abc.AsyncIterator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Awaitable .

Deprecated since version 3.9: collections.abc.Awaitable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Aliases to other ABCs in collections.abc ¶

Deprecated alias to collections.abc.Iterable .

Deprecated since version 3.9: collections.abc.Iterable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Iterator .

Deprecated since version 3.9: collections.abc.Iterator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Callable .

See Annotating callable objects for details on how to use collections.abc.Callable and typing.Callable in type annotations.

Deprecated since version 3.9: collections.abc.Callable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Generator .

A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType] . For example:

Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.

If your generator will only yield values, set the SendType and ReturnType to None :

Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType] :

Deprecated since version 3.9: collections.abc.Generator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Hashable .

Deprecated since version 3.12: Use collections.abc.Hashable directly instead.

Deprecated alias to collections.abc.Reversible .

Deprecated since version 3.9: collections.abc.Reversible now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to collections.abc.Sized .

Deprecated since version 3.12: Use collections.abc.Sized directly instead.

Aliases to contextlib ABCs ¶

Deprecated alias to contextlib.AbstractContextManager .

New in version 3.5.4.

Deprecated since version 3.9: contextlib.AbstractContextManager now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to contextlib.AbstractAsyncContextManager .

Deprecated since version 3.9: contextlib.AbstractAsyncContextManager now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecation Timeline of Major Features ¶

Certain features in typing are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.

Table of Contents

  • Specification for the Python Type System
  • Type aliases
  • Annotating tuples
  • The type of class objects
  • User-defined generic types
  • The Any type
  • Nominal vs structural subtyping
  • Special types
  • Special forms
  • Building generic types and type aliases
  • Other special directives
  • ABCs for working with IO
  • Functions and decorators
  • Introspection helpers
  • Aliases to built-in types
  • Aliases to types in collections
  • Aliases to other concrete types
  • Aliases to container ABCs in collections.abc
  • Aliases to asynchronous ABCs in collections.abc
  • Aliases to other ABCs in collections.abc
  • Aliases to contextlib ABCs
  • Deprecation Timeline of Major Features

Previous topic

Development Tools

pydoc — Documentation generator and online help system

  • Report a Bug
  • Show Source

TutorialsTonight Logo

Python Conditional Assignment

When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

In this tutorial, we will look at different ways to assign values to a variable based on some condition.

1. Using Ternary Operator

The ternary operator is very special operator in Python, it is used to assign a value to a variable based on some condition.

It goes like this:

Here, the value of variable will be value_if_true if the condition is true, else it will be value_if_false .

Let's see a code snippet to understand it better.

You can see we have conditionally assigned a value to variable c based on the condition a > b .

2. Using if-else statement

if-else statements are the core part of any programming language, they are used to execute a block of code based on some condition.

Using an if-else statement, we can assign a value to a variable based on the condition we provide.

Here is an example of replacing the above code snippet with the if-else statement.

3. Using Logical Short Circuit Evaluation

Logical short circuit evaluation is another way using which you can assign a value to a variable conditionally.

The format of logical short circuit evaluation is:

It looks similar to ternary operator, but it is not. Here the condition and value_if_true performs logical AND operation, if both are true then the value of variable will be value_if_true , or else it will be value_if_false .

Let's see an example:

But if we make condition True but value_if_true False (or 0 or None), then the value of variable will be value_if_false .

So, you can see that the value of c is 20 even though the condition a < b is True .

So, you should be careful while using logical short circuit evaluation.

While working with lists , we often need to check if a list is empty or not, and if it is empty then we need to assign some default value to it.

Let's see how we can do it using conditional assignment.

Here, we have assigned a default value to my_list if it is empty.

Assign a value to a variable conditionally based on the presence of an element in a list.

Now you know 3 different ways to assign a value to a variable conditionally. Any of these methods can be used to assign a value when there is a condition.

The cleanest and fastest way to conditional value assignment is the ternary operator .

if-else statement is recommended to use when you have to execute a block of code based on some condition.

Happy coding! 😊

Python Variables and Assignment

Python variables, variable assignment rules, every value has a type, memory and the garbage collector, variable swap, variable names are superficial labels, assignment = is shallow, decomp by var.

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • How to Fix: ValueError: Unknown Label Type: 'Continuous' in Python
  • How To Check If Variable Is Empty In Python?
  • How To Fix - Python RuntimeWarning: overflow encountered in scalar
  • How To Resolve Issue " Threading Ignores Keyboardinterrupt Exception" In Python?
  • AttributeError: can’t set attribute in Python
  • How to Fix ImportError: Cannot Import name X in Python
  • AttributeError: __enter__ Exception in Python
  • Modulenotfounderror: No Module Named 'httpx' in Python
  • How to Fix - SyntaxError: (Unicode Error) 'Unicodeescape' Codec Can't Decode Bytes
  • SyntaxError: ‘return’ outside function in Python
  • How to fix "SyntaxError: invalid character" in Python
  • No Module Named 'Sqlalchemy-Jsonfield' in Python
  • Python Code Error: No Module Named 'Aiohttp'
  • Fix Python Attributeerror: __Enter__
  • Python Runtimeerror: Super() No Arguments
  • Filenotfounderror: Errno 2 No Such File Or Directory in Python
  • ModuleNotFoundError: No module named 'dotenv' in Python
  • Nameerror: Name Plot_Cases_Simple Is Not Defined in Python
  • How To Avoid Notimplementederror In Python?

How to Fix – UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

What is UnboundLocalError: Local variable Referenced Before Assignment?

This error occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.

Please Login to comment...

Similar reads.

  • Python Errors
  • Python How-to-fix
  • Google Introduces New AI-powered Vids App
  • Dolly Chaiwala: The Microsoft Windows 12 Brand Ambassador
  • 10 Best Free Remote Desktop apps for Android in 2024
  • 10 Best Free Internet Speed Test apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Variable Assignment in Python

    python optional variable assignment

  2. Python Variable (Assign value, string Display, multiple Variables & Rules)

    python optional variable assignment

  3. Python Variables and Data Types

    python optional variable assignment

  4. # 11 Variable Assignments in Python

    python optional variable assignment

  5. 11 How to assign values to variables in python

    python optional variable assignment

  6. #5 Variables, Assignment statements in Python || Python Course 2020

    python optional variable assignment

VIDEO

  1. Python Variables Demystified: Store, Change, and Manage Data with Ease

  2. What are Python Strings?

  3. LECTURE 4: PYTHON DAY 4

  4. Python Simple Variable Assignment

  5. #6 Python Variable Assignment Part_1 (Variables in Python)

  6. Variable Assignment in Python

COMMENTS

  1. Using Python Optional Arguments When Defining Functions

    When defining a function, you can include any number of optional keyword arguments to be included using kwargs, which stands for keyword arguments. The function signature looks like this: Python. def add_items(shopping_list, **kwargs): The parameter name kwargs is preceded by two asterisks ( ** ).

  2. python

    Add a comment. 1. The simple solution is to only assign to the variable in one place. def __init__(self, name: str, clb: Optional[B] = None): self.name = name. self.clb = clb. In my opinion you should get rid of the isinstance check completely. Mypy is now responsible for checking your types, the manual check is somewhat redundant.

  3. How to pass optional parameters to a function in Python?

    2 type is <class 'int'>. 1 type is <class 'int'>. geeks type is <class 'str'>. third call. geeks type is <class 'str'>. 3 type is <class 'int'>. 2 type is <class 'int'>. So basically python functional calls checks only if the required number of functional parameters are passed or not. Below shows the case where a user tries to pass arguments in ...

  4. Python Optional Arguments: A How-To Guide

    A Python optional argument is a type of argument with a default value. You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be ...

  5. Master Python Optional Arguments Usage [Tutorial]

    One of the powerful features of Python is the use of *args for optional positional arguments. This allows you to pass a variable number of non-keyword arguments to a function. Let's delve into how to use *args effectively in Python optional arguments. python. # Using *args to accept multiple arguments.

  6. Python Optional Arguments

    Further Resources for Mastering Python Optional Arguments. If you're interested in diving deeper into Python optional arguments and related concepts, here are some resources you might find useful: Python's official documentation on defining functions; provides a thorough overview of function arguments, including optional arguments.

  7. 5 Best Ways to Make an Argument Optional in Python

    Method 1: Using Default Parameters. Specifying default parameters in a function is the simplest way to make arguments optional in Python. By providing a default value during function definition, the argument becomes non-mandatory. If the caller doesn't supply the argument, the function uses the default value.

  8. Python Optional Arguments: A Complete Guide

    The easiest way to create an optional argument is by defining a default parameter. During the function definitions, we can assign default values to the parameters, and the argument for those parameters becomes optional. Example. # show_data function with default gender parameter. def show_data(name, age, gender="Man"):

  9. Optional Arguments in Python

    To make an argument optional, you have to assign some default value to that argument. Here, to make the age argument optional, you can add a default value to the argument age in the function definition to make it optional. In this case, let's initialize it with 0 or any other value which you want. Now Python will consider this argument as an ...

  10. typing

    The function moon_weight takes an argument expected to be an instance of float, as indicated by the type hint earth_weight: float.The function is expected to return an instance of str, as indicated by the -> str hint.. While type hints can be simple classes like float or str, they can also be more complex.The typing module provides a vocabulary of more advanced type hints.

  11. Using Optional Arguments

    Functions with optional arguments offer more flexibility in how you can use them. 00:15 You can call the function with or without the argument. And if there is no argument in the function call, then a default value is used. 00:25 So let's get started by looking at how to assign default values to input parameters.

  12. Python Conditional Assignment (in 3 Ways)

    Let's see a code snippet to understand it better. a = 10. b = 20 # assigning value to variable c based on condition. c = a if a > b else b. print(c) # output: 20. You can see we have conditionally assigned a value to variable c based on the condition a > b. 2. Using if-else statement.

  13. Python Variables and Assignment

    Python Variables. A Python variable is a named bit of computer memory, keeping track of a value as the code runs. A variable is created with an "assignment" equal sign =, with the variable's name on the left and the value it should store on the right: x = 42 In the computer's memory, each variable is like a box, identified by the name of the ...

  14. Python Optional Arguments: Mastering Function Parameters

    When defining functions in Python, optional arguments allow functions to be more adaptable, giving users the freedom to supply fewer arguments than the function can accept.. Specifying Default Values. The beauty of optional arguments lies in their flexibility; you can specify default values for parameters that aren't essential to the function's core operation.

  15. Variables in Python

    To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ): Python. >>> n = 300. This is read or interpreted as " n is assigned the value 300 .". Once this is done, n can be used in a statement or expression, and its value will be substituted: Python.

  16. 5 Common Python Gotchas (And How To Avoid Them)

    So always use the == operator to check if any two Python objects have the same value. 4. Tuple Assignment and Mutable Objects . If you're familiar with built-in data structures in Python, you know that tuples are immutable. So you cannot modify them in place. Data structures like lists and dictionaries, on the other hand, are mutable.

  17. variables

    An exception should be used when something is wrong not when trying to assign a variable. - Paul D. Nov 7, 2022 at 20:33 ... 10 There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it: x = true_value if condition else false_value For further reference, check out ...

  18. How to Fix

    Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in Python

  19. Optional arguments in initializer of Python class

    You can set default parameters: class OpticalTransition(object): def __init__(self, chemical, i, j=None, k=0): self.chemical = chemical. self.i = i. self.k = k. self.j = j if j is not None else i. If you don't explicitly call the class with j and k, your instance will use the defaults you defined in the init parameters.

  20. python

    Additionally, as an extra bonus, you can't simply make a 1:1 translation from that to PEP 484 (e.g. for supporting python versions <= 3.5): def bar(): a # type: str # ^ # UnboundLocalError: cannot access local variable 'a' where it is not associated with a value b # type: int a, b = foo()