numba package

Subpackages

Submodules

numba.assume module

A place to store all assumptions made in various part of the code base.

This allow us to do a usage analysis to discover all code that is assuming something.

Each assumption is defined as a global variable. Its value is the description of the assumption. Code that makes the assumption should assert the_assumption

numba.bytecode module

From NumbaPro

class numba.bytecode.ByteCode(func)

Bases: numba.bytecode.ByteCodeBase

class numba.bytecode.ByteCodeBase(func, func_qualname, argspec, filename, co_names, co_varnames, co_consts, co_freevars, table, labels)

Bases: object

argspec
co_consts
co_freevars
co_names
co_varnames
dump()
filename
func
func_name
func_qualname
labels
table
class numba.bytecode.ByteCodeInst(offset, opcode, arg)

Bases: object

  • offset:

    byte offset of opcode

  • opcode:

    opcode integer value

  • arg:

    instruction arg

  • lineno:

    -1 means unknown

arg
block_effect

Effect of the block stack Returns +1 (push), 0 (none) or -1 (pop)

classmethod get(offset, opname, arg)
get_jump_target()
is_jump
is_terminator
lineno
next
offset
opcode
opname
class numba.bytecode.ByteCodeIter(code)

Bases: object

next()
read_arg(size)
class numba.bytecode.ByteCodeOperation(inst, args)

Bases: object

exception numba.bytecode.ByteCodeSupportError

Bases: exceptions.Exception

class numba.bytecode.CustomByteCode(func, func_qualname, argspec, filename, co_names, co_varnames, co_consts, co_freevars, table, labels)

Bases: numba.bytecode.ByteCodeBase

A simplified ByteCode class, used for hosting inner loops when loop-lifting.

numba.bytecode.get_code_object(obj)

Shamelessly borrowed from llpython

numba.bytecode.get_function_object(obj)

Objects that wraps function should provide a “__numba__” magic attribute that contains a name of an attribute that contains the actual python function object.

class numba.bytecode.opcode_info

Bases: tuple

opcode_info(argsize,)

argsize

Alias for field number 0

numba.callwrapper module

class numba.callwrapper.PyCallWrapper(context, module, func, fndesc, exceptions)

Bases: object

build()
build_wrapper(api, builder, closure, args, kws)
make_const_string(string)
make_exception_switch(api, builder, code)

Handle user defined exceptions. Build a switch to check which exception class was raised.

make_keywords(kws)

numba.cffi_support module

Alias to numba.typing.cffi_utils for backward compatibility

numba.cgutils module

Generic helpers for LLVM code generation.

class numba.cgutils.IfBranchObj(builder, bbenter, bbend)

Bases: object

class numba.cgutils.Structure(context, builder, value=None, ref=None, cast_ref=False)

Bases: object

A high-level object wrapping a alloca’ed LLVM structure, including named fields and attribute access.

class numba.cgutils.VerboseProxy(obj)

Bases: object

Use to wrap llvm.core.Builder to track where segfault happens

numba.cgutils.add_postfix(name, postfix)

Add postfix to string. If the postfix is already there, add a counter.

numba.cgutils.alloca_once(builder, ty, size=None, name='')

Allocate stack memory at the entry block of the current function pointed by builder withe llvm type ty. The optional size arg set the number of element to allocate. The default is 1. The optional name arg set the symbol name inside the llvm IR for debugging.

numba.cgutils.append_basic_block(builder, name='')
numba.cgutils.as_bool_bit(builder, value)
numba.cgutils.as_bool_byte(builder, value)
numba.cgutils.cbranch_or_continue(builder, cond, bbtrue)

Branch conditionally or continue.

Note: a new block is created and builder is moved to the end of the new
block.
numba.cgutils.divmod_by_constant(builder, val, divisor)

Compute the (quotient, remainder) of val divided by the constant positive divisor. The semantics reflects those of Python integer floor division, rather than C’s / LLVM’s signed division and modulo. The difference lies with a negative val.

numba.cgutils.for_range(*args, **kwds)
numba.cgutils.for_range_slice(*args, **kwds)

Generate LLVM IR for a for-loop based on a slice

builder : object
Builder object
start : int
The beginning value of the slice
stop : int
The end value of the slice
step : int
The step value of the slice
intp :
The data type
inc : boolean, optional
A flag to handle the step < 0 case, in which case we decrement the loop
None
numba.cgutils.gep(builder, ptr, *inds)
numba.cgutils.get_function(builder)
numba.cgutils.get_item_pointer(builder, aryty, ary, inds, wraparound=False)
numba.cgutils.get_item_pointer2(builder, data, shape, strides, layout, inds, wraparound=False)
numba.cgutils.get_module(builder)
numba.cgutils.get_null_value(ltype)
numba.cgutils.get_range_from_slice(builder, slicestruct)
numba.cgutils.get_record_data(builder, record)
numba.cgutils.get_record_member(builder, record, offset, typ)
numba.cgutils.get_strides_from_slice(builder, ndim, strides, slice, ax)
numba.cgutils.global_constant(builder_or_module, name, value, linkage=LINKAGE_INTERNAL(8))

Get or create a (LLVM module-)global constant with name or value.

numba.cgutils.goto_block(*args, **kwds)

A context manager which temporarily positions builder at the end of basic block bb (but before any terminator).

numba.cgutils.goto_entry_block(*args, **kwds)
numba.cgutils.guard_null(context, builder, value)
numba.cgutils.guard_zero(context, builder, value)
numba.cgutils.if_likely(*args, **kwds)
numba.cgutils.if_unlikely(*args, **kwds)
numba.cgutils.ifelse(*args, **kwds)
numba.cgutils.ifnot(*args, **kwds)
numba.cgutils.ifthen(*args, **kwds)
numba.cgutils.inbound_gep(builder, ptr, *inds)
numba.cgutils.init_record_by_ptr(builder, ltyp, ptr)
numba.cgutils.is_false(builder, value)

Return a predicate representing whether value is equal to zero.

numba.cgutils.is_neg_int(builder, val)
numba.cgutils.is_not_null(builder, val)
numba.cgutils.is_not_scalar_zero(builder, value)

Return a predicate representin whether a value is not equal to zero. not exactly “not is_scalar_zero” because of nans

numba.cgutils.is_null(builder, val)
numba.cgutils.is_pointer(ltyp)

Whether the LLVM type typ is a struct type.

numba.cgutils.is_scalar_neg(builder, value)

is _value_ negative?. Assumes _value_ is signed

numba.cgutils.is_scalar_zero(builder, value)

Return a predicate representing whether value is equal to zero.

numba.cgutils.is_scalar_zero_or_nan(builder, value)

Return a predicate representing whether value is equal to either zero or NaN.

numba.cgutils.is_struct(ltyp)

Whether the LLVM type typ is a pointer type.

numba.cgutils.is_struct_ptr(ltyp)

Whether the LLVM type typ is a pointer-to-struct type.

numba.cgutils.is_true(builder, value)

Return a predicate representin whether a value is not equal to zero. not exactly “not is_scalar_zero” because of nans

numba.cgutils.loop_nest(*args, **kwds)
numba.cgutils.make_anonymous_struct(builder, values)

Create an anonymous struct constant containing the given LLVM values.

numba.cgutils.normalize_slice(builder, slice, length)

Clip stop

numba.cgutils.pack_array(builder, values)
numba.cgutils.pointer_add(builder, ptr, offset, return_type=None)

Add an integral offset to pointer ptr, and return a pointer of return_type (or, if omitted, the same type as ptr).

Note the computation is done in bytes, and ignores the width of the pointed item type.

numba.cgutils.printf(builder, format_string, *values)
numba.cgutils.set_branch_weight(builder, brinst, trueweight, falseweight)
numba.cgutils.set_record_data(builder, record, buf)
numba.cgutils.terminate(builder, bbend)
numba.cgutils.unpack_tuple(builder, tup, count)

numba.compiler module

class numba.compiler.CompileResult

Bases: tuple

CompileResult(typing_context, target_context, entry_point, typing_error, type_annotation, llvm_module, llvm_func, signature, objectmode, lifted, fndesc, interpmode)

entry_point

Alias for field number 2

fndesc

Alias for field number 10

interpmode

Alias for field number 11

lifted

Alias for field number 9

llvm_func

Alias for field number 6

llvm_module

Alias for field number 5

objectmode

Alias for field number 8

signature

Alias for field number 7

target_context

Alias for field number 1

type_annotation

Alias for field number 4

typing_context

Alias for field number 0

typing_error

Alias for field number 3

exception numba.compiler.CompilerError

Bases: exceptions.Exception

class numba.compiler.Flags

Bases: numba.utils.ConfigOptions

OPTIONS = frozenset(['no_wraparound', 'force_pyobject', 'no_compile', 'enable_pyobject_looplift', 'boundcheck', 'enable_looplift', 'enable_pyobject'])
class numba.compiler.FunctionAttributes

Bases: tuple

FunctionAttributes(name, filename, lineno)

filename

Alias for field number 1

lineno

Alias for field number 2

name

Alias for field number 0

class numba.compiler.Pipeline(typingctx, targetctx, args, return_type, flags, locals)

Bases: object

Stores and manages states for the compiler pipeline

backend_nopython_mode()

Native mode compilation

backend_object_mode()

Object mode compilation

compile_bytecode(bc, lifted=(), func_attr=FunctionAttributes(name='<anonymous>', filename='<unknown>', lineno=0))
compile_extra(func)
compile_internal(bc, func_attr=FunctionAttributes(name='<anonymous>', filename='<unknown>', lineno=0))
extract_bytecode(func)

Extract bytecode from function

fallback_context(*args, **kwds)

Wraps code that would signal a fallback to object mode

frontend_looplift()

Loop lifting analysis and transformation

giveup_context(*args, **kwds)

Wraps code that would signal a fallback to interpreter mode

stage_analyze_bytecode()

Analyze bytecode and translating to Numba IR

stage_annotate_type()

Create type annotation after type inference

stage_compile_interp_mode()

Just create a compile result for interpreter mode

stage_nopython_backend()

Do lowering for nopython

stage_nopython_frontend()

Type inference and legalization

stage_objectmode_backend()

Lowering for object mode

stage_objectmode_frontend()

Front-end: Analyze bytecode, generate Numba IR, infer types

numba.compiler.compile_bytecode(typingctx, targetctx, bc, args, return_type, flags, locals, lifted=(), func_attr=FunctionAttributes(name='<anonymous>', filename='<unknown>', lineno=0))
numba.compiler.compile_extra(typingctx, targetctx, func, args, return_type, flags, locals)
  • return_type

    Use None to indicate

numba.compiler.compile_internal(typingctx, targetctx, func, args, return_type, locals={})
numba.compiler.compile_isolated(func, args, return_type=None, flags=Flags(), locals={})

Compile the function is an isolated environment. Good for testing.

numba.compiler.compile_result(**kws)
numba.compiler.get_function_attributes(func)

Extract the function attributes from a Python function or object with py_func attribute, such as CPUOverloaded.

Returns an instance of FunctionAttributes.

numba.compiler.ir_optimize_for_py_stage(interp)

This passes breaks semantic for the type inferer but they reduces refct calls for object mode.

numba.compiler.legalize_given_types(args, return_type)
numba.compiler.legalize_return_type(return_type, interp, targetctx)

Only accept array return type iff it is passed into the function. Reject function object return types if in nopython mode.

numba.compiler.native_lowering_stage(targetctx, interp, typemap, restype, calltypes, nocompile)
numba.compiler.py_lowering_stage(targetctx, interp, nocompile)
numba.compiler.translate_stage(bytecode)
numba.compiler.type_inference_stage(typingctx, interp, args, return_type, locals={})

numba.config module

exception numba.config.NumbaWarning

Bases: exceptions.Warning

numba.controlflow module

class numba.controlflow.CFBlock(offset)

Bases: object

class numba.controlflow.CFGraph

Bases: object

Generic (almost) implementation of a Control Flow Graph.

add_edge(src, dest, data=None)

Add an edge from node src to node dest, with optional per-edge data. If such an edge already exists, it is replaced (duplicate edges are not possible).

add_node(node)

Add node to the graph. This is necessary before adding any edges from/to the node. node can be any hashable object.

backbone()

Return the set of nodes constituting the graph’s backbone. (i.e. the nodes that every path starting from the entry point

must go through). By construction, it is non-empty: it contains at least the entry point.
dead_nodes()

Return the set of dead nodes (eliminated from the graph).

descendents(node)

Return the set of descendents of the given node, in topological order (ignoring back edges).

dominators()

Return a dictionary of {node -> set(nodes)} mapping each node to the nodes dominating it.

A node D dominates a node N when any path leading to N must go through D.

dump(file=None)

Dump extensive debug information.

exit_points()

Return the computed set of exit nodes (may be empty).

in_loops(node)

Return the list of Loop objects the node belongs to, from innermost to outermost.

loops()

Return a dictionary of {node -> loop} mapping each loop header to the loop (a Loop instance) starting with it.

nodes()

Return the set of live nodes.

post_dominators()

Return a dictionary of {node -> set(nodes)} mapping each node to the nodes post-dominating it.

A node P post-dominates a node N when any path starting from N must go through P.

predecessors(dest)

Yield (node, data) pairs representing the predecessors of node dest. (data will be None if no data was specified when adding the edge)

process()

Compute various properties of the control flow graph. The graph must have been fully populated, and its entry point specified.

set_entry_point(node)

Set the entry point of the graph to node.

successors(src)

Yield (node, data) pairs representing the successors of node src. (data will be None if no data was specified when adding the edge)

topo_order()

Return the sequence of nodes in topological order (ignoring back edges).

topo_sort(nodes, reverse=False)

Iterate over the nodes in topological order (ignoring back edges). The sort isn’t guaranteed to be stable.

class numba.controlflow.ControlFlowAnalysis(bytecode)

Bases: object

  • bytecode

  • blocks

  • blockseq

  • doms: dict of set

    Dominators

  • backbone: set of block offsets

    The set of block that is common to all possible code path.

dump(file=None)
incoming_blocks(block)

Yield (incoming block, number of stack pops) pairs for block.

iterblocks()

Return all blocks in sequence of occurrence

iterliveblocks()

Return all live blocks in sequence of occurrence

jump(target, pops=0)

Register a jump (conditional or not) to target offset. pops is the number of stack pops implied by the jump (default 0).

op_BREAK_LOOP(inst)
op_FOR_ITER(inst)
op_JUMP_ABSOLUTE(inst)
op_JUMP_FORWARD(inst)
op_JUMP_IF_FALSE(inst)
op_JUMP_IF_FALSE_OR_POP(inst)
op_JUMP_IF_TRUE(inst)
op_JUMP_IF_TRUE_OR_POP(inst)
op_POP_BLOCK(inst)
op_POP_JUMP_IF_FALSE(inst)
op_POP_JUMP_IF_TRUE(inst)
op_RAISE_VARARGS(inst)
op_RETURN_VALUE(inst)
op_SETUP_LOOP(inst)
run()
class numba.controlflow.Loop

Bases: numba.controlflow.Loop

A control flow loop, as detected by a CFGraph object.

numba.ctypes_support module

This file fixes portability issues for ctypes

numba.ctypes_utils module

Alias to numba.typing.ctypes_utils for backward compatibility

numba.dataflow module

class numba.dataflow.BlockInfo(offset, incoming_blocks)

Bases: object

append(inst, **kws)
dump()
make_incoming()

Create an incoming variable (due to not enough values being available on our stack) and request its assignment from our incoming blocks’ own stacks.

make_temp(prefix='')
pop(discard=False)

Pop a variable from the stack, or request it from incoming blocks if the stack is empty. If discard is true, the variable isn’t meant to be used anymore, which allows reducing the number of temporaries created.

push(val)
request_outgoing(outgoing_block, phiname, stack_index)

Request the assignment of the next available stack variable for block outgoing_block with target name phiname.

terminator
tos
class numba.dataflow.DataFlowAnalysis(cfa)

Bases: object

Perform stack2reg

This is necessary to resolve blocks that propagates stack value. This would allow the use of and and or and python2.6 jumps.

add_syntax_block(info, block)

Add an inner syntax block.

dispatch(info, inst)
dump()
dup_topx(info, inst, count)
op_BINARY_ADD(info, inst)
op_BINARY_AND(info, inst)
op_BINARY_DIVIDE(info, inst)
op_BINARY_FLOOR_DIVIDE(info, inst)
op_BINARY_LSHIFT(info, inst)
op_BINARY_MODULO(info, inst)
op_BINARY_MULTIPLY(info, inst)
op_BINARY_OR(info, inst)
op_BINARY_POWER(info, inst)
op_BINARY_RSHIFT(info, inst)
op_BINARY_SUBSCR(info, inst)
op_BINARY_SUBTRACT(info, inst)
op_BINARY_TRUE_DIVIDE(info, inst)
op_BINARY_XOR(info, inst)
op_BREAK_LOOP(info, inst)
op_BUILD_LIST(info, inst)
op_BUILD_MAP(info, inst)
op_BUILD_SET(info, inst)
op_BUILD_SLICE(info, inst)

slice(TOS1, TOS) or slice(TOS2, TOS1, TOS)

op_BUILD_TUPLE(info, inst)
op_CALL_FUNCTION(info, inst)
op_COMPARE_OP(info, inst)
op_DELETE_ATTR(info, inst)
op_DUP_TOP(info, inst)
op_DUP_TOPX(info, inst)
op_DUP_TOP_TWO(info, inst)
op_FOR_ITER(info, inst)
op_GET_ITER(info, inst)
op_INPLACE_ADD(info, inst)
op_INPLACE_AND(info, inst)
op_INPLACE_DIVIDE(info, inst)
op_INPLACE_FLOOR_DIVIDE(info, inst)
op_INPLACE_LSHIFT(info, inst)
op_INPLACE_MODULO(info, inst)
op_INPLACE_MULTIPLY(info, inst)
op_INPLACE_OR(info, inst)
op_INPLACE_POWER(info, inst)
op_INPLACE_RSHIFT(info, inst)
op_INPLACE_SUBTRACT(info, inst)
op_INPLACE_TRUE_DIVIDE(info, inst)
op_INPLACE_XOR(info, inst)
op_JUMP_ABSOLUTE(info, inst)
op_JUMP_FORWARD(info, inst)
op_JUMP_IF_FALSE(info, inst)
op_JUMP_IF_FALSE_OR_POP(info, inst)
op_JUMP_IF_TRUE(info, inst)
op_JUMP_IF_TRUE_OR_POP(info, inst)
op_LOAD_ATTR(info, inst)
op_LOAD_CONST(info, inst)
op_LOAD_DEREF(info, inst)
op_LOAD_FAST(info, inst)
op_LOAD_GLOBAL(info, inst)
op_POP_BLOCK(info, inst)
op_POP_JUMP_IF_FALSE(info, inst)
op_POP_JUMP_IF_TRUE(info, inst)
op_POP_TOP(info, inst)
op_PRINT_ITEM(info, inst)
op_PRINT_NEWLINE(info, inst)
op_RAISE_VARARGS(info, inst)
op_RETURN_VALUE(info, inst)
op_ROT_FOUR(info, inst)
op_ROT_THREE(info, inst)
op_ROT_TWO(info, inst)
op_SETUP_LOOP(info, inst)
op_SLICE_0(info, inst)

TOS = TOS[:]

op_SLICE_1(info, inst)

TOS = TOS1[TOS:]

op_SLICE_2(info, inst)

TOS = TOS1[:TOS]

op_SLICE_3(info, inst)

TOS = TOS2[TOS1:TOS]

op_STORE_ATTR(info, inst)
op_STORE_FAST(info, inst)
op_STORE_MAP(info, inst)
op_STORE_SLICE_0(info, inst)

TOS[:] = TOS1

op_STORE_SLICE_1(info, inst)

TOS1[TOS:] = TOS2

op_STORE_SLICE_2(info, inst)

TOS1[:TOS] = TOS2

op_STORE_SLICE_3(info, inst)

TOS2[TOS1:TOS] = TOS3

op_STORE_SUBSCR(info, inst)
op_UNARY_INVERT(info, inst)
op_UNARY_NEGATIVE(info, inst)
op_UNARY_NOT(info, inst)
op_UNARY_POSITIVE(info, inst)
op_UNPACK_SEQUENCE(info, inst)
pop_syntax_block(info)

Pop the innermost syntax block and revert its stack effect.

run()
run_on_block(blk)
class numba.dataflow.LoopBlock

Bases: object

stack_offset

numba.decorators module

Contains function decorators and target_registry

numba.decorators.autojit(*args, **kws)

Deprecated.

Use jit instead. Calls to jit internally.

numba.decorators.jit([signature_or_function[, locals={}[, target='cpu'[, **targetoptions]]]])

This function is used to compile a Python function into native code. It is designed to be used as a decorator for the function to be compiled, but it can also be called as a regular function.

signature_or_function: function or str
This argument takes either the function to be compiled, or the signature of the function to be compiled. If this function is used as a decorator, the function to be compiled is the decorated function. In that case, this argument should only be used to optionally specify the function signature. If this function is called like a regular function, and this argument is used to specify the function signature, this function will return another jit function object which can be called again with the function to be compiled as this argument.

argtypes: deprecated

restype: deprecated

locals: dict
Mapping of local variable names to Numba types. Used to override the types deduced by Numba’s type inference engine.
targets: str
Specifies the target platform to compile for. Valid targets are cpu, gpu, npyufunc, and cuda. Defaults to cpu.
targetoptions:
For a cpu target, valid options are:
nopython: bool
Set to True to disable the use of PyObjects and Python API calls. The default behavior is to allow the use of PyObjects and Python API. Default value is False.
forceobj: bool
Set to True to force the use of PyObjects for every value. Default value is False.
looplift: bool
Set to True to enable jitting loops in nopython mode while leaving surrounding code in object mode. This allows functions to allocate NumPy arrays and use Python objects, while the tight loops in the function can still be compiled in nopython mode. Any arrays that the tight loop uses should be created before the loop is entered. Default value is True.
wraparound: bool
Set to True to enable array indexing wraparound for negative indices, for a small performance penalty. Default value is True.

compiled function

The function can be used in the following ways:

  1. jit(signature, [target=’cpu’, [**targetoptions]]) -> jit(function)

    Equivalent to:

    d = dispatcher(function, targetoptions) d.compile(signature)

    Create a dispatcher object for a python function and default target-options. Then, compile the funciton with the given signature.

    Example:

    @jit(“void(int32, float32)”) def foo(x, y):

    return x + y

  2. jit(function) -> dispatcher

    Same as old autojit. Create a dispatcher function object that specialize at call site.

    Example:

    @jit def foo(x, y):

    return x + y

  3. jit([target=’cpu’, [**targetoptions]]) -> configured_jit(function)

    Same as old autojit and 2). But configure with target and default target-options.

    Example:

    @jit(target=’cpu’, nopython=True) def foo(x, y):

    return x + y

numba.decorators.njit(*args, **kws)

Equivalent to jit(nopython=True)

See documentation for jit function/decorator for full description.

numba.dispatcher module

class numba.dispatcher.LiftedLoop(bytecode, typingctx, targetctx, locals, flags)

Bases: numba.dispatcher._OverloadedBase

Implementation of the hidden dispatcher objects used for lifted loop (a lifted loop is really compiled as a separate function).

compile(sig)
class numba.dispatcher.Overloaded(py_func, locals={}, targetoptions={})

Bases: numba.dispatcher._OverloadedBase

Implementation of user-facing dispatcher objects (i.e. created using the @jit decorator). This is an abstract base class. Subclasses should define the targetdescr class attribute.

compile(sig, locals={}, **targetoptions)

numba.dummyarray module

class numba.dummyarray.Array(dims, itemsize)

Bases: object

A dummy numpy array-like object. Consider it an array without the actual data, but offset from the base data pointer.

dims: tuple of Dim
describing each dimension of the array
ndim: int
number of dimension
shape: tuple of int
size of each dimension
strides: tuple of int
stride of each dimension
itemsize: int
itemsize
extent: (start, end)
start and end offset containing the memory region
classmethod from_desc(offset, shape, strides, itemsize)
is_array = True
is_c_contig
is_f_contig
iter_contiguous_extent()

Generates extents

ravel(order='C')
reshape(*newshape, **kws)
class numba.dummyarray.Dim(start, stop, size, stride, single)

Bases: object

A single dimension of the array

start:
start offset
stop:
stop offset
size:
number of items
stride:
item stride
copy(start=None, stop=None, size=None, stride=None, single=None)
get_offset(idx)
is_contiguous(itemsize)
normalize(base)
single
size
start
stop
stride
class numba.dummyarray.Element(extent)

Bases: object

is_array = False
iter_contiguous_extent()
class numba.dummyarray.Extent

Bases: tuple

Extent(begin, end)

begin

Alias for field number 0

end

Alias for field number 1

numba.dummyarray.compute_index(indices, dims)
numba.dummyarray.is_element_indexing(item, ndim)
numba.dummyarray.iter_strides_c_contig(arr, shape=None)

yields the c-contigous strides

numba.dummyarray.iter_strides_f_contig(arr, shape=None)

yields the f-contigous strides

numba.errcode module

class numba.errcode.Enum(init=0)

Bases: object

get()

numba.findlib module

numba.findlib.find_file(pat, libdir=None)
numba.findlib.find_lib(libname, libdir=None, platform=None)
numba.findlib.get_lib_dir()

Anaconda specific

numba.interpreter module

class numba.interpreter.Assigner

Bases: object

This object keeps track of potential assignment simplifications inside a code block. For example $O.1 = x followed by y = $0.1 can be simplified into y = x, but it’s not possible anymore if we have x = z in-between those two instructions.

NOTE: this is not only an optimization, but is actually necessary due to certain limitations of Numba - such as only accepting the returning of an array passed as function argument.

assign(srcvar, destvar)

Assign srcvar to destvar. Return either srcvar or a possible simplified assignment source (earlier assigned to srcvar).

get_assignment_source(destname)

Get a possible assignment source (a ir.Var instance) to replace destname, otherwise None.

class numba.interpreter.Interpreter(bytecode)

Bases: object

A bytecode interpreter that builds up the IR.

block_constains_opname(offset, opname)
code_consts
code_freevars
code_locals
code_names
current_scope
dump(file=None)
get(name)

Get the variable (a Var instance) with the given name.

get_closure_value(index)

Get a value from the cell contained in this function’s closure.

get_global_value(name)

Get a global value from the func_global (first) or as a builtins (second). If both failed, return a ir.UNDEFINED.

get_used_globals()

Return a dictionary of global variables used by the bytecode.

init_first_block()
insert_block(offset, scope=None, loc=None)
interpret()
op_BINARY_ADD(inst, lhs, rhs, res)
op_BINARY_AND(inst, lhs, rhs, res)
op_BINARY_DIVIDE(inst, lhs, rhs, res)
op_BINARY_FLOOR_DIVIDE(inst, lhs, rhs, res)
op_BINARY_LSHIFT(inst, lhs, rhs, res)
op_BINARY_MODULO(inst, lhs, rhs, res)
op_BINARY_MULTIPLY(inst, lhs, rhs, res)
op_BINARY_OR(inst, lhs, rhs, res)
op_BINARY_POWER(inst, lhs, rhs, res)
op_BINARY_RSHIFT(inst, lhs, rhs, res)
op_BINARY_SUBSCR(inst, target, index, res)
op_BINARY_SUBTRACT(inst, lhs, rhs, res)
op_BINARY_TRUE_DIVIDE(inst, lhs, rhs, res)
op_BINARY_XOR(inst, lhs, rhs, res)
op_BREAK_LOOP(inst)
op_BUILD_LIST(inst, items, res)
op_BUILD_MAP(inst, size, res)
op_BUILD_SET(inst, items, res)
op_BUILD_SLICE(inst, start, stop, step, res, slicevar)
op_BUILD_TUPLE(inst, items, res)
op_CALL_FUNCTION(inst, func, args, kws, res)
op_COMPARE_OP(inst, lhs, rhs, res)
op_DELETE_ATTR(inst, target)
op_DUP_TOP(inst, orig, duped)
op_DUP_TOPX(inst, orig, duped)
op_DUP_TOP_TWO(inst, orig, duped)
op_FOR_ITER(inst, iterator, pair, indval, pred)

Assign new block other this instruction.

op_GET_ITER(inst, value, res)
op_INPLACE_ADD(inst, lhs, rhs, res)
op_INPLACE_AND(inst, lhs, rhs, res)
op_INPLACE_DIVIDE(inst, lhs, rhs, res)
op_INPLACE_FLOOR_DIVIDE(inst, lhs, rhs, res)
op_INPLACE_LSHIFT(inst, lhs, rhs, res)
op_INPLACE_MODULO(inst, lhs, rhs, res)
op_INPLACE_MULTIPLY(inst, lhs, rhs, res)
op_INPLACE_OR(inst, lhs, rhs, res)
op_INPLACE_POWER(inst, lhs, rhs, res)
op_INPLACE_RSHIFT(inst, lhs, rhs, res)
op_INPLACE_SUBTRACT(inst, lhs, rhs, res)
op_INPLACE_TRUE_DIVIDE(inst, lhs, rhs, res)
op_INPLACE_XOR(inst, lhs, rhs, res)
op_JUMP_ABSOLUTE(inst)
op_JUMP_FORWARD(inst)
op_JUMP_IF_FALSE(inst, pred)
op_JUMP_IF_FALSE_OR_POP(inst, pred)
op_JUMP_IF_TRUE(inst, pred)
op_JUMP_IF_TRUE_OR_POP(inst, pred)
op_LOAD_ATTR(inst, item, res)
op_LOAD_CONST(inst, res)
op_LOAD_DEREF(inst, res)
op_LOAD_FAST(inst, res)
op_LOAD_GLOBAL(inst, res)
op_POP_BLOCK(inst)
op_POP_JUMP_IF_FALSE(inst, pred)
op_POP_JUMP_IF_TRUE(inst, pred)
op_PRINT_ITEM(inst, item, printvar, res)
op_PRINT_NEWLINE(inst, printvar, res)
op_RAISE_VARARGS(inst, exc)
op_RETURN_VALUE(inst, retval, castval)
op_SETUP_LOOP(inst)
op_SLICE_0(inst, base, res, slicevar, indexvar, nonevar)
op_SLICE_1(inst, base, start, nonevar, res, slicevar, indexvar)
op_SLICE_2(inst, base, nonevar, stop, res, slicevar, indexvar)
op_SLICE_3(inst, base, start, stop, res, slicevar, indexvar)
op_STORE_ATTR(inst, target, value)
op_STORE_FAST(inst, value)
op_STORE_MAP(inst, dct, key, value)
op_STORE_SLICE_0(inst, base, value, slicevar, indexvar, nonevar)
op_STORE_SLICE_1(inst, base, start, nonevar, value, slicevar, indexvar)
op_STORE_SLICE_2(inst, base, nonevar, stop, value, slicevar, indexvar)
op_STORE_SLICE_3(inst, base, start, stop, value, slicevar, indexvar)
op_STORE_SUBSCR(inst, target, index, value)
op_UNARY_INVERT(inst, value, res)
op_UNARY_NEGATIVE(inst, value, res)
op_UNARY_NOT(inst, value, res)
op_UNARY_POSITIVE(inst, value, res)
op_UNPACK_SEQUENCE(inst, iterable, stores, tupleobj)
store(value, name, redefine=False)

Store value (a Var instance) into the variable named name (a str object).

numba.intrinsics module

Numba only functions

numba.intrinsics.array_ravel(arr)

Flatten a C/F array into a 1D array without enforcing the ordering of the each element.

arr: array

A flattened 1D array

numba.io_support module

numba.ir module

class numba.ir.Assign(value, target, loc)

Bases: numba.ir.Stmt

class numba.ir.Block(scope, loc)

Bases: object

A code block

append(inst)
dump(file=<open file '<stdout>', mode 'w' at 0x10028e150>)
insert_after(stmt, other)

Insert stmt after other.

insert_before_terminator(stmt)
is_terminated
prepend(inst)
remove(inst)
terminator
verify()
class numba.ir.Branch(cond, truebr, falsebr, loc)

Bases: numba.ir.Stmt

is_terminator = True
class numba.ir.Const(value, loc)

Bases: object

class numba.ir.Del(value, loc)

Bases: numba.ir.Stmt

class numba.ir.DelAttr(target, attr, loc)

Bases: numba.ir.Stmt

class numba.ir.Expr(op, loc, **kws)

Bases: numba.ir.Inst

An IR expression (an instruction which can only be part of a larger statement).

classmethod binop(fn, lhs, rhs, loc)
classmethod build_list(items, loc)
classmethod build_map(size, loc)
classmethod build_set(items, loc)
classmethod build_tuple(items, loc)
classmethod call(func, args, kws, loc)
classmethod cast(value, loc)

A node for implicit casting at the return statement

classmethod exhaust_iter(value, count, loc)
classmethod getattr(value, attr, loc)
classmethod getitem(value, index, loc)
classmethod getiter(value, loc)
classmethod inplace_binop(fn, lhs, rhs, loc)
classmethod iternext(value, loc)
list_vars()
classmethod pair_first(value, loc)
classmethod pair_second(value, loc)
classmethod static_getitem(value, index, loc)
classmethod unary(fn, value, loc)
class numba.ir.FreeVar(index, name, value, loc)

Bases: object

A freevar, as loaded by LOAD_DECREF. (i.e. a variable defined in an enclosing non-global scope)

class numba.ir.Global(name, value, loc)

Bases: object

class numba.ir.Inst

Bases: object

Base class for all IR instructions.

list_vars()

List the variables used (read or written) by the instruction.

class numba.ir.Intrinsic(name, type, args)

Bases: object

For inserting intrinsic node into the IR

class numba.ir.Jump(target, loc)

Bases: numba.ir.Stmt

is_terminator = True
class numba.ir.Loc(filename, line, col=None)

Bases: object

Source location

strformat()
class numba.ir.Loop(entry, exit)

Bases: object

entry
exit
exception numba.ir.NotDefinedError

Bases: exceptions.NameError

class numba.ir.Raise(exception, loc)

Bases: numba.ir.Stmt

is_terminator = True
exception numba.ir.RedefinedError

Bases: exceptions.NameError

class numba.ir.Return(value, loc)

Bases: numba.ir.Stmt

is_terminator = True
class numba.ir.Scope(parent, loc)

Bases: object

  • parent: Scope

    Parent scope

  • localvars: VarMap

    Scope-local variable map

  • loc: Loc

    Start of scope location

define(name, loc)

Define a variable

get(name)

Refer to a variable

get_or_define(name, loc)
has_parent
make_temp(loc)
redefine(name, loc)

Redefine if the name is already defined

class numba.ir.SetAttr(target, attr, value, loc)

Bases: numba.ir.Stmt

class numba.ir.SetItem(target, index, value, loc)

Bases: numba.ir.Stmt

class numba.ir.Stmt

Bases: numba.ir.Inst

Base class for IR statements (instructions which can appear on their own in a Block).

is_terminator = False
list_vars()
class numba.ir.StoreMap(dct, key, value, loc)

Bases: numba.ir.Stmt

class numba.ir.Var(scope, name, loc)

Bases: object

  • scope: Scope

  • name: str

  • loc: Loc

    Definition location

is_temp
class numba.ir.VarMap

Bases: object

define(name, var)
get(name)
exception numba.ir.VerificationError

Bases: exceptions.Exception

numba.irpasses module

Contains optimization passes for the IR.

class numba.irpasses.RemoveRedundantAssign(interp)

Bases: object

Turn assignment pairs into one assignment

mark_asssignment(tempassign, offset, inst)
run()
run_block(blk)

numba.looplifting module

class numba.looplifting.SubOffset(val, sub=1)

Bases: object

The loop-jitting may insert bytecode between two bytecode but we cannot guarantee that there is enough integral space between two offsets. This class workaround the problem by introducing a fractional part to the offset.

next()

Helper method to get the next suboffset by incrementing the fractional part only

numba.looplifting.discover_args_and_returns(bytecode, insts, outer_rds, outer_wrs)

Basic analysis for args and returns This completely ignores the ordering or the read-writes.

numba.looplifting.find_previous_inst(insts, offset)
numba.looplifting.find_varnames_uses(bytecode, insts)
numba.looplifting.insert_instruction(insts, item)
numba.looplifting.insert_loop_call(bytecode, loop, args, outer, outerlabels, returns, dispatcher_factory)
numba.looplifting.lift_loop(bytecode, dispatcher_factory)

Lift the top-level loops.

  • outer: ByteCode of a copy of the loop-less function.
  • loops: a list of ByteCode of the loops.
numba.looplifting.make_loop_bytecode(bytecode, loop, args, returns)
numba.looplifting.separate_loops(bytecode, outer, loops)

Separate top-level loops from the function

Stores loopless instructions from the original function into outer. Stores list of loop instructions into loops. Both outer and loops are list-like (append(item) defined).

numba.looplifting.stitch_instructions(outer, loop)

numba.lowering module

class numba.lowering.BaseLower(context, fndesc, interp)

Bases: object

Lower IR to LLVM

init()
init_argument(arg)
lower()
lower_block(block)
post_lower()

Called after all blocks are lowered

pre_lower()

Called before lowering all blocks.

typeof(varname)
class numba.lowering.ExternalFunctionDescriptor(name, restype, argtypes)

Bases: numba.lowering.FunctionDescriptor

A FunctionDescriptor subclass for opaque external functions (e.g. raw C functions).

exception numba.lowering.ForbiddenConstruct(msg, loc)

Bases: numba.lowering.LoweringError

class numba.lowering.FunctionDescriptor(native, modname, qualname, unique_name, doc, typemap, restype, calltypes, args, kws, mangler=None, argtypes=None)

Bases: object

args
argtypes
calltypes
doc
kws
lookup_module()

Return the module in which this function is supposed to exist. This may be a dummy module if the function was dynamically generated.

mangled_name
modname
native
qualname
restype
typemap
unique_name
class numba.lowering.Lower(context, fndesc, interp)

Bases: numba.lowering.BaseLower

alloca(name, type)
alloca_lltype(name, lltype)
getvar(name)
loadvar(name)
lower_assign(ty, inst)
lower_binop(resty, expr)
lower_expr(resty, expr)
lower_inst(inst)
storevar(value, name)
exception numba.lowering.LoweringError(msg, loc)

Bases: exceptions.Exception

class numba.lowering.PythonFunctionDescriptor(native, modname, qualname, unique_name, doc, typemap, restype, calltypes, args, kws, mangler=None, argtypes=None)

Bases: numba.lowering.FunctionDescriptor

classmethod from_object_mode_function(interp)

Build a FunctionDescriptor for a Python function to be compiled and executed in object mode.

classmethod from_specialized_function(interp, typemap, restype, calltypes, mangler)

Build a FunctionDescriptor for a specialized Python function.

numba.lowering.default_mangler(name, argtypes)

numba.macro module

Macro handling passes

Macros are expanded on block-by-block

class numba.macro.Macro(name, func, callable=False, argnames=None)

Bases: object

A macro object is expanded to a function call

argnames
callable
func
name
exception numba.macro.MacroError

Bases: exceptions.Exception

numba.macro.expand_macros(blocks)
numba.macro.expand_macros_in_block(constants, block)
numba.macro.module_getattr_folding(constants, block)

numba.npdatetime module

Helper functions for numpy.timedelta64 and numpy.datetime64. For now, multiples-of-units (for example timedeltas expressed in tens of seconds) are not supported.

numba.npdatetime.can_cast_timedelta_units(src, dest)
numba.npdatetime.combine_datetime_timedelta_units(datetime_unit, timedelta_unit)

Return the unit result of combining datetime_unit with timedelta_unit (e.g. by adding or subtracting). None is returned if combining those units is forbidden.

numba.npdatetime.get_best_unit(unit_a, unit_b)

Get the best (i.e. finer-grained) of two units.

numba.npdatetime.get_datetime_timedelta_conversion(datetime_unit, timedelta_unit)

Compute a possible conversion for combining datetime_unit and timedelta_unit (presumably for adding or subtracting). Return (result unit, integer datetime multiplier, integer timedelta multiplier). RuntimeError is raised if the combination is impossible.

numba.npdatetime.get_timedelta_conversion_factor(src_unit, dest_unit)

Return an integer multiplier allowing to convert from timedeltas of src_unit to dest_unit.

numba.numpy_support module

class numba.numpy_support.UFuncLoopSpec

Bases: numba.numpy_support._UFuncLoopSpec

An object describing a ufunc loop’s inner types. Properties: - inputs: the inputs’ Numba types - outputs: the outputs’ Numba types - numpy_inputs: the inputs’ Numpy dtypes - numpy_outputs: the outputs’ Numpy dtypes - ufunc_sig: the string representing the ufunc’s type signature, in

Numpy format (e.g. “ii->i”)
numpy_inputs
numpy_outputs
numba.numpy_support.as_dtype(nbtype)

Return a numpy dtype instance corresponding to the given Numba type. NotImplementedError is if no correspondence is known.

numba.numpy_support.from_dtype(dtype)

Return a Numba Type instance corresponding to the given Numpy dtype. NotImplementedError is raised on unsupported Numpy dtypes.

numba.numpy_support.from_struct_dtype(dtype)
numba.numpy_support.is_array(val)
numba.numpy_support.is_arrayscalar(val)
numba.numpy_support.map_arrayscalar_type(val)
numba.numpy_support.map_layout(val)
numba.numpy_support.supported_ufunc_loop(ufunc, loop)

Return whether the loop for the ufunc is supported -in nopython-.

loop should be a UFuncLoopSpec instance, and ufunc a numpy ufunc.

For ufuncs implemented using the ufunc_db, it is supported if the ufunc_db contains a lowering definition for ‘loop’ in the ‘ufunc’ entry.

For other ufuncs, it is type based. The loop will be considered valid if it only contains the following letter types: ‘?bBhHiIlLqQfd’. Note this is legacy and when implementing new ufuncs the ufunc_db should be preferred, as it allows for a more fine-grained incremental support.

numba.numpy_support.ufunc_find_matching_loop(ufunc, arg_types)

Find the appropriate loop to be used for a ufunc based on the types of the operands

ufunc - The ufunc we want to check arg_types - The tuple of arguments to the ufunc, including any

explicit output(s).
return value - A UFuncLoopSpec identifying the loop, or None
if no matching loop is found.

numba.objmode module

Lowering implementation for object mode.

class numba.objmode.PyLower(context, fndesc, interp)

Bases: numba.lowering.BaseLower

alloca(name, ltype=None)

Allocate a stack slot and initialize it to NULL. The default is to allocate a pyobject pointer. Use ltype to override.

builtin_lookup(mod, name)
mod:
The __builtins__ dictionary or module, as looked up in a module’s globals.
name: str
The object to lookup
check_error(obj)
check_int_status(num, ok_value=0)

Raise an exception if num is smaller than ok_value.

check_occurred()
cleanup()
decref(value)

This is allow to be called on non pyobject pointer, in which case no code is inserted.

delvar(name)

Delete the variable slot with the given name. This will decref the corresponding Python object.

get_builtin_obj(name)
get_env_const(index)

Look up constant number index inside the environment body. A borrowed reference is returned.

get_module_dict()
incref(value)
init()
init_argument(arg)
is_null(obj)
loadvar(name)

Load the llvm value of the variable named name.

lower_assign(inst)

The returned object must have a new reference

lower_binop(expr, inplace=False)
lower_const(const)
lower_expr(expr)
lower_global(name, value)
  1. Check global scope dictionary.

  2. Check __builtins__.

    2a) is it a dictionary (for non __main__ module) 2b) is it a module (for __main__ module)

lower_inst(inst)
post_lower()
pre_lower()
return_error_occurred()
return_exception_raised()
storevar(value, name)

Stores a llvm value and allocate stack slot if necessary. The llvm value can be of arbitrary type.

numba.pythonapi module

exception numba.pythonapi.NativeError

Bases: exceptions.RuntimeError

class numba.pythonapi.PythonAPI(context, builder)

Bases: object

Code generation facilities to call into the CPython C API (and related helpers).

alloca_obj()
bool_from_bool(bval)

Get a Python bool from a LLVM boolean.

bool_from_long(ival)
borrow_none()
bytes_from_string_and_size(string, size)
call(callee, args, kws)
call_function_objargs(callee, objargs)
complex_adaptor(cobj, cmplx)
complex_from_doubles(realval, imagval)
complex_imag_as_double(cobj)
complex_real_as_double(cobj)
create_np_datetime(val, unit_code)
create_np_timedelta(val, unit_code)
decref(obj)
dict_getitem_string(dic, name)

Returns a borrowed reference

dict_new(presize=0)
dict_pack(keyvalues)

keyvalues: iterable of (str, llvm.Value of PyObject*)

dict_setitem(dictobj, nameobj, valobj)
dict_setitem_string(dictobj, name, valobj)
err_clear()
err_occurred()
err_set_object(exctype, excval)
err_set_string(exctype, msg)
extract_np_datetime(obj)
extract_np_timedelta(obj)
extract_record_data(obj, pbuf)
float_as_double(fobj)
float_from_double(fval)
from_native_array(typ, ary)
from_native_return(val, typ)
from_native_value(val, typ)
from_tuple(typ, val)
get_c_object(name)

Get a Python object through its C-accessible name. (e.g. “PyExc_ValueError”).

get_null_object()
gil_ensure()

Ensure the GIL is acquired. The returned value must be consumed by gil_release().

gil_release(gil)

Release the acquired GIL by gil_ensure(). Must be pair with a gil_ensure().

import_module_noblock(modname)
incref(obj)
iter_next(iterobj)
list_getitem(lst, idx)

Returns a borrowed reference.

list_new(szval)
list_pack(items)
list_setitem(seq, idx, val)

Warning: Steals reference to val

long_as_longlong(numobj)
long_as_ulonglong(numobj)
long_from_long(ival)
long_from_longlong(ival)
long_from_ssize_t(ival)
long_from_ulonglong(ival)
make_none()
native_error_type
numba_array_adaptor(ary, ptr)
number_add(lhs, rhs, inplace=False)
number_and(lhs, rhs, inplace=False)
number_as_ssize_t(numobj)
number_divide(lhs, rhs, inplace=False)
number_float(val)
number_floordivide(lhs, rhs, inplace=False)
number_invert(obj)
number_long(numobj)
number_lshift(lhs, rhs, inplace=False)
number_multiply(lhs, rhs, inplace=False)
number_negative(obj)
number_or(lhs, rhs, inplace=False)
number_positive(obj)
number_power(lhs, rhs, inplace=False)
number_remainder(lhs, rhs, inplace=False)
number_rshift(lhs, rhs, inplace=False)
number_subtract(lhs, rhs, inplace=False)
number_truedivide(lhs, rhs, inplace=False)
number_xor(lhs, rhs, inplace=False)
object_delattr_string(obj, attr)
object_dump(obj)

Dump a Python object on C stderr. For debugging purposes.

object_getattr_string(obj, attr)
object_getitem(obj, key)
object_getiter(obj)
object_istrue(obj)
object_not(obj)
object_richcompare(lhs, rhs, opstr)

Refer to Python source Include/object.h for macros definition of the opid.

object_setattr_string(obj, attr, val)
object_setitem(obj, key, val)
object_str(obj)
parse_tuple(args, fmt, *objs)
parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)
print_object(obj)
print_string(text)
raise_exception(exctype, excval)
raise_missing_global_error(name)
raise_missing_name_error(name)
raise_native_error(msg)
recreate_record(pdata, size, dtypeaddr)
release_record_buffer(pbuf)
return_none()
sequence_getslice(obj, start, stop)
sequence_tuple(obj)
set_add(set, value)
set_new(iterable=None)
string_as_string(strobj)
string_from_constant_string(string)
string_from_string_and_size(string, size)
sys_write_stdout(fmt, *args)
to_native_arg(obj, typ)
to_native_array(typ, ary)
to_native_value(obj, typ)
tuple_getitem(tup, idx)

Borrow reference

tuple_new(count)
tuple_pack(items)
tuple_setitem(tuple_val, index, item)

Steals a reference to item.

tuple_size(tup)
numba.pythonapi.fix_python_api()

Execute once to install special symbols into the LLVM symbol table

numba.serialize module

Serialization support for compiled functions.

numba.sigutils module

numba.sigutils.is_signature(sig)
numba.sigutils.normalize_signature(sig)
numba.sigutils.parse_signature(signature_str)

numba.six module

Utilities for writing code that runs on Python 2 and 3

class numba.six.Iterator

Bases: object

next()
class numba.six.Module_six_moves_urllib

Bases: module

Create a six.moves.urllib namespace that resembles the Python 3 namespace

error = <module 'numba.six.moves.urllib.error' (built-in)>
parse = <module 'numba.six.moves.urllib_parse' (built-in)>
request = <module 'numba.six.moves.urllib.request' (built-in)>
response = <module 'numba.six.moves.urllib.response' (built-in)>
robotparser = <module 'numba.six.moves.urllib.robotparser' (built-in)>
class numba.six.Module_six_moves_urllib_error(name)

Bases: numba.six._LazyModule

Lazy loading of moved objects in six.moves.urllib_error

class numba.six.Module_six_moves_urllib_parse(name)

Bases: numba.six._LazyModule

Lazy loading of moved objects in six.moves.urllib_parse

class numba.six.Module_six_moves_urllib_request(name)

Bases: numba.six._LazyModule

Lazy loading of moved objects in six.moves.urllib_request

class numba.six.Module_six_moves_urllib_response(name)

Bases: numba.six._LazyModule

Lazy loading of moved objects in six.moves.urllib_response

class numba.six.Module_six_moves_urllib_robotparser(name)

Bases: numba.six._LazyModule

Lazy loading of moved objects in six.moves.urllib_robotparser

class numba.six.MovedAttribute(name, old_mod, new_mod, old_attr=None, new_attr=None)

Bases: numba.six._LazyDescr

class numba.six.MovedModule(name, old, new=None)

Bases: numba.six._LazyDescr

numba.six.add_metaclass(metaclass)

Class decorator for creating a class with a metaclass.

numba.six.add_move(move)

Add an item to six.moves.

numba.six.b(s)

Byte literal

numba.six.byte2int(bs)
numba.six.create_bound_method(func, obj)
numba.six.exec_(_code_, _globs_=None, _locs_=None)

Execute code in a namespace.

numba.six.get_unbound_function(unbound)

Get the function out of a possibly unbound function

numba.six.indexbytes(buf, i)
numba.six.iterbytes(buf)
numba.six.iteritems(d, **kw)

Return an iterator over the (key, value) pairs of a dictionary.

numba.six.iterkeys(d, **kw)

Return an iterator over the keys of a dictionary.

numba.six.iterlists(d, **kw)

Return an iterator over the (key, [values]) pairs of a dictionary.

numba.six.itervalues(d, **kw)

Return an iterator over the values of a dictionary.

numba.six.remove_move(name)

Remove item from six.moves.

numba.six.reraise(tp, value, tb=None)

Reraise an exception.

numba.six.u(s)

Text literal

numba.six.with_metaclass(meta, *bases)

Create a base class with a metaclass.

numba.six.wraps(wrapped, assigned=('__module__', '__name__', '__doc__'), updated=('__dict__', ))

numba.special module

numba.special.typeof(val)

Get the type of a variable or value.

Used outside of Numba code, infers the type for the object.

numba.testing module

numba.testing.allow_interpreter_mode(fn)

Temporarily re-enable intepreter mode

numba.testing.discover_tests(startdir)

Discover test under a directory

numba.testing.run_tests(suite, xmloutput=None, verbosity=1)
  • suite [TestSuite]

    A suite of all tests to run

  • xmloutput [str or None]

    Path of XML output directory (optional)

  • verbosity [int]

    Verbosity level of tests output

Returns the TestResult object after running the test suite.

numba.testing.test(**kwargs)

Run all tests under numba.tests.

  • descriptions

  • verbosity

  • buffer

  • failfast

  • xmloutput [str]

    Path of XML output directory

numba.type_annotations module

class numba.type_annotations.SourceLines(func)

Bases: _abcoll.Mapping

avail
class numba.type_annotations.TypeAnnotation(interp, typemap, calltypes, lifted)

Bases: object

annotate()

numba.typeinfer module

Type inference base on CPA. The algorithm guarantees monotonic growth of type-sets for each variable.

Steps:
  1. seed initial types
  2. build constrains
  3. propagate constrains
  4. unify types

Constrain propagation is precise and does not regret (no backtracing). Constrains push types forward following the dataflow.

class numba.typeinfer.BuildTupleConstrain(target, items, loc)

Bases: object

class numba.typeinfer.CallConstrain(target, func, args, kws, loc)

Bases: object

Constrain for calling functions. Perform case analysis foreach combinations of argument types.

resolve(context, typevars, fnty)
class numba.typeinfer.ConstrainNetwork

Bases: object

TODO: It is possible to optimize constrain propagation to consider only
dirty type variables.
append(constrain)
propagate(context, typevars)
class numba.typeinfer.ExhaustIterConstrain(target, count, iterator, loc)

Bases: object

class numba.typeinfer.GetAttrConstrain(target, attr, value, loc, inst)

Bases: object

class numba.typeinfer.IntrinsicCallConstrain(target, func, args, kws, loc)

Bases: numba.typeinfer.CallConstrain

class numba.typeinfer.PairFirstConstrain(target, pair, loc)

Bases: object

class numba.typeinfer.PairSecondConstrain(target, pair, loc)

Bases: object

class numba.typeinfer.Propagate(dst, src, loc)

Bases: object

A simple constrain for direct propagation of types for assignments.

class numba.typeinfer.SetAttrConstrain(target, attr, value, loc)

Bases: object

class numba.typeinfer.SetItemConstrain(target, index, value, loc)

Bases: object

class numba.typeinfer.StaticGetItemConstrain(target, value, index, loc)

Bases: object

class numba.typeinfer.TypeInferer(context, blocks)

Bases: object

Operates on block that shares the same ir.Scope.

build_constrain()
constrain_statement(inst)
dump()
get_function_types(typemap)
get_return_type(typemap)
get_state_token()

The algorithm is monotonic. It can only grow the typesets. The sum of all lengths of type sets is a cheap and accurate description of our progress.

propagate()
resolve_value_type(inst, val)

Resolve the type of a simple Python value, such as can be represented by literals.

seed_return(typ)

Seeding of return value is optional.

seed_type(name, typ)

All arguments should be seeded.

sentry_modified_builtin(inst, gvar)

Ensure that builtins are modified.

typeof_assign(inst)
typeof_call(inst, target, call)
typeof_const(inst, target, const)
typeof_expr(inst, target, expr)
typeof_global(inst, target, gvar)
typeof_intrinsic_call(inst, target, func, *args)
typeof_setattr(inst)
typeof_setitem(inst)
unify()
class numba.typeinfer.TypeVar(context, var)

Bases: object

add_types(*types)
get()
getone()
lock(typ)
union(other)
class numba.typeinfer.TypeVarMap

Bases: dict

set_context(context)
exception numba.typeinfer.TypingError(msg, loc=None)

Bases: exceptions.Exception

numba.types module

These type objects do not have a fixed machine representation. It is up to the targets to choose their representation.

numba.types.optional

alias of Optional

numba.unittest_support module

This file fixes portability issues for unittest

numba.utils module

class numba.utils.BenchmarkResult(func, records, loop)

Bases: object

class numba.utils.ConfigOptions

Bases: object

OPTIONS = ()
copy()
set(name)
unset(name)
class numba.utils.SortedMap(seq)

Bases: _abcoll.Mapping

Immutable

class numba.utils.SortedSet(seq)

Bases: _abcoll.Set

class numba.utils.UniqueDict

Bases: dict

numba.utils.benchmark(func, maxsec=1)
numba.utils.bit_length(intval)

Return the number of bits necessary to represent integer intval.

class numba.utils.cached_property(func, name=None)

Bases: object

Decorator that converts a method with a single self argument into a property cached on the instance.

Optional name argument allows you to make cached properties of other methods. (e.g. url = cached_property(get_absolute_url, name=’url’) )

class numba.utils.finalize(obj, func, *args, **kwargs)

Class for finalization of weakrefable objects

finalize(obj, func, *args, **kwargs) returns a callable finalizer object which will be called when obj is garbage collected. The first time the finalizer is called it evaluates func(*arg, **kwargs) and returns the result. After this the finalizer is dead, and calling it just returns None.

When the program exits any remaining finalizers for which the atexit attribute is true will be run in reverse order of creation. By default atexit is true.

alive

Whether finalizer is alive

atexit

Whether finalizer should be called at exit

detach()

If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None

peek()

If alive then return (obj, func, args, kwargs); otherwise return None

numba.utils.format_time(tm)
numba.utils.runonce(fn)
numba.utils.shutting_down(globals=<built-in function globals>)

Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared.

numba.utils.total_ordering(cls)

Class decorator that fills in missing ordering methods

Module contents

Expose top-level symbols that are safe for import *

numba.jit([signature_or_function[, locals={}[, target='cpu'[, **targetoptions]]]])

This function is used to compile a Python function into native code. It is designed to be used as a decorator for the function to be compiled, but it can also be called as a regular function.

signature_or_function: function or str
This argument takes either the function to be compiled, or the signature of the function to be compiled. If this function is used as a decorator, the function to be compiled is the decorated function. In that case, this argument should only be used to optionally specify the function signature. If this function is called like a regular function, and this argument is used to specify the function signature, this function will return another jit function object which can be called again with the function to be compiled as this argument.

argtypes: deprecated

restype: deprecated

locals: dict
Mapping of local variable names to Numba types. Used to override the types deduced by Numba’s type inference engine.
targets: str
Specifies the target platform to compile for. Valid targets are cpu, gpu, npyufunc, and cuda. Defaults to cpu.
targetoptions:
For a cpu target, valid options are:
nopython: bool
Set to True to disable the use of PyObjects and Python API calls. The default behavior is to allow the use of PyObjects and Python API. Default value is False.
forceobj: bool
Set to True to force the use of PyObjects for every value. Default value is False.
looplift: bool
Set to True to enable jitting loops in nopython mode while leaving surrounding code in object mode. This allows functions to allocate NumPy arrays and use Python objects, while the tight loops in the function can still be compiled in nopython mode. Any arrays that the tight loop uses should be created before the loop is entered. Default value is True.
wraparound: bool
Set to True to enable array indexing wraparound for negative indices, for a small performance penalty. Default value is True.

compiled function

The function can be used in the following ways:

  1. jit(signature, [target=’cpu’, [**targetoptions]]) -> jit(function)

    Equivalent to:

    d = dispatcher(function, targetoptions) d.compile(signature)

    Create a dispatcher object for a python function and default target-options. Then, compile the funciton with the given signature.

    Example:

    @jit(“void(int32, float32)”) def foo(x, y):

    return x + y

  2. jit(function) -> dispatcher

    Same as old autojit. Create a dispatcher function object that specialize at call site.

    Example:

    @jit def foo(x, y):

    return x + y

  3. jit([target=’cpu’, [**targetoptions]]) -> configured_jit(function)

    Same as old autojit and 2). But configure with target and default target-options.

    Example:

    @jit(target=’cpu’, nopython=True) def foo(x, y):

    return x + y

numba.autojit(*args, **kws)

Deprecated.

Use jit instead. Calls to jit internally.

numba.njit(*args, **kws)

Equivalent to jit(nopython=True)

See documentation for jit function/decorator for full description.

numba.vectorize(ftylist[, target='cpu'[, **kws]])

A decorator to create numpy ufunc object from Numba compiled code.

ftylist: iterable
An iterable of type signatures, which are either function type object or a string describing the function type.
target: str
A string for code generation target. Default to “cpu”.

A NumPy universal function

@vectorize([‘float32(float32, float32)’,
‘float64(float64, float64)’])
def sum(a, b):
return a + b
numba.guvectorize(ftylist, signature[, target='cpu'[, **kws]])

A decorator to create numpy generialized-ufunc object from Numba compiled code.

ftylist: iterable
An iterable of type signatures, which are either function type object or a string describing the function type.
signature: str
A NumPy generialized-ufunc signature. e.g. “(m, n), (n, p)->(m, p)”
target: str
A string for code generation target. Defaults to “cpu”.

A NumPy generialized universal-function

@guvectorize([‘void(int32[:,:], int32[:,:], int32[:,:])’,
‘void(float32[:,:], float32[:,:], float32[:,:])’], ‘(x, y),(x, y)->(x, y)’)
def add_2d_array(a, b):
for i in range(c.shape[0]):
for j in range(c.shape[1]):
c[i, j] = a[i, j] + b[i, j]
numba.export(prototype)
numba.exportmany(prototypes)
numba.from_dtype(dtype)

Return a Numba Type instance corresponding to the given Numpy dtype. NotImplementedError is raised on unsupported Numpy dtypes.

numba.optional

alias of Optional

numba.typeof(val)

Get the type of a variable or value.

Used outside of Numba code, infers the type for the object.