PyXLL The Python Excel Add-In
  • Product
    • Features
    • Get Started
    • Request Demo
    • Download
  • Pricing
  • Resources
    • Documentation
    • Blog
    • Videos
    • FAQ
    • Learn Python
    • Customer Portal
    • About Us
  • Support
    • Documentation
    • Videos
    • FAQ
    • Contact Us
  • Contact Us
Table of Contents
  • PyXLL Documentation
  • Introduction to PyXLL
  • User Guide
  • Video Guides and Tutorials
  • API Reference
    • Worksheet Functions
    • Real Time Data
    • Macro Functions
    • Type Conversion
      • get_type_converter
      • xl_arg
      • xl_return
      • xl_arg_type
      • xl_return_type
      • TypeParameters
      • Object
    • Ribbon Functions
    • Menu Functions
    • Plotting
    • Custom Task Panes
    • ActiveX Controls
    • Cell Formatting
    • Tables
    • Errors and Exceptions
    • Utility Functions
    • LRU Cache
    • Excel Application Events
    • PyXLL Add-in Events
    • Excel C API Functions
  • What’s new in PyXLL 5
  • Changelog
Close

Type Conversion¶

The following functions and decorators provide access to PyXLL’s type conversion system.

When registering Python functions as Excel worksheet functions using @xl_func, or as Excel macros using @xl_macro, type information can be supplied that informs the PyXLL add-in how to convert between Python and Excel values.

Type information can be provided to PyXLL in a number of different ways, include Python type hints, a function signature string, and using the @xl_arg and @xl_return decorators documented below.

Custom type conversion methods can be registered using the @xl_arg_type and @xl_return_type decorators.

To access PyXLL’s type converters (including any custom type converters you have registered) you can use the get_type_converter function.

See Argument and Return Types for more details about PyXLL’s type conversion features.

  • get_type_converter

  • @xl_arg

  • @xl_return

  • @xl_arg_type

  • @xl_return_type

  • TypeParameters

  • Object

get_type_converter(src_type, dest_type [, src_kwargs=None] [, dest_kwargs=None])[source]

Returns a function to convert objects of type src_type to dest_type.

Even if there is no function registered that converts exactly from src_type to dest_type, as long as there is a way to convert from src_type to dest_type using one or more intermediate types this function will create a function to do that.

Parameters:
  • src_type – Type or signature of type to convert from.

  • dest_type – Type or signature of type to convert to.

  • src_kwargs (dict) – Parameters for the source type (e.g. {'dtype'=float} for numpy_array).

  • dest_kwargs (dict) – Parameters for the destination type (e.g. {'index'=True} for dataframe).

Returns:

Function to convert from src_type to dest_type.

Example usage:

from pyxll import xl_func, get_type_converter

@xl_func("var x: var")
def py_function(x):
    # if x is a number, convert it to a date
    if isinstance(x, float):
        to_date = get_type_converter("var", "date")
        x = to_date(x)
    return "%s : %s" % (x, type(x))
@xl_arg(_name[, _type][, _label][, _description][, **kwargs])[source]

Decorator for providing type information for a function argument. This can be used instead of providing a function signature to @xl_func and @xl_macro.

Parameters:
  • _name (string) – Argument name. This should match the argument name in the function definition.

  • _type – Optional argument type. This should be a recognized type name or the name of a custom type.

  • _label –

    Argument label that will be used in the Excel function wizard.

    Defaults to the argument name.

    @Since PyXLL 5.5.0.

  • _description –

    Argument description that will be used in the Excel function wizard.

    This can be used instead of documenting the parameter in the function’s docstring.

    @Since PyXLL 5.5.0.

  • kwargs – Type parameters for parameterized types (eg NumPy arrays and Pandas types).

@xl_return([_type=None] [, **kwargs])[source]

Decorator for providing type information for a function’s return value. This can be used instead of providing a function signature to @xl_func and @xl_macro.

Parameters:
  • _type – Optional argument type. This should be a recognized type name or the name of a custom type.

  • kwargs – Type parameters for parameterized types (eg NumPy arrays and Pandas types).

@xl_arg_type(name, base_type [, allow_arrays=True] [, macro=None] [, thread_safe=None] [, typing_type=None])[source]

Returns a decorator for registering a function for converting from a base type to a custom type.

Parameters:
  • name (string) – custom type name.

  • base_type (string) – base type.

  • allow_arrays (boolean) – custom type may be passed in an array using the standard [] notation.

  • macro (boolean) – If True all functions using this type will automatically be registered as a macro sheet equivalent function.

  • thread_safe (boolean) – If False any function using this type will never be registered as thread safe.

  • typing_type – An optional typing type that will be recognised as this type when used as a Python type hint.

@xl_return_type(name, base_type [, allow_arrays=True] [, macro=None] [, thread_safe=None] [, typing_type=None])[source]

Returns a decorator for registering a function for converting from a custom type to a base type.

Parameters:
  • name (string) – custom type name.

  • base_type (string) – base type.

  • allow_arrays (boolean) – custom type may be returned as an array using the standard [] notation.

  • macro (boolean) – If True all functions using this type will automatically be registered as a macro sheet equivalent function.

  • thread_safe (boolean) – If False any function using this type will never be registered as thread safe.

  • typing_type – An optional typing type that will be recognised as this type when used as a Python type hint.

class TypeParameters[source]

New in PyXLL 5.12

The TypeParametes class is used in conjunction with typing.Annotated to specify type parameters used by PyXLL when converting values between Python and Excel.

Using the TypeParameters class it is possible to specify options to PyXLL’s type converters using only Python type hints, without having to use additional type specifier strings.

For example, to specify an argument should be treated as a pandas.DataFrame with the first column being the index, instead of using the type specifier string dataframe<index=True> we can use the Python type hint Annotated[pd.DataFrame, TP(index=True)] like this:

from pyxll import xl_func
from pyxll import TypeParameters as TP
from typing import Annotated
import pandas as pd

@xl_func
def df_head(
    df: Annotated[pd.DataFrame, TP(index=True)],
    n: int
) -> Annotated[pd.DataFrame, TP(index=True)]:
    return df.head(n)
type Object

New in PyXLL 5.12, requires Python 3.12+

Object is a generic type alias that can be used where a parameter or returned value should be passed as a cached object using an object handle, instead of directly by value.

The Object[T] type resolves to T when type checking, allowing function that use cached objects to be written with correct typing information.

See Using Type Hints.

from pyxll import xl_func, Object

class CustomObject:
    def __init__(self, name):
        self.name = name

# The 'Object[T]' generic type alias is used as we want PyXLL to return
# the object to Excel as a cached object, but we want type checks to see
# 'CustomObject' as the return type.
@xl_func
def create_object(name: str) -> Object[CustomObject]:
    return CustomObject(name)
« Macro Functions
Ribbon Functions »
  • Home
  • Product
  • Features
  • Documentation
  • Download
  • Pricing
  • Support
  • Documentation
  • Videos
  • FAQ
  • Learn Python
  • Contact Us
  • About
  • About Us
  • Legal
  • Blog
© Copyright PyXLL Ltd