[FIXED] Python3: pass type as function parameter

Issue

How can i pass int or str as function parameters in python?

Example:

def fn(type:<arg typing here>):
    # do something

output = fn(type=int)

Example 2 from django commands:

parser.add_argument(
        'years', type=int, help="Determines how many years of fake data to generate.")

Solution

Other than the typing declaration, your code should already work. For typing the parameter, you could use typing.Type:

from typing import Type

def fn(type: Type):
    # do something

However, you might not want to use the builtin name type as the name of a parameter. Some might prefer something like this:

from typing import Type

def fn(typ: Type):
    # do something


Answered By - Warren Weckesser
Answer Checked By - Katrina (Python.Easybugfix Volunteer)

Related Posts

Post a Comment