cyberangles blog

Using Assembly Attributes in F#: How to Apply PythonModule for IronPython (C# to F# Translation Guide)

IronPython, an open-source implementation of Python built on the .NET Framework, enables seamless integration between Python and .NET languages like C# and F#. A key aspect of this integration is exposing .NET assemblies as Python modules, which allows Python code to import and use .NET types and methods intuitively.

To achieve this, IronPython relies on assembly attributes—metadata embedded in .NET assemblies—to define how the assembly should be treated when imported into Python. One critical attribute for this purpose is PythonModule, which specifies the name of the Python module associated with the .NET assembly.

While C# developers may be familiar with applying assembly attributes like PythonModule, F# uses a distinct syntax and project structure for attributes, which can be confusing for those transitioning from C#. This guide will demystify assembly attributes in F#, focusing on translating C# PythonModule examples to F# and demonstrating how to use them effectively with IronPython.

2026-01

Table of Contents#

  1. Introduction to Assembly Attributes
  2. Understanding the PythonModule Attribute
  3. C# vs. F#: Assembly Attribute Syntax Differences
  4. Step-by-Step: Applying PythonModule in F#
  5. Common Pitfalls and Solutions
  6. Advanced Use Cases
  7. Conclusion
  8. References

Introduction to Assembly Attributes#

Assembly attributes are pieces of metadata embedded into a .NET assembly (e.g., a .dll or .exe file) that describe the assembly’s identity, version, dependencies, or behavior. Tools, frameworks, and runtime environments (like IronPython) use this metadata to interact with the assembly correctly.

Examples of common assembly attributes include:

  • AssemblyTitle: Specifies the assembly’s friendly name.
  • AssemblyVersion: Defines the version number (e.g., 1.0.0.0).
  • AssemblyDescription: Provides a description of the assembly.

For IronPython, attributes like PythonModule are critical because they bridge .NET and Python, enabling Python to recognize .NET assemblies as native Python modules.

Understanding the PythonModule Attribute#

The PythonModule attribute is specific to IronPython and is defined in the IronPython.Runtime namespace. Its primary role is to:

  • Assign a Python module name to the .NET assembly, allowing Python code to import the assembly using that name (e.g., import mymodule instead of referencing the assembly by its filename).
  • Optionally provide a docstring (documentation string) for the module, which appears when accessing module.__doc__ in Python.

Signature of PythonModule#

The PythonModule attribute has two constructors:

// Simplified signature
public PythonModuleAttribute(string moduleName);
public PythonModuleAttribute(string moduleName, string docString);
  • moduleName: The name used to import the assembly in Python (e.g., "mathutils").
  • docString (optional): A human-readable description of the module.

C# vs. F#: Assembly Attribute Syntax Differences#

While C# and F# both support assembly attributes, their syntax and placement differ significantly. Let’s compare basic assembly attribute usage in both languages to highlight key distinctions.

C# Assembly Attribute Example#

In C#, assembly attributes are typically placed in AssemblyInfo.cs (auto-generated in newer projects) or directly in code files using the [assembly: AttributeName(...)] syntax:

// In AssemblyInfo.cs or a code file
using IronPython.Runtime;
 
[assembly: PythonModule("mymodule", "A sample .NET module for IronPython")]

F# Assembly Attribute Example#

In F#, assembly attributes use the [<assembly: AttributeName(...)] syntax but require explicit marking with [<AssemblyAttribute>] (for custom attributes) and are often placed in a dedicated module (e.g., AssemblyInfo.fs). A minimal F# equivalent of the above C# example is:

// In AssemblyInfo.fs or any F# file
namespace MyFSharpLibrary
 
open IronPython.Runtime
 
[<assembly: PythonModule("mymodule", "A sample F# module for IronPython")>]
[<assembly: AssemblyAttribute>]  // Marks this as an assembly-level attribute
do ()  // Required to execute the attribute application

Key Differences:#

FeatureC#F#
Syntax[assembly: Attribute(...)][<assembly: Attribute(...)] with [<AssemblyAttribute>] (for custom attributes)
PlacementTypically in AssemblyInfo.csTypically in AssemblyInfo.fs (first file in the project)
Execution TriggerImplicitExplicit do () expression to apply the attribute

Step-by-Step: Applying PythonModule in F##

Let’s walk through creating an F# class library, applying the PythonModule attribute, and testing it in IronPython.

4.1 Project Setup#

  1. Open Visual Studio or Rider, and create a new F# Class Library project (targeting .NET 6+ recommended).
  2. Name the project FSharpIronPythonDemo.

4.2 Adding IronPython References#

To use PythonModule, you need to reference IronPython’s libraries:

  1. Right-click the project → Manage NuGet Packages.
  2. Search for and install the IronPython NuGet package (version 3.4.0+ recommended). This adds the IronPython.dll and IronPython.Runtime.dll references.

4.3 Defining the PythonModule Attribute in F##

In F#, assembly attributes are typically placed in AssemblyInfo.fs, which is processed first during compilation. If your project doesn’t have this file:

  1. Right-click the project → Add → New Item → F# File → Name it AssemblyInfo.fs.
  2. Set AssemblyInfo.fs as the first file in the project (right-click the file → Move Up until it’s at the top). This ensures assembly attributes are recognized early.

Add the PythonModule attribute to AssemblyInfo.fs:

// AssemblyInfo.fs
namespace FSharpIronPythonDemo
 
open IronPython.Runtime
 
// Define the Python module name and docstring
[<assembly: PythonModule("fsharp_demo", "A demo module exposing F# types to IronPython")>]
[<assembly: AssemblyAttribute>]  // Marks this as an assembly-level attribute
do ()  // Executes the attribute application

4.4 Exposing F# Types to IronPython#

Next, define an F# type (e.g., a Calculator class) to expose to IronPython. Create a new file Calculator.fs:

// Calculator.fs
namespace FSharpIronPythonDemo
 
type Calculator() =
    /// Adds two integers (exposed to IronPython)
    member this.Add(a: int, b: int) = a + b
 
    /// Multiplies two integers (exposed to IronPython)
    member this.Multiply(a: int, b: int) = a * b

F# types and members are automatically visible to IronPython unless marked internal or private.

4.5 Testing in IronPython#

To verify the setup:

  1. Build the F# project to generate FSharpIronPythonDemo.dll.
  2. Install IronPython (if not already installed) via pip install ironpython.
  3. Create a Python script test_ironpython.py:
    import clr
    # Load the F# assembly (update the path to your .dll)
    clr.AddReference(r"C:\Path\To\FSharpIronPythonDemo\bin\Debug\net6.0\FSharpIronPythonDemo.dll")
     
    # Import the module using the name defined in PythonModule
    import fsharp_demo
     
    # Test the Calculator class
    calc = fsharp_demo.Calculator()
    print(f"2 + 3 = {calc.Add(2, 3)}")       # Output: 2 + 3 = 5
    print(f"4 * 5 = {calc.Multiply(4, 5)}") # Output: 4 * 5 = 20
     
    # Verify the docstring
    print(f"Module docstring: {fsharp_demo.__doc__}") 
    # Output: Module docstring: A demo module exposing F# types to IronPython
  4. Run the script with IronPython: ipy test_ironpython.py. You should see the expected output.

Common Pitfalls and Solutions#

Pitfall 1: PythonModule Attribute Not Recognized#

Issue: IronPython fails to import the module, even after defining PythonModule.
Cause: The attribute is not marked as an assembly-level attribute or is placed in a file processed late in compilation.
Solution:

  • Ensure AssemblyInfo.fs is the first file in your F# project (right-click the file → Move Up).
  • Include [<assembly: AssemblyAttribute>] above the PythonModule attribute.

Pitfall 2: Missing IronPython References#

Issue: Compiler error: The type or namespace name 'PythonModule' could not be found.
Cause: The IronPython NuGet package is not installed.
Solution: Install the IronPython NuGet package via the Package Manager or edit the .fsproj file:

<PackageReference Include="IronPython" Version="3.4.0" />

Pitfall 3: Module Name Mismatch#

Issue: IronPython throws ImportError: No module named 'fsharp_demo'.
Cause: The module name in PythonModule does not match the name used in import.
Solution: Verify the moduleName parameter in PythonModule (e.g., PythonModule("fsharp_demo", ...)) and ensure consistency when importing.

Advanced Use Cases#

1. Adding a Docstring to PythonModule#

Enhance discoverability by adding a docstring to your module:

// In AssemblyInfo.fs
[<assembly: PythonModule(
    "fsharp_demo", 
    "A demo module with math utilities.\n" +
    "Exposes: Calculator (Add, Multiply)"
)>]
[<assembly: AssemblyAttribute>]
do ()

In IronPython, fsharp_demo.__doc__ will now return the full docstring.

2. Combining PythonModule with Other IronPython Attributes#

Use PythonClass or PythonMethod to customize how F# types/methods appear in Python. For example, rename a method for Python:

open IronPython.Runtime.Types
 
type Calculator() =
    [<PythonMethod("add_numbers")>]  // Renames Add to add_numbers in Python
    member this.Add(a: int, b: int) = a + b

In IronPython:

calc = fsharp_demo.Calculator()
print(calc.add_numbers(2, 3))  # Works! Output: 5

Conclusion#

The PythonModule attribute is a powerful tool for integrating F# libraries with IronPython, enabling Python-like imports and seamless interaction with .NET code. By understanding F#’s assembly attribute syntax and following the step-by-step guide, you can easily translate C#-based IronPython workflows to F#.

Key takeaways:

  • Assembly attributes in F# require [<assembly: ...>] and [<AssemblyAttribute>] for custom attributes.
  • Place PythonModule in AssemblyInfo.fs (first file in the project) for visibility.
  • Test imports in IronPython to validate the module name and exposed types.

References#