{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "UCL\n", "\n", "\n", "[](010_Python_Introduction.ipynb)\n", "[](004_Accounts.ipynb)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 005 Packages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction\n", "\n", "\n", "### Purpose\n", "\n", "In this session, we will learn about importing packages into our code. \n", "\n", "### Prerequisites\n", "\n", "You will need some understanding of the following:\n", "\n", "\n", "* [001 Using Notebooks](001_Notebook_use.ipynb)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `import`\n", "\n", "Python comes with a good deal of built-in functionality, and that is what we have mainly been using to date. Often though, we need to classes or functions from other packages. Provided these packages are installed in our distribution, we can use them.\n", "\n", "The system you should have setup for you includes the packages listed in [`environment.yml`](copy/environment.yml).\n", "\n", "When we want to use a non-standard Python package, we must first import it into our codebase. This is done with the `import` directive, e.g.:\n", "\n", " import yaml\n", " \n", "to import a library called `yaml`. We can then access some function `XX` functions in the package as `yaml.XX`. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function safe_load in module yaml:\n", "\n", "safe_load(stream)\n", " Parse the first YAML document in a stream\n", " and produce the corresponding Python object.\n", " \n", " Resolve only basic YAML tags. This is known\n", " to be safe for untrusted input.\n", "\n" ] } ], "source": [ "import yaml\n", "\n", "help(yaml.safe_load)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will learn in [Python Introduction](010_Python_Introduction.ipynb) that classes start with a capital letter. So, if we see a variable in `Python such as `path`, we should recognise that as a class.\n", "\n", "Sometimes we wish to only import certain functions or sub-packages. This is done with the `from` directive. For example to import the class `Path` from the package `pathlib`\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The class `Path` is now available directly as `Path`, whereas if we had imported it as:\n", "\n", " import pathlib\n", " \n", "we would have needed to refer to it as `pathlib.Path`. This will over-ride any current definition of the class `Path` in the current code, so be careful not to over-ride things you don't mean to." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 1\n", "\n", "Make and run a Python cell that imports the class `Loader` from the package `yaml` and show the help text for this." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "scrolled": true, "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class Loader in module yaml.loader:\n", "\n", "class Loader(yaml.reader.Reader, yaml.scanner.Scanner, yaml.parser.Parser, yaml.composer.Composer, yaml.constructor.Constructor, yaml.resolver.Resolver)\n", " | Loader(stream)\n", " | \n", " | Method resolution order:\n", " | Loader\n", " | yaml.reader.Reader\n", " | yaml.scanner.Scanner\n", " | yaml.parser.Parser\n", " | yaml.composer.Composer\n", " | yaml.constructor.Constructor\n", " | yaml.constructor.UnsafeConstructor\n", " | yaml.constructor.FullConstructor\n", " | yaml.constructor.SafeConstructor\n", " | yaml.constructor.BaseConstructor\n", " | yaml.resolver.Resolver\n", " | yaml.resolver.BaseResolver\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, stream)\n", " | Initialize the scanner.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.reader.Reader:\n", " | \n", " | check_printable(self, data)\n", " | \n", " | determine_encoding(self)\n", " | \n", " | forward(self, length=1)\n", " | \n", " | get_mark(self)\n", " | \n", " | peek(self, index=0)\n", " | \n", " | prefix(self, length=1)\n", " | \n", " | update(self, length)\n", " | \n", " | update_raw(self, size=4096)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from yaml.reader.Reader:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.reader.Reader:\n", " | \n", " | NON_PRINTABLE = re.compile('[^\\t\\n\\r -~\\x85\\xa0-\\ud7ff\\ue000-�𐀀-\\U0010...\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.scanner.Scanner:\n", " | \n", " | add_indent(self, column)\n", " | \n", " | check_block_entry(self)\n", " | \n", " | check_directive(self)\n", " | \n", " | check_document_end(self)\n", " | \n", " | check_document_start(self)\n", " | \n", " | check_key(self)\n", " | \n", " | check_plain(self)\n", " | \n", " | check_token(self, *choices)\n", " | \n", " | check_value(self)\n", " | \n", " | fetch_alias(self)\n", " | \n", " | fetch_anchor(self)\n", " | \n", " | fetch_block_entry(self)\n", " | \n", " | fetch_block_scalar(self, style)\n", " | \n", " | fetch_directive(self)\n", " | \n", " | fetch_document_end(self)\n", " | \n", " | fetch_document_indicator(self, TokenClass)\n", " | \n", " | fetch_document_start(self)\n", " | \n", " | fetch_double(self)\n", " | \n", " | fetch_flow_collection_end(self, TokenClass)\n", " | \n", " | fetch_flow_collection_start(self, TokenClass)\n", " | \n", " | fetch_flow_entry(self)\n", " | \n", " | fetch_flow_mapping_end(self)\n", " | \n", " | fetch_flow_mapping_start(self)\n", " | \n", " | fetch_flow_scalar(self, style)\n", " | \n", " | fetch_flow_sequence_end(self)\n", " | \n", " | fetch_flow_sequence_start(self)\n", " | \n", " | fetch_folded(self)\n", " | \n", " | fetch_key(self)\n", " | \n", " | fetch_literal(self)\n", " | \n", " | fetch_more_tokens(self)\n", " | \n", " | fetch_plain(self)\n", " | \n", " | fetch_single(self)\n", " | \n", " | fetch_stream_end(self)\n", " | \n", " | fetch_stream_start(self)\n", " | \n", " | fetch_tag(self)\n", " | \n", " | fetch_value(self)\n", " | \n", " | get_token(self)\n", " | \n", " | need_more_tokens(self)\n", " | \n", " | next_possible_simple_key(self)\n", " | \n", " | peek_token(self)\n", " | \n", " | remove_possible_simple_key(self)\n", " | \n", " | save_possible_simple_key(self)\n", " | \n", " | scan_anchor(self, TokenClass)\n", " | \n", " | scan_block_scalar(self, style)\n", " | \n", " | scan_block_scalar_breaks(self, indent)\n", " | \n", " | scan_block_scalar_ignored_line(self, start_mark)\n", " | \n", " | scan_block_scalar_indentation(self)\n", " | \n", " | scan_block_scalar_indicators(self, start_mark)\n", " | \n", " | scan_directive(self)\n", " | \n", " | scan_directive_ignored_line(self, start_mark)\n", " | \n", " | scan_directive_name(self, start_mark)\n", " | \n", " | scan_flow_scalar(self, style)\n", " | \n", " | scan_flow_scalar_breaks(self, double, start_mark)\n", " | \n", " | scan_flow_scalar_non_spaces(self, double, start_mark)\n", " | \n", " | scan_flow_scalar_spaces(self, double, start_mark)\n", " | \n", " | scan_line_break(self)\n", " | \n", " | scan_plain(self)\n", " | \n", " | scan_plain_spaces(self, indent, start_mark)\n", " | \n", " | scan_tag(self)\n", " | \n", " | scan_tag_directive_handle(self, start_mark)\n", " | \n", " | scan_tag_directive_prefix(self, start_mark)\n", " | \n", " | scan_tag_directive_value(self, start_mark)\n", " | \n", " | scan_tag_handle(self, name, start_mark)\n", " | \n", " | scan_tag_uri(self, name, start_mark)\n", " | \n", " | scan_to_next_token(self)\n", " | \n", " | scan_uri_escapes(self, name, start_mark)\n", " | \n", " | scan_yaml_directive_number(self, start_mark)\n", " | \n", " | scan_yaml_directive_value(self, start_mark)\n", " | \n", " | stale_possible_simple_keys(self)\n", " | \n", " | unwind_indent(self, column)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.scanner.Scanner:\n", " | \n", " | ESCAPE_CODES = {'U': 8, 'u': 4, 'x': 2}\n", " | \n", " | ESCAPE_REPLACEMENTS = {'\\t': '\\t', ' ': ' ', '\"': '\"', '/': '/', '0': ...\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.parser.Parser:\n", " | \n", " | check_event(self, *choices)\n", " | \n", " | dispose(self)\n", " | \n", " | get_event(self)\n", " | \n", " | parse_block_mapping_first_key(self)\n", " | \n", " | parse_block_mapping_key(self)\n", " | \n", " | parse_block_mapping_value(self)\n", " | \n", " | parse_block_node(self)\n", " | \n", " | parse_block_node_or_indentless_sequence(self)\n", " | \n", " | parse_block_sequence_entry(self)\n", " | \n", " | parse_block_sequence_first_entry(self)\n", " | \n", " | parse_document_content(self)\n", " | \n", " | parse_document_end(self)\n", " | \n", " | parse_document_start(self)\n", " | \n", " | parse_flow_mapping_empty_value(self)\n", " | \n", " | parse_flow_mapping_first_key(self)\n", " | \n", " | parse_flow_mapping_key(self, first=False)\n", " | \n", " | parse_flow_mapping_value(self)\n", " | \n", " | parse_flow_node(self)\n", " | \n", " | parse_flow_sequence_entry(self, first=False)\n", " | \n", " | parse_flow_sequence_entry_mapping_end(self)\n", " | \n", " | parse_flow_sequence_entry_mapping_key(self)\n", " | \n", " | parse_flow_sequence_entry_mapping_value(self)\n", " | \n", " | parse_flow_sequence_first_entry(self)\n", " | \n", " | parse_implicit_document_start(self)\n", " | \n", " | parse_indentless_sequence_entry(self)\n", " | \n", " | parse_node(self, block=False, indentless_sequence=False)\n", " | \n", " | parse_stream_start(self)\n", " | \n", " | peek_event(self)\n", " | \n", " | process_directives(self)\n", " | \n", " | process_empty_scalar(self, mark)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.parser.Parser:\n", " | \n", " | DEFAULT_TAGS = {'!': '!', '!!': 'tag:yaml.org,2002:'}\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.composer.Composer:\n", " | \n", " | check_node(self)\n", " | \n", " | compose_document(self)\n", " | \n", " | compose_mapping_node(self, anchor)\n", " | \n", " | compose_node(self, parent, index)\n", " | \n", " | compose_scalar_node(self, anchor)\n", " | \n", " | compose_sequence_node(self, anchor)\n", " | \n", " | get_node(self)\n", " | \n", " | get_single_node(self)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.constructor.UnsafeConstructor:\n", " | \n", " | find_python_module(self, name, mark)\n", " | \n", " | find_python_name(self, name, mark)\n", " | \n", " | make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False)\n", " | \n", " | set_python_instance_state(self, instance, state)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.constructor.UnsafeConstructor:\n", " | \n", " | yaml_multi_constructors = {'tag:yaml.org,2002:python/module:': [0-9][0-9][0-9][0-9])\\n ......\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.constructor.BaseConstructor:\n", " | \n", " | check_data(self)\n", " | \n", " | check_state_key(self, key)\n", " | Block special attributes/methods from being set in a newly created\n", " | object, to prevent user-controlled methods from being called during\n", " | deserialization\n", " | \n", " | construct_document(self, node)\n", " | \n", " | construct_object(self, node, deep=False)\n", " | \n", " | construct_pairs(self, node, deep=False)\n", " | \n", " | construct_sequence(self, node, deep=False)\n", " | \n", " | get_data(self)\n", " | \n", " | get_single_data(self)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods inherited from yaml.constructor.BaseConstructor:\n", " | \n", " | add_constructor(tag, constructor) from builtins.type\n", " | \n", " | add_multi_constructor(tag_prefix, multi_constructor) from builtins.type\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.resolver.Resolver:\n", " | \n", " | yaml_implicit_resolvers = {'': [('tag:yaml.org,2002:null', re.compile(...\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from yaml.resolver.BaseResolver:\n", " | \n", " | ascend_resolver(self)\n", " | \n", " | check_resolver_prefix(self, depth, path, kind, current_node, current_index)\n", " | \n", " | descend_resolver(self, current_node, current_index)\n", " | \n", " | resolve(self, kind, value, implicit)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods inherited from yaml.resolver.BaseResolver:\n", " | \n", " | add_implicit_resolver(tag, regexp, first) from builtins.type\n", " | \n", " | add_path_resolver(tag, path, kind=None) from builtins.type\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from yaml.resolver.BaseResolver:\n", " | \n", " | DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'\n", " | \n", " | DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'\n", " | \n", " | DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'\n", " | \n", " | yaml_path_resolvers = {}\n", "\n" ] } ], "source": [ "# ANSWER\n", "# \n", "from yaml import Loader\n", "help(Loader)\n", "\n", "# This above is a correct answer \n", "# you could have done as below\n", "# but that doesnt quite answer the question correctly\n", "# as it specificaly asks you to import Loader\n", "#\n", "#import yaml\n", "#help(yaml.Loader)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "In this section, we have learned how to import packages using `import` and `from`.\n", " \n", "| command | purpose | \n", "|---|---|\n", "| `import yaml` | import the package `yaml`|\n", "| `from pathlib import Path` | import the method/ class `Path` from the package `pathlib` | \n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "[](010_Python_Introduction.ipynb)\n", "[](004_Accounts.ipynb)\n", "\n" ] } ], "metadata": { "kernelspec": { "display_name": "conda env:geog0111-geog0111", "language": "python", "name": "conda-env-geog0111-geog0111-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.13" } }, "nbformat": 4, "nbformat_minor": 4 }