Basic functionality used in the fastai library
-
def ifnone(a, b)bifais None elsea -
def maybe_attr(o, attr)getattr(o,attr,o) -
def basic_repr(flds)Minimal__repr__ -
def is_array(x)Trueifxsupports__array__oriloc -
def listify(o, *rest)Convertoto alist -
def tuplify(o, use_list, match)Makeoa tuple -
def true(x)Test whetherxis truthy; collections with >0 elements are consideredTrue -
class NullTypeAn object that isFalseand can be called, chained, and indexeddef __getattr__(self, *args)def __call__(self, *args, **kwargs)def __getitem__(self, *args)def __bool__(self)
-
def tonull(x)ConvertNonetonull -
def get_class(nm, *fld_names, **flds)Dynamically create a class, optionally inheriting fromsup, containingfld_names -
def mk_class(nm, *fld_names, **flds)Create a class usingget_classand add to the caller's module -
def wrap_class(nm, *fld_names, **flds)Decorator: makes function a method of a new classnmpassing parameters tomk_class -
class ignore_exceptionsContext manager to ignore exceptionsdef __enter__(self)def __exit__(self, *args)
-
def exec_local(code, var_name)Callexeconcodeand return the varvar_name -
def risinstance(types, obj)Curriedisinstancebut with args reversed -
class InfInfinite lists -
def in_(x, a)Trueifx in a -
def ret_true(*args, **kwargs)Predicate: alwaysTrue -
def ret_false(*args, **kwargs)Predicate: alwaysFalse -
def stop(e)Raises exceptione(by defaultStopIteration) -
def gen(func, seq, cond)Like(func(o) for o in seq if cond(func(o)))but handlesStopIteration -
def chunked(it, chunk_sz, drop_last, n_chunks)Return batches from iteratoritof sizechunk_sz(or returnn_chunkstotal) -
def otherwise(x, tst, y)y if tst(x) else x -
def custom_dir(c, add)Implement custom__dir__, addingaddtocls -
class AttrDictdictsubclass that also provides access to keys as attrsdef __getattr__(self, k)def __setattr__(self, k, v)def __dir__(self)def copy(self)
-
class AttrDictDefaultAttrDictsubclass that returnsNonefor missing attrsdef __init__(self, *args, **kwargs)def __getattr__(self, k)
-
class NSSimpleNamespacesubclass that also addsiteranddictsupportdef __iter__(self)def __getitem__(self, x)def __setitem__(self, x, y)
-
def get_annotations_ex(obj)Backport of py3.10get_annotationsthat returns globals/locals -
def eval_type(t, glb, loc)evala type or collection of types, if needed, for annotations in py3.10+ -
def type_hints(f)Liketyping.get_type_hintsbut returns{}if not allowed type -
def annotations(o)Annotations foro, ortype(o) -
def anno_ret(func)Get the return annotation offunc -
def signature_ex(obj, eval_str)Backport ofinspect.signature(..., eval_str=Trueto <py310 -
def argnames(f, frame)Names of arguments to function or framef -
def with_cast(f)Decorator which uses any parameter annotations as preprocessing functions -
def store_attr(names, self, but, cast, store_args, **attrs)Store params named in comma-separatednamesfrom calling context into attrs inself -
def attrdict(o, *ks)Dict from eachkinkstogetattr(o,k) -
def properties(cls, *ps)Change attrs inclswith names inpsto properties -
def camel2words(s, space)Convert CamelCase to 'spaced words' -
def camel2snake(name)Convert CamelCase to snake_case -
def snake2camel(s)Convert snake_case to CamelCase -
def class2attr(self, cls_name)Return the snake-cased name of the class; strip endingcls_nameif it exists. -
def getcallable(o, attr)Callsgetattrwith a default ofnoop -
def getattrs(o, *attrs)List of allattrsino -
def hasattrs(o, attrs)Test whetherocontains allattrs -
def try_attrs(obj, *attrs)Return first attr that exists inobj -
class GetAttrBaseBasic delegation of__getattr__and__dir__def __getattr__(self, k)def __dir__(self)
-
class GetAttrInherit from this to have all attr accesses inself._xtrapassed down toself.defaultdef __getattr__(self, k)def __dir__(self)def __setstate__(self, data)
-
def delegate_attr(self, k, to)Use in__getattr__to delegate to attrtowithout inheriting fromGetAttr -
class ShowPrintBase class that prints forshowdef show(self, *args, **kwargs)
-
class IntAn extensibleint -
class StrAn extensiblestr -
class FloatAn extensiblefloat -
def partition(coll, f)Partition a collection by a predicate -
def flatten(o)Concatenate all collections and items as a generator -
def concat(colls)Concatenate all collections and items as a list -
def strcat(its, sep)Concatenate stringified itemsits -
def detuplify(x)Ifxis a tuple with one thing, extract it -
def replicate(item, match)Create tuple ofitemcopiedlen(match)times -
def setify(o)Turn any list like-object into a set. -
def merge(*ds)Merge all dictionaries inds -
def range_of(x)All indices of collectionx(i.e.list(range(len(x)))) -
def groupby(x, key, val)Likeitertools.groupbybut doesn't need to be sorted, and isn't lazy, plus some extensions -
def last_index(x, o)Finds the last index of occurence ofxino(returns -1 if no occurence) -
def filter_dict(d, func)Filter adictusingfunc, applied to keys and values -
def filter_keys(d, func)Filter adictusingfunc, applied to keys -
def filter_values(d, func)Filter adictusingfunc, applied to values -
def cycle(o)Likeitertools.cycleexcept creates list ofNones ifois empty -
def zip_cycle(x, *args)Likeitertools.zip_longestbutcycles through elements of all but first argument -
def sorted_ex(iterable, key, reverse)Likesorted, but if key is str useattrgetter; if int useitemgetter -
def not_(f)Create new function that negates result off -
def argwhere(iterable, f, negate, **kwargs)Likefilter_ex, but return indices for matching items -
def filter_ex(iterable, f, negate, gen, **kwargs)Likefilter, but passingkwargstof, defaultingftonoop, and addingnegateandgen -
def renumerate(iterable, start)Same asenumerate, but returns index as 2nd element instead of 1st -
def first(x, f, negate, **kwargs)First element ofx, optionally filtered byf, or None if missing -
def only(o)Return the only item ofo, raise ifodoesn't have exactly one item -
def nested_attr(o, attr, default)Same asgetattr, but ifattrincludes a., then looks inside nested objects -
def nested_setdefault(o, attr, default)Same assetdefault, but ifattrincludes a., then looks inside nested objects -
def nested_callable(o, attr)Same asnested_attrbut if not found will returnnoop -
def nested_idx(coll, *idxs)Index into nested collections, dicts, etc, withidxs -
def set_nested_idx(coll, value, *idxs)Set value indexed like `nested_idx -
def val2idx(x)Dict from value to index -
def uniqueify(x, sort, bidir, start)Unique elements inx, optionalsort, optional return reverse correspondence, optional prepend with elements. -
def loop_first_last(values)Iterate and generate a tuple with a flag for first and last value. -
def loop_first(values)Iterate and generate a tuple with a flag for first value. -
def loop_last(values)Iterate and generate a tuple with a flag for last value. -
def first_match(lst, f, default)First element oflstmatching predicatef, ordefaultif none -
def last_match(lst, f, default)Last element oflstmatching predicatef, ordefaultif none -
class fastupleAtuplewith elementwise ops and more friendly init behavior-
def __new__(cls, x, *rest) -
def mul(self, *args)*is already defined intuplefor replicating, so usemulinstead -
def add(self, *args)+is already defined intuplefor concat, so useaddinstead
-
-
class bindSame aspartial, except you can usearg0arg1etc param placeholdersdef __init__(self, func, *pargs, **pkwargs)def __call__(self, *args, **kwargs)
-
def mapt(func, *iterables)Tuplifiedmap -
def map_ex(iterable, f, *args, **kwargs)Likemap, but usebind, and supportsstrand indexing -
def compose(*funcs)Create a function that composes all functions infuncs, passing along remaining*argsand**kwargsto all -
def maps(*args)Likemap, except funcs are composed first -
def partialler(f, *args, **kwargs)Likefunctools.partialbut also copies over docstring -
def instantiate(t)Instantiatetif it's a type, otherwise do nothing -
def using_attr(f, attr)Construct a function which appliesfto the argument's attributeattr -
def copy_func(f)Copy a non-builtin function (NBcopy.copydoes not work for this) -
def patch_to(cls, as_prop, cls_method)Decorator: addftocls -
def patch(f)Decorator: addfto the first parameter's class (based on f's type annotations) -
def patch_property(f)Deprecated; usepatch(as_prop=True)instead -
def compile_re(pat)Compilepatif it's not None -
class ImportEnumAnEnumthat can have its values imported@classmethod def imports(cls)@property def name(self)
-
class StrEnumAnImportEnumthat behaves like astrdef __str__(self)@property def name(self)
-
def str_enum(name, *vals)Simplified creation ofStrEnumtypes -
class ValEnumAnImportEnumthat stringifies using valuesdef __str__(self)@property def name(self)
-
class StatefulA base class/mixin for objects that should not serialize all their statedef __init__(self, *args, **kwargs)def __getstate__(self)def __setstate__(self, state)
-
class NotStrBehaves like astr, but isn't an instance of onedef __init__(self, s)def __repr__(self)def __str__(self)def __add__(self, b)def __mul__(self, b)def __len__(self)def __eq__(self, b)def __lt__(self, b)def __hash__(self)def __bool__(self)def __contains__(self, b)def __iter__(self)
-
class PrettyStringLittle hack to get strings to show properly in Jupyter.def __repr__(self)
-
def even_mults(start, stop, n)Build log-stepped array fromstarttostopinnsteps. -
def num_cpus()Get number of cpus -
def add_props(f, g, n)Create properties passing each ofrange(n)to f -
def typed(f)Decorator to check param and return types at runtime -
def exec_new(code)Executecodein a new environment and return it -
def exec_import(mod, sym)Importsymfrommodin a new environment -
def str2bool(s)Case-insensitive convert stringstoo a bool (y,yes,t,true,on,1->True)
Basic single and dual parameter dispatch
-
def lenient_issubclass(cls, types)If possible return whetherclsis a subclass oftypes, otherwise return False. -
def sorted_topologically(iterable)Return a new list containing all items from the iterable sorted topologically -
class TypeDispatchDictionary-like object;__getitem__matches keys of types usingissubclass-
def __init__(self, funcs, bases) -
def add(self, f)Add typetand functionf -
def first(self)Get first function in ordered dict of type:func. -
def returns(self, x)Get the return type of annotation ofx. -
def __repr__(self) -
def __call__(self, *args, **kwargs) -
def __get__(self, inst, owner) -
def __getitem__(self, k)Find first matching type that is a super-class ofk
-
-
class DispatchRegA global registry forTypeDispatchobjects keyed by function namedef __init__(self)def __call__(self, f)
-
def retain_meta(x, res, as_copy)Callres.set_meta(x), if it exists -
def default_set_meta(self, x, as_copy)Copy over_metafromxtores, if it's missing -
@typedispatch def cast(x, typ)castxto typetyp(may also changexinplace) -
def retain_type(new, old, typ, as_copy)Castnewto type ofoldortypif it's a superclass -
def retain_types(new, old, typs)Cast each item ofnewto type of matching item inoldif it's a superclass -
def explode_types(o)Return the type ofo, potentially in nested dictionaries for thing that are listy
Document parameters using comments.
-
def docstring(sym)Get docstring forsymfor functions ad classes -
def parse_docstring(sym)Parse a numpy-style docstring insym -
def isdataclass(s)Check ifsis a dataclass but not a dataclass' instance -
def get_dataclass_source(s)Get source code for dataclasss -
def get_source(s)Get source code for string, function object or dataclasss -
def get_name(obj)Get the name ofobj -
def qual_name(obj)Get the qualified name ofobj -
@delegates(_docments) def docments(elt, full, **kwargs)Generates adocment -
def extract_docstrings(code)Create a dict from function/class/method names to tuples of docstrings and param lists
Parse numpy-style docstrings
-
def strip_blank_lines(l)Remove leading and trailing blank lines from a list of lines -
class ReaderA line-based string reader.def __init__(self, data)def __getitem__(self, n)def reset(self)def read(self)def seek_next_non_empty_line(self)def eof(self)def read_to_condition(self, condition_func)def read_to_next_empty_line(self)def read_to_next_unindented_line(self)def peek(self, n)def is_empty(self)
-
class ParseErrordef __str__(self)
-
class NumpyDocStringParses a numpydoc string to an abstract representationdef __init__(self, docstring, config)def __iter__(self)def __len__(self)def __getitem__(self, key)def __setitem__(self, key, val)
-
def dedent_lines(lines, split)Deindent a list of lines maximally
The
Lclass and helpers for it
-
@contextmanager def working_directory(path)Change working directory topathand return to previous on exit. This is a multi-line docstring. Ok this is a different line even. -
def add_docs(cls, cls_doc, **docs)Copy values fromdocstoclsdocstrings, and confirm all public methods are documented -
def docs(cls)Decorator version ofadd_docs, using_docsdict -
def coll_repr(c, max_n)String repr of up tomax_nitems of (possibly lazy) collectionc -
def is_bool(x)Check whetherxis a bool or None -
def mask2idxs(mask)Convert bool mask or index list to indexL -
def is_indexer(idx)Test whetheridxwill index a single item in a list -
class CollBaseBase class for composing a list ofitemsdef __init__(self, items)def __len__(self)def __getitem__(self, k)def __setitem__(self, k, v)def __delitem__(self, i)def __repr__(self)def __iter__(self)
-
class LBehaves like a list ofitemsbut can also index with list of indices or masks-
def __init__(self, items, *rest) -
def __getitem__(self, idx) -
def copy(self) -
def __setitem__(self, idx, o)Setidx(can be list of indices, or mask, or int) items too(which is broadcast if not iterable) -
def __eq__(self, b) -
def sorted(self, key, reverse) -
def __iter__(self) -
def __contains__(self, b) -
def __reversed__(self) -
def __invert__(self) -
def __repr__(self) -
def __mul__(a, b) -
def __add__(a, b) -
def __radd__(a, b) -
def __addi__(a, b) -
@classmethod def split(cls, s, sep, maxsplit) -
@classmethod def range(cls, a, b, step) -
def map(self, f, *args, **kwargs) -
def argwhere(self, f, negate, **kwargs) -
def argfirst(self, f, negate) -
def filter(self, f, negate, **kwargs) -
def enumerate(self) -
def renumerate(self) -
def unique(self, sort, bidir, start) -
def val2idx(self) -
def cycle(self) -
def map_dict(self, f, *args, **kwargs) -
def map_first(self, f, g, *args, **kwargs) -
def itemgot(self, *idxs) -
def attrgot(self, k, default) -
def starmap(self, f, *args, **kwargs) -
def zip(self, cycled) -
def zipwith(self, *rest) -
def map_zip(self, f, *args, **kwargs) -
def map_zipwith(self, f, *rest, **kwargs) -
def shuffle(self) -
def concat(self) -
def reduce(self, f, initial) -
def sum(self) -
def product(self) -
def setattrs(self, attr, val)
-
-
def save_config_file(file, d, **kwargs)Write settings dict to a new config file, or overwrite the existing one. -
class ConfigReading and writingConfigParserini filesdef __init__(self, cfg_path, cfg_name, create, save, extra_files, types)def __repr__(self)def __setitem__(self, k, v)def __contains__(self, k)def save(self)def __getattr__(self, k)def __getitem__(self, k)def get(self, k, default)def path(self, k, default)
Recognize image file formats based on their first few bytes.
-
def test_jpeg(h, f)JPEG data with JFIF or Exif markers; and raw JPEG -
def test_gif(h, f)GIF ('87 and '89 variants) -
def test_tiff(h, f)TIFF (can be in Motorola or Intel byte order) -
def test_rgb(h, f)SGI image library -
def test_pbm(h, f)PBM (portable bitmap) -
def test_pgm(h, f)PGM (portable graymap) -
def test_ppm(h, f)PPM (portable pixmap) -
def test_rast(h, f)Sun raster file -
def test_xbm(h, f)X bitmap (X10 or X11)
-
def is_iter(o)Test whetherocan be used in aforloop -
def is_coll(o)Test whetherois a collection (i.e. has a usablelen) -
def all_equal(a, b)Compares whetheraandbare the same length and have the same contents -
def noop(x, *args, **kwargs)Do nothing -
def noops(self, x, *args, **kwargs)Do nothing (method) -
def isinstance_str(x, cls_name)Likeisinstance, except takes a type name instead of a type -
def equals(a, b)Comparesaandbfor equality; supports sublists, tensors and arrays too -
def ipython_shell()Same asget_ipythonbut returnsFalseif not in IPython -
def in_ipython()Check if code is running in some kind of IPython environment -
def in_colab()Check if the code is running in Google Colaboratory -
def in_jupyter()Check if the code is running in a jupyter notebook -
def in_notebook()Check if the code is running in a jupyter notebook -
def remove_prefix(text, prefix)Temporary until py39 is a prereq -
def remove_suffix(text, suffix)Temporary until py39 is a prereq
Metaclasses
-
def test_sig(f, b)Test the signature of an object -
class FixSigMetaA metaclass that fixes the signature on classes that override__new__def __new__(cls, name, bases, dict)
-
class PrePostInitMetaA metaclass that calls optional__pre_init__and__post_init__methodsdef __call__(cls, *args, **kwargs)
-
class AutoInitSame asobject, but no need for subclasses to callsuper().__init__def __pre_init__(self, *args, **kwargs)
-
class NewChkMetaMetaclass to avoid recreating object passed to constructordef __call__(cls, x, *args, **kwargs)
-
class BypassNewMetaMetaclass: castsxto this class if it's of typecls._bypass_typedef __call__(cls, x, *args, **kwargs)
-
def empty2none(p)ReplaceParameter.emptywithNone -
def anno_dict(f)__annotation__ dictionary withemptycast toNone`, returning empty if doesn't exist -
def use_kwargs_dict(keep, **kwargs)Decorator: replace**kwargsin signature withnamesparams -
def use_kwargs(names, keep)Decorator: replace**kwargsin signature withnamesparams -
def delegates(to, keep, but)Decorator: replace**kwargsin signature with params fromto -
def method(f)Markfas a method -
def funcs_kwargs(as_method)Replace methods incls._methodswith those fromkwargs
Network, HTTP, and URL functions
-
def urlquote(url)Update url's path withurllib.parse.quote -
def urlwrap(url, data, headers)Wrapurlin a urllibRequestwithurlquote -
class HTTP4xxClientErrorBase class for client exceptions (code 4xx) fromurl*functions -
class HTTP5xxServerErrorBase class for server exceptions (code 5xx) fromurl*functions -
def urlopen(url, data, headers, timeout, **kwargs)Likeurllib.request.urlopen, but firsturlwraptheurl, and encodedata -
def urlread(url, data, headers, decode, return_json, return_headers, timeout, **kwargs)Retrieveurl, usingdatadict orkwargstoPOSTif present -
def urljson(url, data, timeout)Retrieveurland decode json -
def urlclean(url)Remove fragment, params, and querystring fromurlif present -
def urlsave(url, dest, reporthook, headers, timeout)Retrieveurland save based on its name -
def urlvalid(x)Test ifxis a valid URL -
def urlrequest(url, verb, headers, route, query, data, json_data)Requestforurlwith optional route params replaced byroute, plusquerystring, and postdata -
@patch def summary(self, skip)Summary containing full_url, headers, method, and data, removingskipfrom headers -
def urlsend(url, verb, headers, decode, route, query, data, json_data, return_json, return_headers, debug, timeout)Send request withurlrequest, converting result to json ifreturn_json -
def do_request(url, post, headers, **data)Call GET or json-encoded POST onurl, depending onpost -
def start_server(port, host, dgram, reuse_addr, n_queue)Create asocketserver onport, with optionalhost, of typedgram -
def start_client(port, host, dgram)Create asocketclient onport, with optionalhost, of typedgram -
def tobytes(s)Convertsinto HTTP-ready bytes format -
def http_response(body, status, hdrs, **kwargs)Create an HTTP-ready response, addingkwargstohdrs -
@threaded def recv_once(host, port)Spawn a thread to receive a single HTTP request and store ind['r']
Threading and multiprocessing functions
-
def threaded(process)Runfin aThread(orProcessifprocess=True), and returns it -
def startthread(f)Likethreaded, but start thread immediately -
def startproc(f)Likethreaded(True), but start Process immediately -
class ThreadPoolExecutorSame as Python's ThreadPoolExecutor, except can passmax_workers==0for serial executiondef __init__(self, max_workers, on_exc, pause, **kwargs)def map(self, f, items, *args, **kwargs)
-
@delegates() class ProcessPoolExecutorSame as Python's ProcessPoolExecutor, except can passmax_workers==0for serial executiondef __init__(self, max_workers, on_exc, pause, **kwargs)def map(self, f, items, *args, **kwargs)
-
def parallel(f, items, *args, **kwargs)Appliesfuncin parallel toitems, usingn_workers -
def run_procs(f, f_done, args)Callffor each item inargsin parallel, yieldingf_done -
def parallel_gen(cls, items, n_workers, **kwargs)Instantiateclsinn_workersprocs & call each on a subset ofitemsin parallel.
-
def imp_mod(module_path, package)Import dynamically the module referenced infn -
def has_deco(node, name)Check if a function nodenodehas a decorator namedname -
def create_pyi(fn, package)Convertfname.pytofname.pyiby removing function bodies and expandingdelegateskwargs -
@call_parse def py2pyi(fname, package)Convertfname.pytofname.pyiby removing function bodies and expandingdelegateskwargs -
@call_parse def replace_wildcards(path)Expand wildcard imports in the specified Python file.
A fast way to turn your python function into a script.
-
def store_true()Placeholder to pass toParamforstore_trueaction -
def store_false()Placeholder to pass toParamforstore_falseaction -
def bool_arg(v)Use astypeforParamto getboolbehavior -
class ParamA parameter in a function used inanno_parserorcall_parsedef __init__(self, help, type, opt, action, nargs, const, choices, required, default)def set_default(self, d)@property def pre(self)@property def kwargs(self)def __repr__(self)
-
def anno_parser(func, prog)Look at params (annotated withParam) in func and return anArgumentParser -
def args_from_prog(func, prog)Extract args fromprog -
def call_parse(func, nested)Decorator to create a simple CLI fromfuncusinganno_parser
Fast styling for friendly CLIs.
-
class StyleCodeAn escape sequence for styling terminal text.def __init__(self, name, code, typ)def __str__(self)
-
class StyleA minimal terminal text styler.def __init__(self, codes)def __dir__(self)def __getattr__(self, k)def __call__(self, obj)def __repr__(self)
-
def demo()Demonstrate all available styles and their codes.
Helper functions to quickly write tests in notebooks
-
def test_fail(f, msg, contains, args, kwargs)Fails withmsgunlessf()raises an exception and (optionally) hascontainsine.args -
def test(a, b, cmp, cname)assertthatcmp(a,b); display inputs andcname or cmp.__name__if it fails -
def nequals(a, b)Comparesaandbfornot equals -
def test_eq(a, b)testthata==b -
def test_eq_type(a, b)testthata==band are same type -
def test_ne(a, b)testthata!=b -
def is_close(a, b, eps)Isawithinepsofb -
def test_close(a, b, eps)testthatais withinepsofb -
def test_is(a, b)testthata is b -
def test_shuffled(a, b)testthataandbare shuffled versions of the same sequence of items -
def test_stdout(f, exp, regex)Test thatfprintsexpto stdout, optionally checking asregex -
def test_fig_exists(ax)Test there is a figure displayed inax -
class ExceptionExpectedContext manager that tests if an exception is raiseddef __init__(self, ex, regex)def __enter__(self)def __exit__(self, type, value, traceback)
Definition of
TransformandPipeline
-
class TransformDelegates (__call__,decode,setup) to (encodes,decodes,setups) ifsplit_idxmatchesdef __init__(self, enc, dec, split_idx, order)@property def name(self)def __call__(self, x, **kwargs)def decode(self, x, **kwargs)def __repr__(self)def setup(self, items, train_setup)
-
class InplaceTransformATransformthat modifies in-place and just returns whatever it's passed -
class DisplayedTransformA transform with a__repr__that shows its attrs@property def name(self)
-
class ItemTransformA transform that always take tuples as itemsdef __call__(self, x, **kwargs)def decode(self, x, **kwargs)
-
def get_func(t, name, *args, **kwargs)Get thet.name(potentially partial-ized withargsandkwargs) ornoopif not defined -
class FuncBasic wrapper around anamewithargsandkwargsto call on a given typedef __init__(self, name, *args, **kwargs)def __repr__(self)def __call__(self, t)
-
def compose_tfms(x, tfms, is_enc, reverse, **kwargs)Apply allfunc_nmattribute oftfmsonx, maybe inreverseorder -
def mk_transform(f)Convert functionftoTransformif it isn't already one -
def gather_attrs(o, k, nm)Used in getattr to collect all attrskfromself.{nm} -
def gather_attr_names(o, nm)Used in dir to collect all attrskfromself.{nm} -
class PipelineA pipeline of composed (for encode/decode) transforms, setup with typesdef __init__(self, funcs, split_idx)def setup(self, items, train_setup)def add(self, ts, items, train_setup)def __call__(self, o)def __repr__(self)def __getitem__(self, i)def __setstate__(self, data)def __getattr__(self, k)def __dir__(self)def decode(self, o, full)def show(self, o, ctx, **kwargs)
XDG Base Directory Specification helpers.
-
def xdg_cache_home()Path corresponding toXDG_CACHE_HOME -
def xdg_config_dirs()Paths corresponding toXDG_CONFIG_DIRS -
def xdg_config_home()Path corresponding toXDG_CONFIG_HOME -
def xdg_data_dirs()Paths corresponding to XDG_DATA_DIRS` -
def xdg_data_home()Path corresponding toXDG_DATA_HOME -
def xdg_runtime_dir()Path corresponding toXDG_RUNTIME_DIR -
def xdg_state_home()Path corresponding toXDG_STATE_HOME
Concise generation of XML.
-
class FTA 'Fast Tag' structure, containingtag,children,andattrsdef __init__(self, tag, cs, attrs, void_, **kwargs)def __setattr__(self, k, v)def __getattr__(self, k)@property def list(self)def get(self, k, default)def __repr__(self)def __add__(self, b)def __getitem__(self, idx)def __iter__(self)
-
def ft(tag, *c, **kw)Create anFTstructure forto_xml() -
def Html(*c, **kwargs)An HTML tag, optionally preceeded by!DOCTYPE HTML -
class Safedef __html__(self)
-
def to_xml(elm, lvl, indent, do_escape)Convertftelement tree into an XML string -
def highlight(s, lang)Markdown to syntax-highlightsin languagelang
Utility functions used in the fastai library
-
def walk(path, symlinks, keep_file, keep_folder, skip_folder, func, ret_folders)Generator version ofos.walk, using functions to filter files and folders -
def globtastic(path, recursive, symlinks, file_glob, file_re, folder_re, skip_file_glob, skip_file_re, skip_folder_re, func, ret_folders)A more powerfulglob, including regex matches, symlink handling, and skip parameters -
@contextmanager def maybe_open(f, mode, **kwargs)Context manager: openfif it is a path (and close on exit) -
def mkdir(path, exist_ok, parents, overwrite, **kwargs)Creates and returns a directory defined bypath, optionally removing previous existing directory ifoverwriteisTrue -
def image_size(fn)Tuple of (w,h) for png, gif, or jpg;Noneotherwise -
def bunzip(fn)bunzipfn, raising exception if output already exists -
def loads(s, **kw)Same asjson.loads, but handlesNone -
def loads_multi(s)Generator of >=0 decoded json dicts, possibly with non-json ignored text at start and end -
def dumps(obj, **kw)Same asjson.dumps, but usesujsonif available -
def untar_dir(fname, dest, rename, overwrite)untarfileintodest, creating a directory if the root contains more than one item -
def repo_details(url)Tuple ofowner,namefrom ssh or https git repourl -
def run(cmd, *rest)Passcmd(splitting withshlexif string) tosubprocess.run; returnstdout; raiseIOErrorif fails -
def open_file(fn, mode, **kwargs)Open a file, with optional compression if gz or bz2 suffix -
def save_pickle(fn, o)Save a pickle file, to a file name or opened file -
def load_pickle(fn)Load a pickle file from a file name or opened file -
def parse_env(s, fn)Parse a shell-style environment string or file -
def expand_wildcards(code)Expand all wildcard imports in the given code string. -
def dict2obj(d, list_func, dict_func)Convert (possibly nested) dicts (or lists of dicts) toAttrDict -
def obj2dict(d)Convert (possibly nested) AttrDicts (or lists of AttrDicts) todict -
def repr_dict(d)Print nested dicts and lists, such as returned bydict2obj -
def is_listy(x)isinstance(x, (tuple,list,L,slice,Generator)) -
def mapped(f, it)mapfoverit, unless it's not listy, in which case returnf(it) -
@patch def readlines(self, hint, encoding)Read the content ofself -
@patch def read_json(self, encoding, errors)Same asread_textfollowed byloads -
@patch def mk_write(self, data, encoding, errors, mode)Make all parent dirs ofself, and writedata -
@patch def relpath(self, start)Same asos.path.relpath, but returns aPath, and resolves symlinks -
@patch def ls(self, n_max, file_type, file_exts)Contents of path as a list -
@patch def delete(self)Delete a file, symlink, or directory tree -
class IterLenBase class to add iteration to anything supporting__len__and__getitem__def __iter__(self)
-
@docs class ReindexCollectionReindexes collectioncollwith indicesidxsand optional LRU cache of sizecachedef __init__(self, coll, idxs, cache, tfm)def __getitem__(self, i)def __len__(self)def reindex(self, idxs)def shuffle(self)def cache_clear(self)def __getstate__(self)def __setstate__(self, s)
-
def get_source_link(func)Return link tofuncin source code -
def truncstr(s, maxlen, suf, space)Truncatesto lengthmaxlen, adding suffixsufif truncated -
def sparkline(data, mn, mx, empty_zero)Sparkline fordata, withNones (and zero, ifempty_zero) shown as empty column -
def modify_exception(e, msg, replace)Modifiesewith a custom message attached -
def round_multiple(x, mult, round_down)Roundxto nearest multiple ofmult -
def set_num_threads(nt)Get numpy (and others) to usentthreads -
def join_path_file(file, path, ext)Returnpath/fileif file is a string or aPath, file otherwise -
def autostart(g)Decorator that automatically starts a generator -
class EventTimerAn event timer with history ofstoreitems of timespan-
def __init__(self, store, span) -
def add(self, n)Recordnevents -
@property def duration(self) -
@property def freq(self)
-
-
def stringfmt_names(s)Unique brace-delimited names ins -
class PartialFormatterAstring.Formatterthat doesn't error on missing fields, and tracks missing fields and unused argsdef __init__(self)def get_field(self, nm, args, kwargs)def check_unused_args(self, used, args, kwargs)
-
def partial_format(s, **kwargs)string formats, ignoring missing field errors, returning missing and extra fields -
def utc2local(dt)Convertdtfrom UTC to local time -
def local2utc(dt)Convertdtfrom local to UTC time -
def trace(f)Addset_traceto an existing functionf -
@contextmanager def modified_env(*delete, **replace)Context manager temporarily modifyingos.environby deletingdeleteand replacingreplace -
class ContextManagersWrapper forcontextlib.ExitStackwhich enters a collection of context managersdef __init__(self, mgrs)def __enter__(self)def __exit__(self, *args, **kwargs)
-
def shufflish(x, pct)Randomly relocate items ofxup topctoflen(x)from their starting location -
def console_help(libname)Show help for all console scripts fromlibname -
def hl_md(s, lang, show)Syntax highlightsusinglang. -
def type2str(typ)Stringifytyp -
class Unsetdef __repr__(self)def __str__(self)def __bool__(self)@property def name(self)
-
def nullable_dc(cls)Likedataclass, but default ofUNSETadded to fields without defaults -
def flexiclass(cls)Convertclsinto adataclasslikemake_nullable. Converts in place and also returns the result. -
def asdict(o)Convertoto adict, supporting dataclasses, namedtuples, iterables, and__dict__attrs. -
def is_typeddict(cls)Check ifclsis aTypedDict -
def is_namedtuple(cls)Trueifclsis a namedtuple type -
def flexicache(*funcs)Likelru_cache, but customisable with policyfuncs -
def time_policy(seconds)Aflexicachepolicy that expires cached items aftersecondshave passed -
def mtime_policy(filepath)Aflexicachepolicy that expires cached items afterfilepathmodified-time changes -
def timed_cache(seconds, maxsize)Likelru_cache, but also with time-based eviction