### Install JuliaCall Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Installation commands for pip and conda environments. ```bash pip install juliacall ``` ```bash conda install conda-forge::pyjuliacall ``` -------------------------------- ### Install PythonCall Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Use the Julia package manager to add the PythonCall package. ```julia pkg> add PythonCall ``` -------------------------------- ### Initialize JuliaCall Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Basic setup for interactive or scripting use by importing the Julia Main module. ```python from juliacall import Main as jl ``` -------------------------------- ### Install Python packages with CondaPkg Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Use the Pkg REPL to add Python dependencies to your project. ```julia julia> using CondaPkg julia> # press ] to enter the Pkg REPL pkg> conda add some_package ``` -------------------------------- ### Configure PythonCall for existing Python installations Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Set the CondaPkg backend to Null to use a pre-installed Python environment without automatic package management. ```julia ENV["JULIA_CONDAPKG_BACKEND"] = "Null" ENV["JULIA_PYTHONCALL_EXE"] = "/path/to/python" # optional ``` ```julia pkg> preference add CondaPkg backend=Null pkg> preference add PythonCall exe=/path/to/python # optional ``` -------------------------------- ### Get Python library handle Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns a handle to the open libpython or C_NULL if unknown. ```julia python_library_handle() ``` -------------------------------- ### pylen Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Gets the length of an object. ```APIDOC ## pylen(x) ### Description The length of `x`. Equivalent to `len(x)` in Python, converted to an `Integer`. ``` -------------------------------- ### Example of ccall requires the compiler error output Source: https://juliapy.github.io/PythonCall.jl/dev/faq This error occurs when incompatible versions of libstdc++.so are loaded by Python libraries before JuliaCall. ```text ERROR: `ccall` requires the compilerTraceback (most recent call last): File "/home/dingraha/projects/pythoncall_import_error/run.py", line 2, in from foo import Foo File "/home/dingraha/projects/pythoncall_import_error/foo.py", line 4, in import juliacall; jl = juliacall.newmodule("FooModule") File "/home/dingraha/projects/pythoncall_import_error/venv/lib/python3.9/site-packages/juliacall/__init__.py", line 218, in init() File "/home/dingraha/projects/pythoncall_import_error/venv/lib/python3.9/site-packages/juliacall/__init__.py", line 214, in init raise Exception('PythonCall.jl did not start properly') Exception: PythonCall.jl did not start properly ``` -------------------------------- ### Define custom wrapper type Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Example of creating a custom Julia struct that wraps a Python object. ```julia # The new type with a field for the Python object being wrapped. struct MyType py::Py end # Says that the object is a wrapper. ispy(x::MyType) = true # Says how to access the underlying Python object. Py(x::MyType) = x.py ``` -------------------------------- ### Get Python executable path Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the file path to the Python interpreter or missing if unknown. ```julia python_executable_path() ``` -------------------------------- ### Get Python interpreter version Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the version of the Python interpreter or missing if unknown. ```julia python_version() ``` -------------------------------- ### Get Python library path Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the file path to libpython or missing if unknown. ```julia python_library_path() ``` -------------------------------- ### Error Message: Heap Corruption Source: https://juliapy.github.io/PythonCall.jl/dev/faq Example of the abort error that can occur on some systems when PyTorch and JuliaCall interact improperly. ```text Python(65251,0x104cf8580) malloc: Heap corruption detected, free list is damaged at 0x600001c17280 *** Incorrect guard value: 1903002876 Python(65251,0x104cf8580) malloc: *** set a breakpoint in malloc_error_break to debug [1] 65251 abort ipython ``` -------------------------------- ### Get underlying pointer Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Retrieves the raw pointer from a Python object. ```julia getptr(x) ``` -------------------------------- ### pyhelp Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to the Python help() function. ```APIDOC ## pyhelp([x]) ### Description Equivalent to `help(x)` in Python. ``` -------------------------------- ### Execute Julia code from Python Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Demonstrates calling Julia functions, generating arrays, and interacting with NumPy. ```python jl.println("Hello from Julia!") # Hello from Julia! x = jl.rand(range(10), 3, 5) x._jl_display() # 3×5 Matrix{Int64}: # 8 1 7 0 6 # 9 2 1 4 0 # 1 8 5 4 0 import numpy numpy.sum(x, axis=0) # array([18, 11, 13, 8, 6], dtype=int64) ``` -------------------------------- ### Get next iterator item Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the next item in the iterator or NULL if exhausted. ```julia unsafe_pynext(x) ``` -------------------------------- ### Load and Use juliacall IPython Extension Source: https://juliapy.github.io/PythonCall.jl/dev/compat Demonstrates loading the extension and using cell magic to synchronize variables between Python and Julia. ```python In [1]: %load_ext juliacall In [2]: x = 2 In [3]: y = 8 In [4]: %%julia x y z ...: z = "$x^$y = $(x^y)"; ...: ...: In [5]: z Out[5]: '2^8 = 256' ``` -------------------------------- ### pywith Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Executes a function within a context manager. ```APIDOC ## pywith(f, o, d=nothing) ### Description Equivalent to `with o as x: f(x)` in Python, where `x` is a `Py`. On success, the value of `f(x)` is returned. If an exception occurs but is suppressed then `d` is returned. ``` -------------------------------- ### Import and use Julia Main module Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall-reference Use the Main module as an entry point for interactive scripts to access Julia functionality. ```python from juliacall import Main as jl jl.println("Hello, world!") ``` -------------------------------- ### Initialize CondaPkg and PythonCall in a script Source: https://juliapy.github.io/PythonCall.jl/dev/faq Ensure CondaPkg is loaded before PythonCall to correctly manage Python package dependencies. ```julia using CondaPkg CondaPkg.add("numpy") using PythonCall np = pyimport("numpy") ``` -------------------------------- ### pyprint Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Prints objects to the standard output. ```APIDOC ## pyprint(...) ### Description Equivalent to `print(...)` in Python. ``` -------------------------------- ### pybinaryio(io::IO) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Julia IO object as a Python binary IO object. ```APIDOC ## pybinaryio(io::IO) ### Description Wrap `io` as a Python binary IO object. ``` -------------------------------- ### Configure PythonCall for system-level Conda or Pixi Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Use the System or SystemPixi backend to leverage a pre-installed Conda or Pixi implementation. ```julia ENV["JULIA_CONDAPKG_BACKEND"] = "System" # or "SystemPixi" for Pixi ENV["JULIA_CONDAPKG_EXE"] = "/path/to/conda" # optional ``` ```julia pkg> preference add CondaPkg backend=System pkg> preference add CondaPkg exe=/path/to/conda # optional ``` -------------------------------- ### Wrapping Python sequences with PyList Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Demonstrates wrapping a Python list as a Julia vector and performing mutations that reflect in the original Python object. ```julia julia> x = pylist([3,4,5]) Python: [3, 4, 5] julia> y = PyList{Union{Int,Nothing}}(x) 3-element PyList{Union{Nothing, Int64}}: 3 4 5 julia> push!(y, nothing) 4-element PyList{Union{Nothing, Int64}}: 3 4 5 nothing julia> append!(y, 1:2) 6-element PyList{Union{Nothing, Int64}}: 3 4 5 nothing 1 2 julia> x Python: [3, 4, 5, None, 1, 2] ``` -------------------------------- ### Error Message: AttributeError Source: https://juliapy.github.io/PythonCall.jl/dev/faq Example of the error encountered when a Python package expects a native Numpy array but receives a Julia ArrayValue. ```text AttributeError: Julia: type Array has no field dtype ``` -------------------------------- ### fix_qt_plugin_path() Source: https://juliapy.github.io/PythonCall.jl/dev/compat Sets the QT_PLUGIN_PATH environment variable to ensure Qt can locate its configuration files. ```APIDOC ## fix_qt_plugin_path() ### Description Attempts to set the `QT_PLUGIN_PATH` environment variable in Python if it is not already set. This resolves issues where Qt fails to find its `qt.conf` file when running within the Julia executable. ``` -------------------------------- ### Construct TimeDelta64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs a TimeDelta64 where the unit is stored at runtime. ```julia TimeDelta64(value, [unit]) ``` -------------------------------- ### Set PythonCall preferences via Pkg REPL Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Use the PreferenceTools package to add configuration preferences directly from the Julia Pkg REPL. ```julia julia> using PreferenceTools julia> # now press ] to enter the Pkg REPL pkg> preference add PythonCall exe=/path/to/python ``` -------------------------------- ### Fix Qt Plugin Path Source: https://juliapy.github.io/PythonCall.jl/dev/compat Configures the QT_PLUGIN_PATH environment variable to ensure Qt locates its configuration files correctly when running within Julia. ```julia fix_qt_plugin_path() ``` -------------------------------- ### Avoid Python interaction during precompilation Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Demonstrates patterns for safely importing Python modules in Julia packages to prevent crashes during precompilation. ```julia module MyModule using PythonCall const foo = pyimport("foo") bar() = foo.bar() # will crash when called end ``` ```julia module MyModule using PythonCall const foo = Ref{Py}() function __init__() foo[] = pyimport("foo") end bar() = foo[].bar() end ``` ```julia module MyModule using PythonCall bar() = pyimport("foo").bar() end ``` ```julia module MyModule using PythonCall bar() = @pyconst(pyimport("foo")).bar() end ``` ```julia module MyModule using PythonCall bar() = @pyconst(pyimport("foo").bar)() end ``` -------------------------------- ### Construct DateTime64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs a DateTime64 where the unit is stored at runtime. ```julia DateTime64(value, [unit]) DateTime64(value, format, [unit]) ``` -------------------------------- ### pytextio(io::IO) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Julia IO object as a Python text IO object. ```APIDOC ## pytextio(io::IO) ### Description Wrap `io` as a Python text IO object. ``` -------------------------------- ### Import PythonCall Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Load the module into the Julia environment. ```julia julia> using PythonCall ``` -------------------------------- ### Activate GUI Event Loop Source: https://juliapy.github.io/PythonCall.jl/dev/compat Enables background event processing for specific GUI frameworks to support interactive modes. ```julia event_loop_on(g::Symbol; interval=0.04, fix=false) ``` -------------------------------- ### Define Julia dependencies in juliapkg.json Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Create a juliapkg.json file to specify required Julia versions and packages for your project. ```json { "julia": "1.5", "packages": { "Example": { "uuid": "7876af07-990d-54b4-ab0e-23690620f79a", "version": "0.5, 0.6" } } } ``` -------------------------------- ### pytable(src, format=:pandas; ...) Source: https://juliapy.github.io/PythonCall.jl/dev/compat Constructs a Python table from a Tables.jl-compatible table source. ```APIDOC ## pytable(src, format=:pandas; ...) ### Description Constructs a Python table from a Tables.jl-compatible table `src`. The `format` parameter determines the resulting Python object type. ### Parameters - **src** (Any) - Required - A Tables.jl-compatible table. - **format** (Symbol) - Optional - The target format. Supported values: `:pandas` (pandas.DataFrame), `:columns` (dict), `:rows` (list of namedtuples), `:rowdicts` (list of dicts). - **...** (Keyword arguments) - Optional - Additional arguments passed to the constructor (e.g., to the `DataFrame` constructor when using `:pandas`). ``` -------------------------------- ### PythonCall.pyproperty Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates a Python property with getter, setter, and deleter. ```APIDOC ## pyproperty(; get=nothing, set=nothing, del=nothing, doc=nothing) ### Description Creates a Python `property` with the given getter, setter, and deleter functions. If provided, functions are converted to Python callables via `pyfunc`. ``` -------------------------------- ### PythonCall.PySet Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python set as a Julia AbstractSet. ```APIDOC ## PySet{T=Py}([x]) Wraps the Python set `x` (or anything satisfying the set interface) as an `AbstractSet{T}`. If `x` is not a Python object, it is converted to one using `pyset`. ``` -------------------------------- ### Pass variables and return multiple outputs with @pyexec Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Demonstrates passing named variables to Python and returning multiple functions or values, including type casting. ```julia julia> @pyexec (num=10) => """ def add(a, b): return a + b def subtract(a, b): return a - b plusone = num + 1 """ => (add, subtract, plusone::Float64) (add = , subtract = , plusone = 11.0) julia> add(4, 3) Python: 7 julia> subtract(4, 3) Python: 1 julia> plusone 11.0 ``` -------------------------------- ### Configure PythonCall for existing Conda environments Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Use the Current backend to utilize an already activated Conda environment. ```julia ENV["JULIA_CONDAPKG_BACKEND"] = "Current" ENV["JULIA_CONDAPKG_EXE"] = "/path/to/conda" # optional ``` ```julia pkg> preference add CondaPkg backend=Current pkg> preference add CondaPkg exe=/path/to/conda # optional ``` -------------------------------- ### PythonCall.pyexec Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Execute Python code. ```APIDOC ## pyexec([T=Nothing], code, globals, locals=nothing) ### Description Executes the provided Python code. If T is provided, it extracts variables from the local scope. ### Signature `pyexec([T=Nothing], code, globals, locals=nothing)` ``` -------------------------------- ### pyin Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks for membership in a Python object. ```APIDOC ## pyin(v, x) ### Description Equivalent to `v in x` in Python. ``` -------------------------------- ### event_loop_on(g::Symbol; interval=0.04, fix=false) Source: https://juliapy.github.io/PythonCall.jl/dev/compat Activates an event loop for a specified GUI framework, allowing it to run in the background of a Julia session. ```APIDOC ## event_loop_on(g::Symbol; interval=0.04, fix=false) ### Description Activates an event loop for the GUI framework `g`, so that the framework can run in the background of a Julia session. The event loop runs every `interval` seconds. ### Parameters - **g** (Symbol) - Required - The GUI framework to activate. Supported values: :pyqt4, :pyqt5, :pyside, :pyside2, :pyside6, :gtk, :gtk3, :wx, :tkinter. - **interval** (Float64) - Optional - The interval in seconds at which the event loop runs. Defaults to 0.04. - **fix** (Bool) - Optional - If true and `g` is a Qt framework, `fix_qt_plugin_path` is called. Defaults to false. ``` -------------------------------- ### pysetitem Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Sets an item in a Python object. ```APIDOC ## pysetitem(x, k, v) ### Description Equivalent to `setitem(x, k, v)` or `x[k] = v` in Python. ``` -------------------------------- ### Create a new Julia module Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall-reference Create a new module with a specified name, typically used within packages. ```python newmodule(name) ``` -------------------------------- ### Create a Python property Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates a Python property with optional getter, setter, and deleter functions. ```julia pyproperty(; get=nothing, set=nothing, del=nothing, doc=nothing) pyproperty(get) ``` -------------------------------- ### PythonCall.pyall Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to the Python all(x) function. ```APIDOC ## pyall(x) ### Description Returns true if all elements of the iterable x are true (or if the iterable is empty). ### Signature `pyall(x)` ``` -------------------------------- ### Wrapping Python file objects with PyIO Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Views a Python file object as a Julia IO object for standard IO operations. ```julia julia> x = pyimport("io").StringIO() Python: <_io.StringIO object at 0x000000006579BC70> julia> y = PyIO(x) PyIO(, false, true, false, 4096, UInt8[], 4096, UInt8[]) julia> println(y, "Hello, world!") julia> flush(y) julia> x.seek(0) Python: 0 julia> x.read() Python: 'Hello, world!\n' ``` -------------------------------- ### PythonCall.pyany Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to the Python any(x) function. ```APIDOC ## pyany(x) ### Description Returns true if any element of the iterable x is true. ### Signature `pyany(x)` ``` -------------------------------- ### Define PyIO wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python IO stream as a Julia IO stream with configurable buffering and text/binary modes. ```julia PyIO(x; own=false, text=missing, line_buffering=false, buflen=4096) ``` -------------------------------- ### Create a new Julia module Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Use this approach when developing packages to avoid polluting the global Main namespace. ```python import juliacall jl = juliacall.newmodule("SomeName") ``` -------------------------------- ### Define PySet wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python set or set-like object as a Julia AbstractSet. ```julia PySet{T=Py}([x]) ``` -------------------------------- ### Wrap IO streams for Python Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Functions to wrap Julia IO streams as Python binary or text IO objects. ```julia pybinaryio(io::IO) ``` ```julia pytextio(io::IO) ``` -------------------------------- ### pynext Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Retrieves the next item from an iterator. ```APIDOC ## pynext(x, [d]) ### Description Equivalent to `next(x, d)` in Python. Returns the next item from the iterator `x`. If there are no more items, returns `d` if given, else raises `StopIteration`. ``` -------------------------------- ### juliacall.newmodule(name) Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall-reference Creates a new Julia module with the specified name. ```APIDOC ## juliacall.newmodule(name) ### Description Creates a new module with the given name. ### Parameters - **name** (str) - Required - The name of the new module. ``` -------------------------------- ### Accessing Parametric Types with TypeValue Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall-reference Demonstrates using indexing on a TypeValue to replicate Julia's curly syntax for parametric types. ```python from juliacall import Main as jl # equivalent to Vector{Int}() in Julia jl.Vector[jl.Int]() ``` -------------------------------- ### TimeDelta64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs a TimeDelta64 type where the unit is stored as a run-time value. ```APIDOC ## TimeDelta64 ### Description Construct a `TimeDelta64` with the given `value` and `unit`. The unit is stored as a run-time value, and the memory layout matches `numpy.timedelta64`. ### Signature `TimeDelta64(value, [unit])` ### Parameters - **value** (Integer, String) - Required - The value to represent. - **unit** (Unit) - Optional - The time unit for the value. ``` -------------------------------- ### Compare less than or equal with pyle Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks if x is less than or equal to y, equivalent to x <= y in Python. ```julia pyle(x, y) pyle(Bool, x, y) ``` -------------------------------- ### Interact with Python Modules Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Import Python modules and perform operations using Python objects. ```julia julia> re = pyimport("re") Python: julia> words = re.findall("[a-zA-Z]+", "PythonCall.jl is very useful!") Python: ['PythonCall', 'jl', 'is', 'very', 'useful'] julia> sentence = Py(" ").join(words) Python: 'PythonCall jl is very useful' julia> pyconvert(String, sentence) "PythonCall jl is very useful" ``` -------------------------------- ### Python Builtin Equivalents Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Functions that provide direct equivalents to Python's built-in functions. ```julia pyall(x) ``` ```julia pyany(x) ``` ```julia pyascii(x) ``` ```julia pycall(f, args...; kwargs...) ``` ```julia pycallable(x) ``` ```julia pycompile(...) ``` ```julia pycontains(x, v) ``` ```julia pydelattr(x, k) ``` ```julia pydelitem(x, k) ``` ```julia pydir(x) ``` -------------------------------- ### PythonCall.pystaticmethod Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Converts a callable to a Python static method. ```APIDOC ## pystaticmethod(f; ...) ### Description Converts callable `f` to a Python static method. If `f` is a Julia function, it is converted using `pyfunc`. ``` -------------------------------- ### Execute Python Code Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Functions and macros for executing Python code, with support for persistent module scope. ```julia pyexec([T=Nothing], code, globals, locals=nothing) ``` ```julia pyexec(@NamedTuple{ans::Float64}, "ans=x+y", Main, (x=1.1, y=2.2)) # returns (ans = 3.3,) ``` ```julia pyexec("global x; x=12", Main) pyeval(Int, "x", Main) # returns 12 ``` ```julia @pyexec [inputs =>] code [=> outputs] ``` ```julia @pyexec (x=1.1, y=2.2) => `ans=x+y` => ans::Float64 # returns 3.3 ``` ```julia @pyexec `global x; x=12` @pyeval `x` => Int # returns 12 ``` -------------------------------- ### Create a new Py object Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates a new Py object representing the Python object at the given pointer. Steals the reference if a pointer is provided. ```julia pynew([ptr]) ``` -------------------------------- ### DateTime64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs a DateTime64 type where the unit is stored as a run-time value. ```APIDOC ## DateTime64 ### Description Construct a `DateTime64` with the given `value` and `unit`. The unit is stored as a run-time value, and the memory layout matches `numpy.datetime64`. ### Signature `DateTime64(value, [unit])` `DateTime64(value, format, [unit])` ### Parameters - **value** (Integer, Dates.Date, Dates.DateTime, String) - Required - The value to represent. - **unit** (Unit) - Optional - The time unit for the value. - **format** (String) - Optional - Format string for parsing the value. ``` -------------------------------- ### pyimport Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Imports Python modules or attributes. ```APIDOC ## pyimport(m) ## pyimport(m => k) ## pyimport(m => (k1, k2, ...)) ## pyimport(m1, m2, ...) ### Description Import a module `m`, or an attribute `k`, or a tuple of attributes. If several arguments are given, return the results of importing each one in a tuple. ``` -------------------------------- ### pyrepr Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the string representation of an object. ```APIDOC ## pyrepr(x) ### Description Equivalent to `repr(x)` in Python. ``` -------------------------------- ### Define PyTable wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps an object as a Tables.jl-compatible table. ```julia PyTable(x) ``` -------------------------------- ### pynot(x) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the falsiness of x, equivalent to not x in Python, converted to a Julia Bool. ```APIDOC ## pynot(x) ### Description Returns the falsiness of x, equivalent to not x in Python, converted to a Julia Bool. ``` -------------------------------- ### PythonCall.PyIO Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python IO stream as a Julia IO stream. ```APIDOC ## PyIO(x; own=false, text=missing, line_buffering=false, buflen=4096) Wrap the Python IO stream `x` as a Julia IO stream. When this goes out of scope and is finalized, it is automatically flushed. ``` -------------------------------- ### Evaluate Python Code Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Functions and macros for evaluating Python code strings or commands. ```julia pyeval([T=Py], code, globals, locals=nothing) ``` ```julia pyeval(Float64, "x+y", Main, (x=1.1, y=2.2)) # returns 3.3 ``` ```julia @pyeval [inputs =>] code [=> T] ``` ```julia @pyeval (x=1.1, y=2.2) => `x+y` => Float64 # returns 3.3 ``` -------------------------------- ### PythonCall.@pyeval Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Macro to evaluate a Python expression. ```APIDOC ## @pyeval [inputs =>] code [=> T] ### Description Macro version of pyeval that evaluates code in a new local scope. ### Signature `@pyeval [inputs =>] code [=> T]` ``` -------------------------------- ### PythonCall.@pyexec Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Macro to execute Python code. ```APIDOC ## @pyexec [inputs =>] code [=> outputs] ### Description Macro version of pyexec to execute code and optionally extract outputs. ### Signature `@pyexec [inputs =>] code [=> outputs]` ``` -------------------------------- ### Define PyObjectArray wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates an array of Py objects that supports the Python buffer protocol. ```julia PyObjectArray(undef, dims...) PyObjectArray(array) ``` -------------------------------- ### Define PyList wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python list or sequence as a Julia AbstractVector. ```julia PyList{T=Py}([x]) ``` -------------------------------- ### pytruth(x) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the truthiness of x, equivalent to bool(x) in Python, converted to a Julia Bool. ```APIDOC ## pytruth(x) ### Description Returns the truthiness of x, equivalent to bool(x) in Python, converted to a Julia Bool. ``` -------------------------------- ### Create a Python type with pytype Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Defines a new Python class using Julia functions, including methods, class methods, static methods, and properties. ```julia pytype(name, bases, dict) ``` ```julia Foo = pytype("Foo", (), [ "__module__" => "__main__", pyfunc( name = "__init__", doc = """ Specify x and y to store in the Foo. If omitted, y defaults to None. """, function (self, x, y = nothing) self.x = x self.y = y return end, ), pyfunc( name = "__repr__", self -> "Foo($(self.x), $(self.y))", ), pyclassmethod( name = "frompair", doc = "Construct a Foo from a tuple of length two.", (cls, xy) -> cls(xy...), ), pystaticmethod( name = "hello", doc = "Prints a friendly greeting.", (name) -> println("Hello, $name"), ), "xy" => pyproperty( doc = "A tuple of x and y.", get = (self) -> (self.x, self.y), set = function (self, xy) (x, y) = xy self.x = x self.y = y nothing end, ), ]) ``` -------------------------------- ### Arithmetic Functions Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference A collection of functions that map directly to Python arithmetic operators and built-in functions. ```APIDOC ## Arithmetic Functions ### Description These functions provide direct equivalents to Python's arithmetic operators and built-in functions. They can be used to perform operations on Python objects within Julia. ### Functions - **pyneg(x)**: Equivalent to `-x` in Python. - **pypos(x)**: Equivalent to `+x` in Python. - **pyabs(x)**: Equivalent to `abs(x)` in Python. - **pyinv(x)**: Equivalent to `~x` in Python. - **pyindex(x)**: Convert `x` losslessly to an `int`. - **pyadd(x, y)**: Equivalent to `x + y` in Python. - **pysub(x, y)**: Equivalent to `x - y` in Python. - **pymul(x, y)**: Equivalent to `x * y` in Python. - **pymatmul(x, y)**: Equivalent to `x @ y` in Python. - **pypow(x, y, z=None)**: Equivalent to `x ** y` or `pow(x, y, z)` in Python. - **pyfloordiv(x, y)**: Equivalent to `x // y` in Python. - **pytruediv(x, y)**: Equivalent to `x / y` in Python. - **pymod(x, y)**: Equivalent to `x % y` in Python. - **pydivmod(x, y)**: Equivalent to `divmod(x, y)` in Python. - **pylshift(x, y)**: Equivalent to `x << y` in Python. - **pyrshift(x, y)**: Equivalent to `x >> y` in Python. - **pyand(x, y)**: Equivalent to `x & y` in Python. - **pyxor(x, y)**: Equivalent to `x ^ y` in Python. - **pyor(x, y)**: Equivalent to `x | y` in Python. ``` ```APIDOC ## In-place Arithmetic Functions ### Description These functions perform in-place arithmetic operations, equivalent to Python's augmented assignment operators. ### Functions - **pyiadd(x, y)**: Equivalent to `x += y`. - **pyisub(x, y)**: Equivalent to `x -= y`. - **pyimul(x, y)**: Equivalent to `x *= y`. - **pyimatmul(x, y)**: Equivalent to `x @= y`. - **pyipow(x, y, z=None)**: Equivalent to `x **= y`. - **pyifloordiv(x, y)**: Equivalent to `x //= y`. - **pyitruediv(x, y)**: Equivalent to `x /= y`. - **pyimod(x, y)**: Equivalent to `x %= y`. - **pyilshift(x, y)**: Equivalent to `x <<= y`. - **pyirshift(x, y)**: Equivalent to `x >>= y`. - **pyiand(x, y)**: Equivalent to `x &= y`. - **pyixor(x, y)**: Equivalent to `x ^= y`. - **pyior(x, y)**: Equivalent to `x |= y`. ``` -------------------------------- ### Convert to a Python static method Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Converts a callable to a Python static method, ensuring arguments are passed as Py objects. ```julia pystaticmethod(f; ...) ``` -------------------------------- ### pyiter Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates an iterator from an object. ```APIDOC ## pyiter(x) ### Description Equivalent to `iter(x)` in Python. ``` -------------------------------- ### Compare less than with pylt Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks if x is less than y, equivalent to x < y in Python. ```julia pylt(x, y) pylt(Bool, x, y) ``` -------------------------------- ### Execute Python code with @pyexec Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Uses the @pyexec macro to define a Python function and map it to a Julia variable. ```julia julia> @pyexec """ global re import re def my_sentence(s): words = re.findall("[a-zA-Z]+", s) sentence = " ".join(words) return sentence """ => my_sentence Python: julia> sentence = my_sentence("PythonCall.jl is very useful!") Python: 'PythonCall jl is very useful' ``` -------------------------------- ### pyne(x, y) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to x != y in Python. The version with Bool converts the result to a Julia Bool. ```APIDOC ## pyne(x, y) ### Description Equivalent to x != y in Python. The second form `pyne(Bool, x, y)` converts the result to a Julia Bool. ``` -------------------------------- ### Construct InlineDateTime64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs an InlineDateTime64 where the unit is encoded in the type. ```julia InlineDateTime64{unit}(value) InlineDateTime64{unit}(value, format) InlineDateTime64(value, [unit]) InlineDateTime64(value, format, [unit]) ``` -------------------------------- ### Evaluate Julia code strings Source: https://juliapy.github.io/PythonCall.jl/dev/juliacall Use seval to execute Julia code strings, commonly used for importing Julia modules. ```python from array import array jl.seval("using Statistics") x = array('i', [1, 2, 3]) jl.mean(x) # 2.0 y = array('i', [2,4,8]) jl.cor(x, y) # 0.9819805060619657 ``` -------------------------------- ### Copy Python object into destination Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Copies the source Python object into the destination Py object. Used for module-level constant initialization. ```julia pycopy!(dst::Py, src) ``` -------------------------------- ### Wrapping Python arrays with PyArray Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Provides a Julia array view of Python objects satisfying the buffer protocol or numpy array interface. ```julia julia> x = pyimport("array").array("i", [3, 4, 5]) Python: array('i', [3, 4, 5]) julia> y = PyArray(x) 3-element PyArray{Int32, 1, true, true, Int32}: 3 4 5 julia> sum(y) 12 julia> y[1] = 0 0 julia> x Python: array('i', [0, 4, 5]) ``` -------------------------------- ### Construct InlineTimeDelta64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs an InlineTimeDelta64 where the unit is encoded in the type. ```julia InlineTimeDelta64{unit}(value) InlineTimeDelta64(value, [unit]) ``` -------------------------------- ### Parallel Python Execution with GIL Management Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Uses GIL unlock/lock macros to safely execute Python code across multiple Julia threads. ```julia PythonCall.GIL.@unlock Threads.@threads for i in 1:4 PythonCall.GIL.@lock pyimport("time").sleep(5) end ``` -------------------------------- ### pysetattr Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Sets an attribute on a Python object. ```APIDOC ## pysetattr(x, k, v) ### Description Equivalent to `setattr(x, k, v)` or `x.k = v` in Python. ``` -------------------------------- ### pyeq(x, y) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to x == y in Python. The version with Bool converts the result to a Julia Bool. ```APIDOC ## pyeq(x, y) ### Description Equivalent to x == y in Python. The second form `pyeq(Bool, x, y)` converts the result to a Julia Bool. ``` -------------------------------- ### Compare greater than or equal with pyge Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks if x is greater than or equal to y, equivalent to x >= y in Python. ```julia pyge(x, y) pyge(Bool, x, y) ``` -------------------------------- ### InlineTimeDelta64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs an InlineTimeDelta64 type where the unit is part of the type definition. ```APIDOC ## InlineTimeDelta64 ### Description Construct an `InlineTimeDelta64` with the given `value` and `unit`. The unit is part of the type. ### Signature `InlineTimeDelta64{unit}(value)` `InlineTimeDelta64(value, [unit])` ### Parameters - **value** (Integer, String) - Required - The value to represent. Can be an integer, "NaT", or "NaN". - **unit** (Unit) - Optional - The time unit for the value. ``` -------------------------------- ### Wrap Julia values as raw Python objects with pyjlraw Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Julia object into a Python object with a rigid Julian interface. ```julia pyjlraw(v) ``` -------------------------------- ### pylt(x, y) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to x < y in Python. The version with Bool converts the result to a Julia Bool. ```APIDOC ## pylt(x, y) ### Description Equivalent to x < y in Python. The second form `pylt(Bool, x, y)` converts the result to a Julia Bool. ``` -------------------------------- ### pyjlraw(v) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Julia object into a Python object with a rigid Julian interface. ```APIDOC ## pyjlraw(v) ### Description Create a Python object wrapping the Julia object `x`. It has type `juliacall.RawValue`, which provides a rigid "Julian" interface. ``` -------------------------------- ### InlineDateTime64 Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Constructs an InlineDateTime64 type where the unit is part of the type definition. ```APIDOC ## InlineDateTime64 ### Description Construct an `InlineDateTime64` with the given `value` and `unit`. The unit is part of the type, so an instance consists of one `Int64` for the value. ### Signature `InlineDateTime64{unit}(value)` `InlineDateTime64{unit}(value, format)` `InlineDateTime64(value, [unit])` `InlineDateTime64(value, format, [unit])` ### Parameters - **value** (Integer, Dates.Date, Dates.DateTime, String) - Required - The value to represent. Can be an integer, date/time object, "NaT", "NaN", or a string to be parsed. - **unit** (Unit) - Optional - The time unit for the value. - **format** (String) - Optional - Format string for parsing the value. ``` -------------------------------- ### Define PyException wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python exception as a Julia Exception. ```julia PyException(x) ``` -------------------------------- ### Convert Python list to Julia vector Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Demonstrates converting a Python list to various Julia vector types using pyconvert. ```julia julia> x = pylist([3.4, 5.6]) Python: [3.4, 5.6] julia> pyconvert(Vector, x) 2-element Vector{Float64}: 3.4 5.6 julia> pyconvert(Vector{Float32}, x) 2-element Vector{Float32}: 3.4 5.6 julia> pyconvert(Any, x) 2-element PyList{Any}: 3.4 5.6 ``` -------------------------------- ### PythonCall.PyDict Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python dict as a Julia AbstractDict. ```APIDOC ## PyDict{K=Py,V=Py}([x]) Wraps the Python dict `x` (or anything satisfying the mapping interface) as an `AbstractDict{K,V}`. If `x` is not a Python object, it is converted to one using `pydict`. ``` -------------------------------- ### pyge(x, y) Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Equivalent to x >= y in Python. The version with Bool converts the result to a Julia Bool. ```APIDOC ## pyge(x, y) ### Description Equivalent to x >= y in Python. The second form `pyge(Bool, x, y)` converts the result to a Julia Bool. ``` -------------------------------- ### Convert to a Python class method Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Converts a callable to a Python class method, ensuring arguments are passed as Py objects. ```julia pyclassmethod(f; ...) ``` -------------------------------- ### PythonCall.PyList Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python list or sequence as a Julia AbstractVector. ```APIDOC ## PyList{T=Py}([x]) Wraps the Python list `x` (or anything satisfying the sequence interface) as an `AbstractVector{T}`. If `x` is not a Python object, it is converted to one using `pylist`. ``` -------------------------------- ### Register a custom conversion rule Source: https://juliapy.github.io/PythonCall.jl/dev/conversion-to-julia Use this function to register a new conversion rule for pyconvert. It should typically be called within the __init__ function of a module to avoid issues during precompilation. ```julia pyconvert_add_rule(tname::String, T::Type, func::Function, priority::PyConvertPriority=PYCONVERT_PRIORITY_NORMAL) ``` -------------------------------- ### PythonCall.pyeval Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Evaluate a Python expression. ```APIDOC ## pyeval([T=Py], code, globals, locals=nothing) ### Description Evaluates the given Python code string and returns the result converted to type T. ### Signature `pyeval([T=Py], code, globals, locals=nothing)` ``` -------------------------------- ### @py expr Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Evaluates an expression using Python-like syntax and semantics, returning a Py object. It supports literals, function calls, attribute access, indexing, and various Python statements. ```APIDOC ## @py expr ### Description Evaluates the provided expression using Python-like syntax and semantics. It translates Python-style operations (calls, operators, attribute access) into their corresponding PythonCall operations and returns the result as a `Py` object. ### Syntax `@py expr` ### Supported Features - **Literals and names:** Numeric, string, `None`, `True`, `False`, and containers. - **Calls and operators:** Translates to `pycall` and `py*` helpers. - **Attribute access and indexing:** Maps to `pygetattr`, `pygetitem`, and `pyslice`. - **Statements:** Supports assignments, deletions, control flow (`if`, `while`, `for`), and imports. - **Interop:** Use `@jl` to splice Julia expressions into the Python evaluation. ``` -------------------------------- ### Convert Python objects to Julia with @pyconvert Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Macro version of pyconvert that evaluates to a specified expression on failure. ```julia @pyconvert(T, x, [onfail]) ``` -------------------------------- ### Define PyDict wrapper Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Python dict or mapping as a Julia AbstractDict. ```julia PyDict{K=Py,V=Py}([x]) ``` -------------------------------- ### PythonCall.pyfunc Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Wraps a Julia callable as a Python function. ```APIDOC ## pyfunc(f; [name], [qualname], [doc], [signature]) ### Description Wraps the callable `f` as an ordinary Python function. Arguments passed to `f` are always of type `Py` and are not automatically converted. ``` -------------------------------- ### @pyconst ex Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Creates a constant Python object that is evaluated once and cached, ensuring the same Julia object is returned on subsequent calls. ```APIDOC ## @pyconst ex ### Description Equivalent to `Py(ex)`, but ensures the expression is evaluated only once. Subsequent calls return the exact same Julia object. ### Syntax `@pyconst ex` ### Notes - If `ex` is a string literal, the string is interned. - Do not use this macro at the top level of a module; use `pynew()` and `pycopy!()` instead. ``` -------------------------------- ### Compare inequality with pyne Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks if two objects are not equal, equivalent to x != y in Python. ```julia pyne(x, y) pyne(Bool, x, y) ``` -------------------------------- ### Compare equality with pyeq Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Checks if two objects are equal, equivalent to x == y in Python. ```julia pyeq(x, y) pyeq(Bool, x, y) ``` -------------------------------- ### PythonCall Builtin Functions Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference A collection of functions providing direct equivalents to Python's built-in operations. ```julia pyhelp([x]) ``` ```julia pyimport(m) pyimport(m => k) pyimport(m => (k1, k2, ...)) pyimport(m1, m2, ...) ``` ```julia pyin(v, x) ``` ```julia pyis(x, y) ``` ```julia pyisinstance(x, t) ``` ```julia pyissubclass(s, t) ``` ```julia pyiter(x) ``` ```julia pylen(x) ``` ```julia pynext(x, [d]) ``` ```julia pyprint(...) ``` ```julia pyrepr(x) ``` ```julia pysetattr(x, k, v) ``` ```julia pysetitem(x, k, v) ``` ```julia pytype(x) ``` ```julia pywith(f, o, d=nothing) ``` -------------------------------- ### Access Python Builtins Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall Access Python built-in objects and types via the pybuiltins interface. ```julia julia> pybuiltins.None Python: None julia> pybuiltins.True Python: True julia> pybuiltins.ValueError("some error") Python: ValueError('some error') ``` -------------------------------- ### pytype Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Returns the type of a Python object. ```APIDOC ## pytype(x) ### Description The Python `type` of `x`. ``` -------------------------------- ### pyisinstance Source: https://juliapy.github.io/PythonCall.jl/dev/pythoncall-reference Tests if an object is of a specific type. ```APIDOC ## pyisinstance(x, t) ### Description Test if `x` is of type `t`. Equivalent to `isinstance(x, t)` in Python. ```