### Using PrePostInitMeta for Initialization Hooks Python Source: https://fastcore.fast.ai/meta.html.md This example demonstrates the use of `PrePostInitMeta` to define `__pre_init__` and `__post_init__` methods. These methods are automatically called before and after the standard `__init__` method, allowing for setup and teardown logic. ```python class _T(metaclass=PrePostInitMeta): def __pre_init__(self): self.a = 0; def __init__(self,b=0): self.b = self.a + 1; assert self.b==1 def __post_init__(self): self.c = self.b + 2; assert self.c==3 t = _T() test_eq(t.a, 0) # set with __pre_init__ test_eq(t.b, 1) # set with __init__ test_eq(t.c, 3) # set with __post_init__ ``` -------------------------------- ### NS Instance Output - fastcore - Text Source: https://fastcore.fast.ai/basics.html.md Example of the string representation of an NS instance. ```text namespace(a=1, b={'c': 1, 'd': 2}, c={'c': 1, 'd': 2}, d={'c': 1, 'd': 2}, e={'c': 1, 'd': 2}, f={'c': 1, 'd': 2, 'e': 4, 'f': [1, 2, 3, 4, 5]}) ``` -------------------------------- ### Install fastcore (Conda/Pip) Source: https://fastcore.fast.ai/index Commands to install the fastcore library using either the Conda package manager or Pip. Includes the standard installation and an editable installation for development. ```Shell conda install fastcore -c fastai ``` ```Shell pip install fastcore ``` ```Shell pip install -e ".[dev]" ``` -------------------------------- ### Process Module AST - Python Source: https://fastcore.fast.ai/py2pyi.html.md Gets the raw AST for the module using `_get_tree` and then processes it using the `_proc_mod` function. It also calculates the initial number of nodes in the raw tree body, likely as a setup step for comparing the tree before and after processing. ```Python raw_tree = _get_tree(mod) processed_tree = _proc_mod(mod) n_raw_tree_nodes = len(raw_tree.body) ``` -------------------------------- ### Sample Function for bind Demonstration Source: https://fastcore.fast.ai/basics.html.md Defines a simple Python function `myfn` with positional and keyword arguments. This function is used in subsequent examples to demonstrate the capabilities of the `bind` utility. ```python def myfn(a,b,c,d=1,e=2): return(a,b,c,d,e) ``` -------------------------------- ### Importing fastcore network utilities Source: https://fastcore.fast.ai/net.html.md Imports necessary modules from fastcore and nbdev for testing and documentation examples. ```python from fastcore.test import * from nbdev.showdoc import * from fastcore.nb_imports import * ``` -------------------------------- ### Importing fastcore meta dependencies - Python Source: https://fastcore.fast.ai/meta.html.md This code block imports necessary modules from `fastcore.foundation`, `nbdev.showdoc`, and `fastcore.nb_imports`. These imports are likely prerequisites for the examples and functionality discussed in the rest of the document. ```python from fastcore.foundation import * from nbdev.showdoc import * from fastcore.nb_imports import * ``` -------------------------------- ### Accessing Config Values (Attribute, Item, Get) Source: https://fastcore.fast.ai/foundation.html.md Demonstrates accessing configuration values using attribute access (dot notation), item access (square brackets), and the `get` method with an optional default value. ```python test_eq(cfg.user,'fastai') test_eq(cfg['some_path'], 'test') test_eq(cfg.get('foo','bar'),'bar') ``` -------------------------------- ### Emulating List Behavior with CollBase in Python Source: https://fastcore.fast.ai/foundation.html.md This snippet demonstrates the basic list-like functionality provided by the `CollBase` base class. It shows how a class inheriting from `CollBase` can support standard list operations such as getting length (`__len__`), item access (`__getitem__`), item assignment (`__set_item__`), item deletion (`__delitem__`), and string representation (`__repr__`). The example uses `test_eq` to verify the results of these operations. ```python class _T(CollBase): pass l = _T([1,2,3,4,5]) test_eq(len(l), 5) # __len__ test_eq(l[-1], 5); test_eq(l[0], 1) #__getitem__ l[2] = 100; test_eq(l[2], 100) # __set_item__ del l[0]; test_eq(len(l), 4) # __delitem__ test_eq(str(l), '[2, 100, 4, 5]') # __repr__ ``` -------------------------------- ### Example Usage of Original what Function with Path Source: https://fastcore.fast.ai/xtras.html.md Demonstrates calling the reimplemented `what` function with a file path (`fname`) to determine the image type. ```Python fname = 'images/puppy.jpg' what(fname) ``` -------------------------------- ### Nesting Styles Example 1 (Python) Source: https://fastcore.fast.ai/style.html.md Provides an example of combining multiple styles within a single print statement, demonstrating how to apply different styles to different parts of a string, including nesting. ```python print(S.bold(S.blue('key') + ' = value ') + S.light_gray(' ' + S.underline('# With a comment')) + ' and unstyled text') ``` -------------------------------- ### Getting Function Annotations with anno_dict in Python Source: https://fastcore.fast.ai/meta.html.md Demonstrates the anno_dict function, which retrieves the __annotations__ dictionary of a function, replacing Parameter.empty with None. Shows an example function _f with type hints and asserts the expected output dictionary. Requires the L type hint to be defined elsewhere. ```python def _f(a:int, b:L)->str: ... test_eq(anno_dict(_f), {'a': int, 'b': L, 'return': str}) ``` -------------------------------- ### Nesting Styles Example 2 (Python) Source: https://fastcore.fast.ai/style.html.md Another example showing how to nest styles, applying bold formatting to a word ("is") within a blue-colored string. ```python print(S.blue('this '+S.bold('is')+' a test')) ``` -------------------------------- ### AttrDict Pretty Print Output - fastcore - JSON Source: https://fastcore.fast.ai/basics.html.md Example of the JSON-like output format when an AttrDict is pretty-printed. ```json { 'a': 1, 'b': {'c': 1, 'd': 2}, 'c': {'c': 1, 'd': 2}, 'd': {'c': 1, 'd': 2}, 'e': {'c': 1, 'd': 2}, 'f': {'c': 1, 'd': 2, 'e': 4, 'f': [1, 2, 3, 4, 5]}} ``` -------------------------------- ### Finding Config File in Parent Directories Source: https://fastcore.fast.ai/foundation.html.md Demonstrates using the static method `Config.find` to search for a configuration file (`cfg_name`) starting in a specified path (or the current directory) and traversing up parent directories. ```python Config.find('settings.ini').repo ``` -------------------------------- ### Accessing Detailed Documentation with fastcore doc Source: https://fastcore.fast.ai/tour.html.md This snippet shows how to use the `doc` function in fastcore to open a detailed documentation window for a specific object (like `coll_repr`), providing comprehensive information including source code links, related functions, and examples. ```python doc(coll_repr) ``` -------------------------------- ### Example Usage of fastcore parallel_gen (Commented) - Python Source: https://fastcore.fast.ai/parallel.html.md This commented-out snippet provides an example of how to use `fastcore.parallel_gen` with a simple callable class `_C`. It demonstrates instantiating the class in parallel processes and processing items in batches, although the code is currently inactive. ```python # class _C: # def __call__(self, o): return ((i+1) for i in o) # items = range(5) # res = L(parallel_gen(_C, items, n_workers=0)) # idxs,dat1 = zip(*res.sorted(itemgetter(0))) # test_eq(dat1, range(1,6)) # res = L(parallel_gen(_C, items, n_workers=3)) # idxs,dat2 = zip(*res.sorted(itemgetter(0))) # test_eq(dat2, dat1) ``` -------------------------------- ### Using map_ex with a Function Source: https://fastcore.fast.ai/basics.html.md Shows the basic usage of `fastcore.map_ex`, which is similar to `map` but offers additional features. This example applies the `operator.neg` function to each element of a list. ```python test_eq(map_ex(t,operator.neg), [0,-1,-2,-3]) ``` -------------------------------- ### Writing config file with inline comments for fastcore Config in Python Source: https://fastcore.fast.ai/foundation.html.md Provides an example of a config file string containing inline comments and demonstrates how to write this string to a file, preparing it for parsing with `ConfigParser`. ```Python cfg_str = """\\\n[DEFAULT]\nuser = fastai # inline comment\n\n# Library configuration\nlib_name = fastcore\n\n# Paths\nsome_path = test\n\n# Feature flags\nsome_bool = True\n\n# Numeric settings\nsome_num = # missing value\n"""\n\nwith open('../tmp.ini', 'w') as f:\n f.write(cfg_str) ``` -------------------------------- ### Example Output of docments (JSON) Source: https://fastcore.fast.ai/docments.html.md Shows the JSON output structure returned by `docments(add_mixed, full=True)`, detailing the extracted documentation for parameters ('a', 'b') and the return value, including annotations, defaults, and docstrings. ```JSON { 'a': { 'anno': , 'default': , 'docment': 'the first number to add'}, 'b': { 'anno': 'int', 'default': , 'docment': 'the 2nd number to add (default: 0)'}, 'return': { 'anno': , 'default': , 'docment': 'the result'}} ``` -------------------------------- ### Importing gt for fastcore L examples Source: https://fastcore.fast.ai/foundation.html.md Imports the 'gt' function from fastcore.utils, used in subsequent examples for filtering. ```python from fastcore.utils import gt ``` -------------------------------- ### store_attr Storing All Arguments by Default (Complete Example) Source: https://fastcore.fast.ai/basics.html.md Provides a complete example demonstrating how `fastcore.store_attr` stores all constructor arguments as instance attributes when called without arguments, including class definition, instantiation, and verification. ```python class T: def __init__(self, a,b,c): store_attr() t = T(1,c=2,b=3) assert t.a==1 and t.b==3 and t.c==2 ``` -------------------------------- ### Using the startproc decorator Source: https://fastcore.fast.ai/parallel.html.md Demonstrates the `@startproc` decorator, which is equivalent to `@threaded(process=True)` and starts the function execution in a new process immediately upon the function's definition. ```python @startproc def _(): time.sleep(0.05) print("second") @startproc def _(): time.sleep(0.01) print("first") time.sleep(0.1) ``` -------------------------------- ### Define Sample Function f - Python Source: https://fastcore.fast.ai/py2pyi.html.md Defines a sample Python function `f` with type hints for parameters (`a` as int, `b` as str with default 'a') and return type (`str`). It includes a docstring and returns an integer `1`. This function is used as an example for AST analysis and decorator handling. ```Python def f(a: int, b: str='a') -> str: """I am f""" return 1 ``` -------------------------------- ### Testing Warnings with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Demonstrates the use of `test_warns` to assert that a function raises a warning. Includes examples of successful tests and expected failures when no warning is raised, and showing the warning. ```python test_warns(lambda: warnings.warn("Oh no!")) test_fail(lambda: test_warns(lambda: 2+2), contains='No warnings raised') ``` ```python test_warns(lambda: warnings.warn("Oh no!"), show=True) ``` -------------------------------- ### Getting Function Argument Names with fastcore.argnames Source: https://fastcore.fast.ai/basics.html.md Demonstrates how `fastcore.argnames` retrieves a list of parameter names for a given function. ```python test_eq(argnames(f), ['x']) ``` -------------------------------- ### Testing Equality and Type with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Demonstrates how to use `test_eq_type` to assert that two values are equal and have the same type. Includes examples of successful tests and expected failures. ```python test_eq_type(1,1) test_fail(lambda: test_eq_type(1,1.)) test_eq_type([1,1],[1,1]) test_fail(lambda: test_eq_type([1,1],(1,1))) test_fail(lambda: test_eq_type([1,1],[1,1.])) ``` -------------------------------- ### Using globtastic for filtered file search in fastcore (Python) Source: https://fastcore.fast.ai/xtras.html.md This example demonstrates using the `globtastic` function to search for files. It starts the search in the current directory (`.`), skips folders starting with `_` or `.`, only enters folders containing `core`, includes files matching the glob `*.*py*`, and further filters to include files matching the regex `c`. ```python globtastic('.', skip_folder_re='^[_.]', folder_re='core', file_glob='*.*py*', file_re='c') ``` -------------------------------- ### Running Basic Commands - Python Source: https://fastcore.fast.ai/xtras.html.md Shows how to use the `run` function to execute simple commands, accepting the command as a string (which is split), a list of arguments, or multiple direct arguments. ```python run('echo', same_in_win=True) run('pip', '--version', same_in_win=True) run(['pip', '--version'], same_in_win=True) ``` -------------------------------- ### Modifying fastcore L and using methods Source: https://fastcore.fast.ai/foundation.html.md Examples of modifying an L object using append, +, and *, and applying methods like map, sum, product, cycle, and shuffle. ```python t = L() test_eq(t, []) t.append(1) test_eq(t, [1]) t += [3,2] test_eq(t, [1,3,2]) t = t + [4] test_eq(t, [1,3,2,4]) t = 5 + t test_eq(t, [5,1,3,2,4]) test_eq(L(1,2,3), [1,2,3]) test_eq(L(1,2,3), L(1,2,3)) t = L(1)*5 t = t.map(operator.neg) test_eq(t,[-1]*5) test_eq(~L([True,False,False]), L([False,True,True])) t = L(range(4)) test_eq(zip(t, L(1).cycle()), zip(range(4),(1,1,1,1))) t = L.range(100) test_shuffled(t,t.shuffle()) ``` ```python test_eq(L([]).sum(), 0) test_eq(L([]).product(), 1) ``` ```python def _f(x,a=0): return x+a t = L(1)*5 test_eq(t.map(_f), t) test_eq(t.map(_f,1), [2]*5) test_eq(t.map(_f,a=2), [3]*5) ``` -------------------------------- ### Instantiating fastcore Config from file in Python Source: https://fastcore.fast.ai/foundation.html.md Demonstrates creating a `Config` object by specifying the path and filename of an existing ini file, showing how the configuration is loaded into the object. ```Python save_config_file('../tmp.ini', _d) try: cfg = Config('..', 'tmp.ini') finally: os.unlink('../tmp.ini') cfg ``` -------------------------------- ### Getting Range or Indices with fastcore range_of Source: https://fastcore.fast.ai/basics.html.md Explains the `range_of` function, which returns the indices of a collection if the input is a collection, or a standard `range` object if the input is an integer. Examples show its use with a list and an integer. ```python test_eq(range_of([1,1,1,1]), [0,1,2,3]) test_eq(range_of(4), [0,1,2,3]) ``` -------------------------------- ### Using bind with Fixed Values and Argument Reordering Source: https://fastcore.fast.ai/basics.html.md Shows another example of `fastcore.bind` where the first argument is fixed to `17`, the second argument is taken from the first input using `arg0`, and the third argument is taken from the second input. A keyword argument `e` is also overridden. ```python test_eq(bind(myfn, 17, arg0, e=3)(19,14), (17,19,14,1,3)) ``` -------------------------------- ### Using fastcore parallel with Pause - Python Source: https://fastcore.fast.ai/parallel.html.md This example defines a function `print_time` that simulates work by sleeping and then prints an index and the current time. It then calls `fastcore.parallel` with this function and a range of inputs, demonstrating the effect of the `pause` parameter on the start times of parallel processes. ```python def print_time(i): time.sleep(random.random()/1000) print(i, datetime.now()) parallel(print_time, range(5), n_workers=2, pause=0.25); ``` -------------------------------- ### Joining Path and File in Python Source: https://fastcore.fast.ai/xtras.html.md Explains the `join_path_file` function, its parameters (`file`, `path`, `ext`), and how it constructs a file path or returns the file object itself. Mentions the code demonstrates creating a path, joining a file name, and handling file objects. ```python path = Path.cwd()/'_tmp'/'tst' f = join_path_file('tst.txt', path) assert path.exists() test_eq(f, path/'tst.txt') with open(f, 'w') as f_: assert join_path_file(f_, path) == f_ shutil.rmtree(Path.cwd()/'_tmp') ``` -------------------------------- ### Truncate String with truncstr (Python) Source: https://fastcore.fast.ai/xtras.html.md Provides examples of using `truncstr` to shorten a string to a specified maximum length. Shows how to customize the truncation suffix and add space padding, verified with `test_eq`. ```python w = 'abacadabra'\ntest_eq(truncstr(w, 10), w)\ntest_eq(truncstr(w, 5), 'abac…')\ntest_eq(truncstr(w, 5, suf=''), 'abaca')\ntest_eq(truncstr(w, 11, space='_'), w+"_")\ntest_eq(truncstr(w, 10, space='_'), w[:-1]+'…')\ntest_eq(truncstr(w, 5, suf='!!'), 'aba!!') ``` -------------------------------- ### Using ExceptionExpected Context Manager (Python) Source: https://fastcore.fast.ai/test.html.md Demonstrates the usage of the `ExceptionExpected` context manager to assert that specific exceptions are raised within a block of code. Shows examples with default behavior, specific exception types, and regex matching on the exception message. ```python def _tst_1(): assert False, "This is a test" def _tst_2(): raise SyntaxError with ExceptionExpected(): _tst_1() with ExceptionExpected(ex=AssertionError, regex="This is a test"): _tst_1() with ExceptionExpected(ex=SyntaxError): _tst_2() ``` -------------------------------- ### Delegates with instance methods in Python Source: https://fastcore.fast.ai/meta.html.md This example shows `delegates` used with instance methods. The `@delegates(foo)` decorator on the instance method `bar` includes parameters from the instance method `foo` into the signature of `bar`. ```Python class _T(): def foo(self, a=1, b=2): pass @delegates(foo) def bar(self, c=3, **kwargs): pass ``` -------------------------------- ### Running Platform-Specific Commands - Python Source: https://fastcore.fast.ai/xtras.html.md Demonstrates using `run` to execute different commands based on the operating system (`cmd /c dir /p` on Windows, `ls -ls` on others) and asserts that expected output is present. ```python if sys.platform == 'win32': assert 'ipynb' in run('cmd /c dir /p') assert 'ipynb' in run(['cmd', '/c', 'dir', '/p']) assert 'ipynb' in run('cmd', '/c', 'dir', '/p') else: assert 'ipynb' in run('ls -ls') assert 'ipynb' in run(['ls', '-l']) assert 'ipynb' in run('ls', '-l') ``` -------------------------------- ### Demonstrating All Styles (Python) Source: https://fastcore.fast.ai/style.html.md Shows how to call the `demo()` function, which prints a list of all available styles and their corresponding ANSI escape codes, useful for exploring options. ```python demo() ``` -------------------------------- ### Generating Colab Link in fastcore Source: https://fastcore.fast.ai/tour.html.md This snippet shows how to use the `colab_link` function in fastcore to generate a link to an interactive Google Colab notebook for a specific file, enabling users to follow along with documentation examples interactively. ```python colab_link('000_tour') ``` -------------------------------- ### Creating HTTP Response (Python) Source: https://fastcore.fast.ai/net.html.md Generates an HTTP-ready byte response string. It takes a body, status code, optional headers, and additional keyword arguments which are added to the headers. The example shows creating a basic 200 OK response with a custom header. ```Python exp = b'HTTP/1.1 200 OK\r\nUser-Agent: me\r\nContent-Length: 4\r\n\r\nbody'\ntest_eq(http_response('body', 200, User_Agent='me'), exp) ``` -------------------------------- ### Example Output of docments with full=True on Delegated Function (JSON) Source: https://fastcore.fast.ai/docments.html.md Shows the JSON output structure returned by `docments(_b, full=True)`, detailing the combined documentation for parameters ('a', 'b') and the return value, including annotations, defaults, and docstrings, extracted from a function using `@delegates`. ```JSON { 'a': {'anno': , 'default': 2, 'docment': 'First'}, 'b': { 'anno': 'str', 'default': , 'docment': 'Second'}, 'return': { 'anno': , 'default': , 'docment': None}} ``` -------------------------------- ### Executing Code Locally with exec_local in Python Source: https://fastcore.fast.ai/basics.html.md Shows how `exec_local` executes a string of Python code and returns the value of a specified variable defined within that code. The example executes `a=1` and returns the value of `a`. ```python test_eq(exec_local("a=1", "a"), 1) ``` -------------------------------- ### Simplifying Class Initialization and Representation with fastcore store_attr and basic_repr (Python) Source: https://fastcore.fast.ai/tour.html.md Demonstrates using `fastcore.store_attr` to automatically assign constructor arguments to instance attributes and `fastcore.basic_repr` to generate a simple, useful string representation for an object. ```python class ProductPage: def __init__(self,author,price,cost): store_attr() __repr__ = basic_repr('author,price,cost') ProductPage("Jeremy", 1.50, 0.50) ``` -------------------------------- ### Creating fastcore Config with default values in Python Source: https://fastcore.fast.ai/foundation.html.md Shows how to instantiate a `Config` object using a `create` dictionary, which provides default values if the specified config file does not exist. ```Python try: cfg = Config('..', 'tmp.ini', create=_d) finally: os.unlink('../tmp.ini') cfg ``` -------------------------------- ### Creating NS Instance - fastcore - Python Source: https://fastcore.fast.ai/basics.html.md Shows how to create an instance of the NS class, which is a subclass of SimpleNamespace. ```python d = NS(**_test_dict) d ``` -------------------------------- ### Getting Indices of Collection in Python Source: https://fastcore.fast.ai/basics.html.md This function returns a list of indices for a given collection `x`. It is equivalent to `list(range(len(x)))`. It provides a simple way to get the valid index range for iterating over a collection. ```Python test_eq(range_of([1,1,1,1]), [0,1,2,3]) ``` -------------------------------- ### Get Source Code Link (Python) Source: https://fastcore.fast.ai/xtras.html.md Demonstrates how to use `get_source_link` to retrieve the URL for a function's source code, particularly useful in nbdev projects. Shows importing the function and asserting properties of the generated link. ```python from fastcore.test import test_eq ``` ```python assert 'fastcore/test.py' in get_source_link(test_eq)\nassert get_source_link(test_eq).startswith('https://github.com/fastai/fastcore')\nget_source_link(test_eq) ``` -------------------------------- ### Using bunzip to Decompress .bz2 Files in Python Source: https://fastcore.fast.ai/xtras.html.md Shows how to use the `bunzip` function to decompress a `.bz2` file (`files/test.txt.bz2`). It includes setup to ensure the target file doesn't exist before decompression and cleanup afterwards. It verifies the content of the decompressed file. ```Python f = Path('files/test.txt') if f.exists(): f.unlink() bunzip('files/test.txt.bz2') t = f.open().readlines() test_eq(len(t),1) test_eq(t[0], 'test\n') f.unlink() ``` -------------------------------- ### Executing code in a new environment with fastcore Source: https://fastcore.fast.ai/basics.html.md Illustrates the use of the `exec_new` function to execute a string of code in a fresh global environment and retrieve the resulting environment dictionary. ```python g = exec_new('a=1') test_eq(g['a'], 1) ``` -------------------------------- ### Using mkdir to Create and Overwrite Directories in Python Source: https://fastcore.fast.ai/xtras.html.md Demonstrates the usage of the `mkdir` function to create a new directory. It also shows how the `overwrite=True` parameter can be used to remove an existing directory and its contents before creating a new empty one at the same path. Uses `tempfile` for a safe test environment. ```Python with tempfile.TemporaryDirectory() as d: path = Path(os.path.join(d, 'new_dir')) new_dir = mkdir(path) assert new_dir.exists() test_eq(new_dir, path) # test overwrite with open(new_dir/'test.txt', 'w') as f: f.writelines('test') test_eq(len(list(walk(new_dir))), 1) # assert file is present new_dir = mkdir(new_dir, overwrite=True) test_eq(len(list(walk(new_dir))), 0) # assert file was deleted ``` -------------------------------- ### Get Multiple Attributes as List (Python) Source: https://fastcore.fast.ai/basics.html.md Demonstrates using `getattrs` to retrieve a list of specified attributes from an object. It shows how to get multiple attribute values in a single call, useful for extracting several pieces of data simultaneously. ```python from fractions import Fraction ``` ```python getattrs(Fraction(1,2), 'numerator', 'denominator') ``` -------------------------------- ### Partitioning a Collection by Predicate with partition in Python Source: https://fastcore.fast.ai/basics.html.md This example demonstrates the `partition` function, which splits a collection into two lists based on a predicate function. The first list contains elements for which the predicate is true, and the second contains elements for which it is false. Here, it partitions a range of numbers based on whether they are odd or even. ```python ts,fs = partition(range(10), mod(2)) test_eq(fs, [0,2,4,6,8]) test_eq(ts, [1,3,5,7,9]) ``` -------------------------------- ### Get Snake-cased Class Attribute Name (Python) Source: https://fastcore.fast.ai/basics.html.md Illustrates how `class2attr` is used within a class property to get the snake-cased version of the class name, optionally stripping a specified suffix. Useful for creating default attribute names based on class hierarchy. ```python class Parent: @property def name(self): return class2attr(self, 'Parent') class ChildOfParent(Parent): pass class ParentChildOf(Parent): pass p = Parent() cp = ChildOfParent() cp2 = ParentChildOf() test_eq(p.name, 'parent') test_eq(cp.name, 'child_of') test_eq(cp2.name, 'parent_child_of') ``` -------------------------------- ### Initializing ReindexCollection with Index (Python) Source: https://fastcore.fast.ai/xtras.html.md Demonstrates how to create a ReindexCollection instance with a list and an initial index to reverse the order of elements. ```python rc=ReindexCollection(['a', 'b', 'c', 'd', 'e'], idxs=[4,3,2,1,0]) list(rc) ``` -------------------------------- ### BypassNewMeta - Bypass Example in Python Source: https://fastcore.fast.ai/meta.html.md Demonstrates BypassNewMeta when the input object's type (_TestB) matches the class's _bypass_type (_TestB). Shows that the constructor returns the original object (t2 is t), and modifications to one are reflected in the other. Requires the _T class definition. Uses test_is and test_eq which are likely testing utilities. ```python t = _TestB() t2 = _T(t) t2.new_attr = 15 test_is(t, t2) # since t2 just references t these will be the same test_eq(t.new_attr, t2.new_attr) # likewise, chaning an attribute on t will also affect t2 because they both point to the same object. t.new_attr = 9 test_eq(t2.new_attr, 9) ``` -------------------------------- ### Converting Masks/Indices with mask2idxs in Python Source: https://fastcore.fast.ai/foundation.html.md This snippet provides examples of the `mask2idxs` function. It shows how the function converts a boolean list, a boolean NumPy array, and a list of integers into a list of indices, typically represented as a fastcore `L` object. The examples use `test_eq` to verify the correctness of the conversion for different input types. ```python test_eq(mask2idxs([False,True,False,True]), [1,3]) test_eq(mask2idxs(array([False,True,False,True])), [1,3]) test_eq(mask2idxs(array([1,2,3])), [1,2,3]) ``` -------------------------------- ### Loading Pickle File fastcore Python Source: https://fastcore.fast.ai/xtras.html.md Describes the `load_pickle` function which loads data from a pickle file, supporting different compression formats. The example demonstrates saving data to a temporary file with various suffixes (.pkl, .bz2, .gz) and then loading it back to verify the function's correctness. ```python for suf in '.pkl','.bz2','.gz': # delete=False is added for Windows # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file with tempfile.NamedTemporaryFile(suffix=suf, delete=False) as f: fn = Path(f.name) save_pickle(fn, 't') t = load_pickle(fn) f.close() test_eq(t,'t') ``` -------------------------------- ### Customizing Path Representation with Path.__repr__ (Python) Source: https://fastcore.fast.ai/xtras.html.md Shows how the `__repr__` method of `Path` is updated in fastcore to display paths relative to a defined `Path.BASE_PATH`. This example sets a base path temporarily and asserts the expected relative string representation. ```python t = ipy_files[0].absolute() try: Path.BASE_PATH = t.parent.parent test_eq(repr(t), f"Path('nbs/{t.name}')") finally: Path.BASE_PATH = None ``` -------------------------------- ### Generating Log-Stepped Arrays with even_mults in Python Source: https://fastcore.fast.ai/basics.html.md Demonstrates the usage of the even_mults function. It shows how to generate a list of numbers that are logarithmically spaced between a start and stop value, with a specified number of steps. Includes test cases for different inputs. Requires fastcore.basics. ```python test_eq(even_mults(2,8,3), [2,4,8]) test_eq(even_mults(2,32,5), [2,4,8,16,32]) test_eq(even_mults(2,8,1), 8) ``` -------------------------------- ### Verifying Config Read Source: https://fastcore.fast.ai/foundation.html.md Tests reading a configuration file back after creation and checks specific values to ensure the configuration was loaded correctly. ```python try: cfg = Config('..', 'tmp.ini', inline_comment_prefixes=('#')) finally: os.unlink('../tmp.ini') test_eq(cfg.user,'fastai') test_eq(cfg.some_num,'') ``` -------------------------------- ### Using EventTimer Class in Python Source: https://fastcore.fast.ai/xtras.html.md Explains the `EventTimer` class, its initialization parameters (`store`, `span`), and how to add events and retrieve event count and frequency. Mentions the code demonstrates creating an instance, adding events, and printing statistics. ```python # Random wait function for testing def _randwait(): yield from (sleep(random.random()/200) for _ in range(100)) c = EventTimer(store=5, span=0.03) for o in _randwait(): c.add(1) print(f'Num Events: {c.events}, Freq/sec: {c.freq:.01f}') print('Most recent: ', sparkline(c.hist), *L(c.hist).map('{:.01f}')) ``` -------------------------------- ### Basic fastcore L creation and indexing Source: https://fastcore.fast.ai/foundation.html.md Shows how to create an L object from a range and perform basic list operations like equality checks, reversal, single item assignment, and multiple item assignment using tuple/list indexing. ```python t = L(range(12)) test_eq(t, list(range(12))) test_ne(t, list(range(11))) t.reverse() test_eq(t[0], 11) t[3] = "h" test_eq(t[3], "h") t[3,5] = ("j","k") test_eq(t[3,5], ["j","k"]) test_eq(t, L(t)) test_eq(L(L(1,2),[3,4]), ([1,2],[3,4])) t ``` -------------------------------- ### Using bind with Argument Reordering (arg0, arg1) Source: https://fastcore.fast.ai/basics.html.md Demonstrates using `fastcore.bind` to create a partial application of `myfn` where positional arguments are reordered using `arg0` and `arg1` placeholders, and a keyword argument `e` is set. ```python test_eq(bind(myfn, arg1, 17, arg0, e=3)(19,14), (14,17,19,1,3)) ``` -------------------------------- ### Getting Unique Items with L.unique in Python Source: https://fastcore.fast.ai/foundation.html.md Return the unique items from an L object, preserving the original order of the first appearance of each item. ```python test_eq(L(4,1,2,3,4,4).unique(), [4,1,2,3]) ``` -------------------------------- ### Testing Inequality with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Illustrates the use of `test_ne` to assert that two values are not equal. Provides various examples with lists, arrays, and dictionaries. ```python test_ne([1,2],[1]) test_ne([1,2],[1,3]) test_ne(array([1,2]),array([1,1])) test_ne(array([1,2]),array([1,1])) test_ne([array([1,2]),3],[array([1,2])]) test_ne([3,4],array([3])) test_ne([3,4],array([3,5])) test_ne(dict(a=1,b=2), ['a', 'b']) test_ne(['a', 'b'], dict(a=1,b=2)) ``` -------------------------------- ### Importing asyncio Module - Python Source: https://fastcore.fast.ai/parallel.html.md This snippet imports the `asyncio` library, which is required for asynchronous programming in Python. It is a necessary dependency for the subsequent example demonstrating the `parallel_async` function. ```python import asyncio ``` -------------------------------- ### Creating Class with Fields and Functions using mk_class in Python Source: https://fastcore.fast.ai/basics.html.md Shows creating a class `_t` with a positional field 'a', inheriting from `dict`, setting a docstring, and adding a method `foo`. Demonstrates instantiation with positional and keyword arguments. ```python def foo(self): return 1 mk_class('_t', 'a', sup=dict, doc='test doc', funcs=foo) t = _t(3, b=2) test_eq(t.a, 3) test_eq(t.b, 2) test_eq(t.foo(), 1) test_eq(t.__doc__, 'test doc') t ``` -------------------------------- ### Defining a Function with Unsorted Arguments Source: https://fastcore.fast.ai/meta.html.md Defines a simple Python function with keyword arguments that are not in alphabetical order. This function is used in the subsequent example to demonstrate argument sorting. ```python def unsortedfunc(c=3,a=1,b=2): pass unsortedfunc ``` -------------------------------- ### Applying delegates with keep=True in Python Source: https://fastcore.fast.ai/meta.html.md This example shows how to use the `delegates` decorator with the `keep=True` argument. This includes the delegated parameters in the signature while also retaining the `**kwargs` parameter. ```Python @delegates(baz, keep=True) def foo(c, a, **kwargs): return c + baz(a, **kwargs) ``` -------------------------------- ### Adding Docstrings with add_docs (Python) Source: https://fastcore.fast.ai/foundation.html.md Demonstrates a simple class definition before applying docstrings using the `add_docs` function. ```python class T: def foo(self): pass def bar(self): pass ``` -------------------------------- ### Getting Number of CPUs with num_cpus in Python Source: https://fastcore.fast.ai/basics.html.md Shows how to call the num_cpus function to retrieve the number of available CPU cores on the system. Requires fastcore.basics. ```python num_cpus() ``` -------------------------------- ### Running Commands Returning Bytes - Python Source: https://fastcore.fast.ai/xtras.html.md Shows how to use `run` with the `as_bytes=True` argument to receive the raw byte output from the command instead of the automatically decoded string output. ```python if sys.platform == 'win32': test_eq(run('cmd /c echo hi'), 'hi') else: test_eq(run('echo hi', as_bytes=True), b'hi\n') ``` -------------------------------- ### Defining Classes for Composition (Initial) - Python Source: https://fastcore.fast.ai/basics.html.md Defines two simple classes, _WebPage and _ProductPage, to illustrate a composition scenario where accessing attributes of the composed object (_WebPage instance within _ProductPage) requires explicit chaining (e.g., p.page.author). This setup highlights the problem that GetAttr solves. ```python class _WebPage: def __init__(self, title, author="Jeremy"): self.title,self.author = title,author class _ProductPage: def __init__(self, page, price): self.page,self.price = page,price page = _WebPage('Soap', author="Sylvain") p = _ProductPage(page, 15.0) ``` -------------------------------- ### Testing Help Flag with ArgumentParser in Python Source: https://fastcore.fast.ai/script.html.md Illustrates how the `ArgumentParser` generated by `anno_parser` correctly handles the standard `-h` or `--help` flag, printing the generated help message. ```python try: p.parse_args(['-h']) except: pass ``` -------------------------------- ### Using the startthread decorator Source: https://fastcore.fast.ai/parallel.html.md Illustrates the `@startthread` decorator, which is similar to `@threaded` but automatically starts the function execution in a new thread immediately upon the function's definition. ```python @startthread def _(): time.sleep(0.05) print("second") @startthread def _(): time.sleep(0.01) print("first") time.sleep(0.1) ``` -------------------------------- ### Using bind like partial (No Reordering) Source: https://fastcore.fast.ai/basics.html.md Demonstrates using `fastcore.bind` without any argument reordering, effectively behaving like Python's built-in `functools.partial`. ```python test_eq(bind(myfn)(17,19,14), (17,19,14,1,2)) ``` -------------------------------- ### Using map_ex with bind-like Arguments Source: https://fastcore.fast.ai/basics.html.md Shows how `fastcore.map_ex` supports the same `arg` parameters as `bind`. This allows using placeholders like `arg0` within the function `f` passed to `map_ex`. ```python def f(a=None,b=None): return b test_eq(map_ex(t, f, b=arg0), range(4)) ``` -------------------------------- ### Creating ArgumentParser from Function with Param Annotations in Python Source: https://fastcore.fast.ai/script.html.md Demonstrates how to define a function using `fastcore.script.Param` annotations to specify argument details and then use `anno_parser` to automatically generate an `argparse.ArgumentParser`. It shows how required and optional arguments, types, defaults, and actions like 'version' are handled. ```python _en = str_enum('_en', 'aa','bb','cc') def f(required:Param("Required param", int), a:Param("param 1", bool_arg), v:Param("Print version", action='version', version='%(prog)s 2.0.0'), b:Param("param 2", str)="test", c:Param("param 3", _en)=_en.aa): "my docs" ... p = anno_parser(f, 'progname') p.print_help() ``` -------------------------------- ### Testing Iterability with is_iter (Python) Source: https://fastcore.fast.ai/foundation.html.md Provides examples using `is_iter` to test whether various Python objects, including lists, NumPy arrays, and generators, are considered iterable. ```python assert is_iter([1]) assert not is_iter(array(1)) assert is_iter(array([1,2])) assert (o for o in range(3)) ``` -------------------------------- ### Using fastcore.annotations for Broader Annotation Access Source: https://fastcore.fast.ai/basics.html.md Illustrates how `fastcore.annotations` retrieves annotations from various objects (`_T` class, instance, `__init__` method, function `f`), supporting more cases than `type_hints`, while returning empty for types without annotations. ```python for o in _T,_T(),_T.__init__,f: test_eq(annotations(o), exp) assert not annotations(int) assert not annotations(print) ``` -------------------------------- ### Testing Shuffled Sequences with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Illustrates how to use `test_shuffled` to assert that two sequences contain the same elements but potentially in a different order. Provides examples with lists and strings. ```python a = list(range(50)) b = copy(a) random.shuffle(b) test_shuffled(a,b) test_fail(lambda:test_shuffled(a,a)) ``` ```python a = 'abc' b = 'abcabc' test_fail(lambda:test_shuffled(a,b)) ``` ```python a = ['a', 42, True] b = [42, True, 'a'] test_shuffled(a,b) ``` -------------------------------- ### Importing datetime Module - Python Source: https://fastcore.fast.ai/parallel.html.md This simple snippet imports the `datetime` class from Python's standard `datetime` module. It is a prerequisite for the subsequent code example that measures execution time. ```python from datetime import datetime ``` -------------------------------- ### Applying Docstrings with add_docs (Python) Source: https://fastcore.fast.ai/foundation.html.md Shows how to use the `add_docs` function to assign docstrings to a class and its methods after the class has been defined. ```python add_docs(T, cls_doc="A docstring for the class.", foo="The foo method.", bar="The bar method.") ``` -------------------------------- ### Getting Function Return Annotations with fastcore.anno_ret Source: https://fastcore.fast.ai/basics.html.md Demonstrates how `fastcore.anno_ret` extracts the return type annotation from functions, including standard types and complex types like `typing.Tuple`. ```python def f(x) -> float: return x test_eq(anno_ret(f), float) def f(x) -> typing.Tuple[float,float]: return x assert anno_ret(f)==typing.Tuple[float,float] ``` -------------------------------- ### Viewing Function Help with Param Annotations Source: https://fastcore.fast.ai/script.html.md Calls the built-in `help()` function on a function annotated with `Param` to show how the annotations are displayed in the function's help documentation. ```python help(f) ``` -------------------------------- ### Reading Multiple Config Files with extra_files Source: https://fastcore.fast.ai/foundation.html.md Shows how to merge configurations from multiple files by specifying their paths in the `extra_files` parameter during Config initialization. Values from later files override those from earlier ones. ```python with tempfile.TemporaryDirectory() as d: a = Config(d, 'a.ini', {'a':0,'b':0}) b = Config(d, 'b.ini', {'a':1,'c':0}) c = Config(d, 'c.ini', {'a':2,'d':0}, extra_files=[a.config_file,b.config_file]) test_eq(c.d, {'a':'2','b':'0','c':'0','d':'0'}) ``` -------------------------------- ### Testing Approximate Equality with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Shows how to use `test_close` to assert that two numerical values or sequences are within a specified epsilon of each other. Includes examples with lists and NumPy arrays. ```python test_close(1,1.001,eps=1e-2) test_fail(lambda: test_close(1,1.001)) test_close([-0.001,1.001], [0.,1.], eps=1e-2) test_close(np.array([-0.001,1.001]), np.array([0.,1.]), eps=1e-2) test_close(array([-0.001,1.001]), array([0.,1.]), eps=1e-2) ``` -------------------------------- ### Using the types Parameter for Type Conversion Source: https://fastcore.fast.ai/foundation.html.md Illustrates how to automatically convert configuration values to specified Python types (like Path, bool, int) using the `types` dictionary provided during initialization. ```python _types = dict(some_path=Path, some_bool=bool, some_num=int) cfg = Config('..', 'tmp.ini', create=_d, save=False, types=_types) test_eq(cfg.user,'fastai') test_eq(cfg['some_path'].resolve(), (Path('..')/'test').resolve()) test_eq(cfg.get('some_num'), 3) ``` -------------------------------- ### Using ignore_exceptions Context Manager in Python Source: https://fastcore.fast.ai/basics.html.md Illustrates the use of the `ignore_exceptions` context manager to suppress exceptions raised within its block. The example shows an `Exception` being raised but ignored. ```python with ignore_exceptions(): # Exception will be ignored raise Exception ``` -------------------------------- ### Iterating NS Instance - fastcore - Python Source: https://fastcore.fast.ai/basics.html.md Shows how to iterate over the keys of an NS instance. ```python list(d) ``` -------------------------------- ### Testing Figure Existence with fastcore (Python) Source: https://fastcore.fast.ai/test.html.md Illustrates how to use `test_fig_exists` to assert that a matplotlib Axes object contains a displayed figure. Includes setup code to create and display a figure. ```python fig,ax = plt.subplots() ax.imshow(array(im)); ``` ```python test_fig_exists(ax) ``` -------------------------------- ### Generate Sparkline (Python) Source: https://fastcore.fast.ai/xtras.html.md Shows how to create a text-based sparkline visualization from a list of numerical data using `sparkline`. Demonstrates handling `None` values and optionally treating zero as empty, as well as setting explicit min/max bounds. ```python data = [9,6,None,1,4,0,8,15,10]\nprint(f'without "empty_zero": {sparkline(data, empty_zero=False)}')\nprint(f' with "empty_zero": {sparkline(data, empty_zero=True )}') ``` ```python sparkline([1,2,3,400], mn=0, mx=3) ``` -------------------------------- ### fastuple Type and Equality Checks Source: https://fastcore.fast.ai/basics.html.md Shows how to check the type of a `fastuple` instance and perform equality (`test_eq`, `test_eq_type`) and inequality (`test_ne`) comparisons. Also demonstrates creating an empty `fastuple`. ```python test_eq(type(fastuple(1)), fastuple) test_eq_type(fastuple(1,2), fastuple(1,2)) test_ne(fastuple(1,2), fastuple(1,3)) test_eq(fastuple(), ()) ``` -------------------------------- ### Using fastcore typed decorator with Union types Source: https://fastcore.fast.ai/basics.html.md Demonstrates how to specify multiple allowed types for an argument using a tuple (or `|` in Python 3.10+). Shows examples with and without casting enabled. ```python @typed def discount(price:int|float, pct:float): return (1-pct) * price assert 90.0 == discount(100.0, .1) @typed(cast=True) def discount(price:int|None, pct:float): return (1-pct) * price assert 90.0 == discount(100.0, .1) ``` -------------------------------- ### Getting Request Summary with fastcore.net (Python) Source: https://fastcore.fast.ai/net.html.md Generate a summary dictionary for a `Request` object, including its full URL, headers, method, and data. Allows specifying headers to skip from the summary output. ```python req.summary(skip='Hdr1') ``` -------------------------------- ### Importing Modules for XML Processing - Python Source: https://fastcore.fast.ai/xml.html.md Imports standard Python libraries like `pprint` and modules from `IPython.display` and `fastcore.test` for testing and display purposes within the documentation context. ```python from IPython.display import Markdown from pprint import pprint from fastcore.test import test_eq ```