Link Search Menu Expand Document

Python Style Guide

Intro

Python is the main dynamic language used at Grove. This style guide is a list of dos and don’ts for Python programs. In short this document’s goal is to help us BE CONSISTENT.

The Zen of Python

The Zen of Python is a good starting point for code quality guidelines. Although they are sometimes self-contradictory, they provide the few principles that are the basis for good Python development.

Don’t be a zealot about these, but be sure to understand what they are and how to employ them.

$ python -c 'import this'
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Tooling

In order to help us enforce a unified style standard we utilize pre-commit hooks to run formatters, linters, and typecheckers so we can avoid having wasted arguments on niche little details about code style.

Commit Hook Installation

  1. Install the pre-commit utility to your local machine through pip.

     $ pip install --user pre-commit
     Collecting pre-commit
       Using cached pre_commit-2.0.1-py2.py3-none-any.whl (170 kB)
     ...
    
  2. Within the repositories root directory, install the hooks with pre-commit.

     $ pre-commit install
     pre-commit installed at .git/hooks/pre-commit
    

Now, with these hooks installed, everytime you try to commit a code change, the installed hooks will run and alter your changes to enforce code style. This will mostly make new deltas to your existing deltas and ask you to add the new stylistic changes to your changeset and re-commit.

pre-commit usage

Formatters

For formatting our code we utilize black as our opinionated code formatter so that we don’t have to argue about the specifics of a coding style. The black tool does not define standards for everything, but it does handle 90% of common stylistic Python arguments so that we don’t have to think about them.

For sorting imports we utilize isort so that we can avoid having to maintain our imports in a readable manner. Along with this, we need to maintain our list of third-party packages in our isort configuration which is where we utilize the seed-isort-config pre-commit hook.

Linters

For linting our code we utilize flake8 along with the flake8-docstrings plugin to find common errors and warnings about our software.

Typecheckers

For typechecking our code we utilize mypy.

Semicolons

Do not use semicolons to terminate your lines. And do not use semicolons to put two statements on the same line.

Just don’t use semicolons.

Naming

Python filenames must have a .py extension and must not contain dashes (-). This allows them to be imported and unittested. If you want an executable to be accessible without the extension, use a symbolic link or a simple bash wrapper containing exec "$0.py" "$@".

Type Public Internal
Packages lower_with_under  
Modules lower_with_under _lower_with_under
Classes CapWords _CapWords
Exceptions CapWords  
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under _lower_with_under
Instance Variables lower_with_under _lower_with_under (protected)
Method Names lower_with_under() _lower_with_under() (protected)
Function/Method Parameters lower_with_under  
Local Variables lower_with_under  

Function names, variable names, and filenames should be descriptive; eschew abbreviation. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.

Always use a .py filename extension. Never use dashes.

Names to Avoid

  • Single character names should almost never be used other than the occasional use of _ for throwaway variables (which should never be accessed again).
  • Dashes (-) in any package/module name.
  • __double_leading_and_trailing_underscore__ names (which are reserved by Python).

Naming Conventions

  • “Internal” means internal to a module, or protected or private within a class.
  • Prepending a single underscore (_) has some support for protecting module variables and functions (not included with from module import * although you should never use wildcard imports). While prepending a double underscore (__ aka “dunder”) to an instance variable or method effectively makes the variable or method private to its class (using name mangling) we discourage its use as it impacts readability and testability and isn’t really private.
  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
  • Use CapWords for class names, but lower_with_under for module names. Although there are some old modules named CapWords.py, this is now discouraged because it’s confusing when the module happens to be named after a class. (“wait – did I write import StringIO or from StringIO import StringIO?”)
  • Underscores may appear in unittest method names starting with test_ to separate logical components of the name, even if those components use CapWords. One possible pattern is test_<MethodUnderTest>_<state>; for example test_pop_empty_stack is okay. There is no one correct way to name test methods.

Style

Python style is defined and enforced by black. This tool acts as an opinionated code formatter using common PEP-8 compatible standards which deals with indentation, line-continuation, whitespacing, and many other common sources of contention for Python style. By utilizing a pre-defined code foramtter, we can avoid many unnecessary nits when just letting the robot do much of the formatting for us.

For rules not explicitly handled by black, we define the following specs:

Line Length

Maximum line length is 140 characters.

Classes

If a class inherits from no other base classes, explicitly inherit from object. This also applies to nested classes.

class SampleClass(object):
    pass


class OuterClass(object):

    class InnerClass(object):
        pass


class ChildClass(ParentClass):
    """Explicitly inherits from another class already."""

Inheriting from object is needed to make properties work properly in Python 2 and can protect your code from potential incompatibility with Python 3. It also defines special methods that implement the default semantics of objects including __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__.

Functions / Methods

Prefer small and focused functions.

We recognize that long functions are sometimes appropriate, so no hard limit is placed on function length. If a function exceeds about 12-13 mccabe complexity checked by flake8, think about whether it can be broken up without harming the structure of the program.

Even if your complicated function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code.

You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces.

Strings

Strings should commonly be defined using double-quotes " simply because it is a standard that should be defined. Although there is not real difference between single and double quoted strings in Python, the reasoning for commonly defaulting strings to utilize double quotes is the following

In most common strings, the character ' needs to be escaped with backslashes much more frequently than the " character. For example, when defaulting to using single-quotes, you will need to escape strings such as 'don\'t', 'can\'t', etc.

It is encouraged that if if need to define a string that contains double-quotes, you should utilize single-quotes to define the string. As a general rule-of-thumb, pick the string definition that most effectively removes the necessity to introduce backslashes.

For string interpolation, always utilize Python’s literal string interpolation also termed f-strings as defined by PEP-498.

my_string = "A custom string"
f"This is my string, {my_string}"

You should also be aware of the formatting capabilities of these f-strings such as using !r, !s, and !a as replacements for manual calls to repr(), str(), and ascii() respectively. Please read through PEP-498 for more details.

Avoid using the + and += operators to accumulate a string within a loop. Since strings are immutable, this creates unnecessary temporary objects and results in quadratic rather than linear running time. Instead, add each substring to a list and "".join the list after the loop terminates (or, write each substring to a io.BytesIO buffer).

When a literal string won’t fit on a single line, use parentheses for implicit line joining. If you need to avoid embedding extra space in the string, use either concatenated single-line strings or a multi-line string with textwrap.dedent() to remove the initial space on each line:

# YES
long_string = (
    "And this too is fine if you can not accept\n"
    "extraneous leading spaces."
)

# NO
long_string = """This is pretty ugly.
Don't do this.
"""
long_string = ("And this is not recommended since you can not accept\n" +
                 "extraneous leading spaces.")
long_string = """This is not recommended since your use case can't accept
      extraneous leading spaces."""
  Yes:
  import textwrap

  long_string = textwrap.dedent("""\
      This is also fine, because textwrap.dedent()
      will collapse common leading spaces in each line.""")

Accessors

If an accessor function would be trivial, you should use public variables instead of accessor functions to avoid the extra cost of function calls in Python. When more functionality is added you can use @property to keep the syntax consistent.

Files and Sockets

Explicitly close files and sockets when done with them.

Leaving files, sockets or other file-like objects open unnecessarily has many downsides:

  • They may consume limited system resources, such as file descriptors. Code that deals with many such objects may exhaust those resources unnecessarily if they’re not returned to the system promptly after use.
  • Holding files open may prevent other actions such as moving or deleting them.
  • Files and sockets that are shared throughout a program may inadvertently be read from or written to after logically being closed. If they are actually closed, attempts to read or write from them will throw exceptions, making the problem known sooner.

Furthermore, while files and sockets are automatically closed when the file object is destructed, tying the lifetime of the file object to the state of the file is poor practice:

  • There are no guarantees as to when the runtime will actually run the file’s destructor. Different Python implementations use different memory management techniques, such as delayed Garbage Collection, which may increase the object’s lifetime arbitrarily and indefinitely.
  • Unexpected references to the file, e.g. in globals or exception tracebacks, may keep it around longer than intended.

The preferred way to manage files is using the “with” statement:

with open("hello.txt") as hello_file:
    for line in hello_file:
        print(line)

For file-like objects that do not support the “with” statement, use contextlib.closing():

import contextlib

with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
    for line in front_page:
        print(line)

Imports

Imports should be on separate lines. E.g.:

# YES
import os
import sys

# NO
import os, sys

Imports are always put at the top of the file, just after any module comments and docstrings and before module globals and constants. Imports should be grouped from most generic to least generic:

  1. Python future import statements. For example:

     from __future__ import absolute_import
     from __future__ import division
     from __future__ import print_function
    
  2. Python standard library imports. For example:

     import sys
    
  3. third-party module or package imports. For example:

     import tensorflow as tf
    
  4. Code repository sub-package imports. For example:

     from otherproject.ai import mind
    
  5. Application-specific imports that are part of the same top level sub-package as this file. For example:

     from .common.things import time_machine
    

Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module’s full package path. Code should always have a blank line between import sections.

Documentation

Python uses docstrings to document code. A docstring is a string that is the first statement in a package, module, class or function. These strings can be extracted automatically through the __doc__ member of the object and are used by pydoc. Always use the three double-quote """ format for docstrings (per PEP-257). A docstring should be organized as a summary line (one physical line) terminated by a period, question mark, or exclamation point, followed by a blank line, followed by the rest of the docstring starting at the same cursor position as the first quote of the first line. There are more formatting guidelines for docstrings below.

Since most documentation tooling is built around Sphinx-style docstrings, we use their defined format for building module, class, function, and other docstrings. One of the powerful features of this docstring style is Sphinx’s autodoc for cross-referencing between Python objects which you should make use of extensively in your docstrings.

Modules

Every file should contain encoding, copyright, and license boilerplate.

# -*- encoding: utf-8 -*-
# Copyright (c) 2020 AUTHOR <EMAIL>
# MIT License <https://choosealicense.com/licenses/mit/>

Following comment file heading boilperplace, files should start with a docstring describing the contents and usage of the module.

"""A one line summary of the module or program, terminated by a period.

Leave one blank line. The rest of this docstring should contain an overall description of the module or program.
Optionally, it may also contain a brief description of exported classes and functions and/or usage examples.

>>> foo = MyClass()
>>> bar = foo.method_name()
"""

Documenting Classes

Classes should have a docstring below the class definition describing the class. If your class has public attributes, they should be documented here with an :cvar: reference line formatted the same as function parameters.

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    :cvar bool likes_spam: A boolean indicating if we like SPAM or not.
    :cvar int eggs: An integer count of the eggs we have laid.
    """

Documenting Functions / Methods

In this section, “function” means a method, function, or generator.

A function must have a docstring, unless it meets all of the following criteria:

  • not externally visible
  • very short
  • very obvious

A docstring should give enough information to write a call to the function without reading the function’s code. The docstring should be descriptive-style ("""Fetches rows from a Bigtable.""") rather than imperative-style ("""Fetch rows from a Bigtable."""), except for @property data descriptors, which should use the same style as attributes. A docstring should describe the function’s calling syntax and its semantics, not its implementation. For tricky code, comments alongside the code are encouraged along with using docstrings.

A method that overrides a method from a base class may have a simple docstring sending the reader to its overridden method’s docstring, such as the following:

"""See base classes implementation at :meth:`.BaseClass.method_name`."""

The rationale is that there is no need to repeat in many places documentation that is already present in the base method’s docstring. When doing this, ensure that you are providing a Sphinx automodule references using the :func: or :meth: tags for quick referencing in generated documentation.

However, if the overriding method’s behavior is substantially different from the overridden method, or details need to be provided (e.g., documenting additional side effects), a docstring with at least those differences is required on the overriding method.

Certain aspects of a function should be documented in special sections, listed below. These sections can be omitted in cases where the function does not require parameters and the function’s name and signature are informative enough that it can be aptly described using a one-line docstring.

Parameters

List each parameter by name using the :param: tag. The parameter definition should be followed by the parameter type and the parameter named followed by a colon and a description of the parameter.

If the description is too long to fit on a single 88-character line, use a hanging indent of 2 or 4 spaces (be consistent with the rest of the file).

:param [type] [name]: [description]

For example:

"""
:param bool is_true: Probably should be true, defaults to True
"""

Returns

Describe the type and semantics of the return value. If the function always returns None, this section is not required.

:returns: [description]
:rtype: [type]

For example:

"""
:returns: True when the operation is successful, otherwise False
:rtype: bool
"""

Raises

List all exceptions that are relevant to the interface. You should not document exceptions that get raised if the API specified in the docstring is violated (because this would paradoxically make behavior under violation of the API part of the API).

:raises [exception_type]: [description]

For example:

"""
:raises IOError: When an error occurs when retrieving the IO device
"""
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table. Silly things may happen if
    other_silly_variable is not None.

    If a key from the keys argument is missing from the dictionary,
    then that row was not found in the table.

    :param BigTable big_table: An open BigTable instance.
    :param List[str] keys: A sequence of strings representing the key of each table row
      to fetch.
    :param Optional[str] other_silly_variable: Another optional variable, that has a
      much longer name than the other args, and which does nothing.
    :returns: A dictionary mappinng of keys to the corresponding table row data fetched.
    :rtype: Dict[str, Tuple[str, str]]
    :raises IOError: when an error occured accessing the bigtable.Table object

    >>> fetch_bigtable_rows(BigTable, ["Serak", "Zim", "Lrrr"])
    {'Serak': ('Rigel VII', 'Preparer'),
     'Zim': ('Irk', 'Invader'),
     'Lrrr': ('Omicron Persei 8', 'Emperor')}
    """

Comments

The final place to have comments is in tricky parts of the code. If you’re going to have to explain it at the next code review, you should comment it now. Complicated operations get a few lines of comments before the operations commence. Non-obvious ones get comments at the end of the line.

# We use a weighted dictionary search to find out where i is in
# the array. We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0:  # True if i is 0 or a power of 2.

To improve legibility, these comments should start at least 2 spaces away from the code with the comment character #, followed by at least one space before the text of the comment itself.

On the other hand, never describe the code. Assume the person reading the code knows Python (though not what you’re trying to do) better than you do.

# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1

Tagged Comments

Use TODO, FIXME, BUG, HACK, XXX tagged comments for code that is temporary, a short-term solution, or good-enough but not perfect. A tagged comment begins with one of the listed strings in all caps followed by a colon with the comment after the colon.

The purpose is to have a consistent comment tagging format that can be searched to find out how to get more details. One of these comments does not indicated a commitment that the person referenced via the git blame will fix the problem.

# TODO: Use a "*" here for string repetition.
# FIXME: Change this to use relations.

Punctuation, Spelling, and Grammer

Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones.

Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style.

Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal.

Type Annotations

General Rules

  • Familiarize yourself with PEP-484.
  • In methods, only annotate self, or cls if it is necessary for proper type information. e.g., @classmethod def create(cls: Type[T]) -> T: return cls()
  • If any other variable or a returned type should not be expressed, use Any.
  • You are not required to annotate all the functions in a module.
    • At least annotate your public APIs.
    • Use judgment to get to a good balance between safety and clarity on the one hand, and flexibility on the other.
    • Annotate code that is prone to type-related errors (previous bugs or complexity).
    • Annotate code that is hard to understand.
    • Annotate code as it becomes stable from a types perspective. In many cases, you can annotate all the functions in mature code without losing too much flexibility.

Line Breaking

Try to follow the existing rules. After annotating, many function signatures will become “one parameter per line”.

def my_method(
  self,
  first_var: int,
  second_var: Foo,
  third_var: Optional[Bar]
) -> int:
  ...

Always prefer breaking between variables, and not for example between variable names and type annotations. However, if everything fits on the same line, go for it.

def my_method(self, first_var: int) -> int:
  ...

If the combination of the function name, the last parameter, and the return type is too long, give the return declaration its own line.

def my_method(
    self, first_var: int
) -> Tuple[MyLongType1, MyLongType1]:
  ...

If a single name and type is too long, consider using an alias for the type. The last resort is to break after the colon and indent by 4.

# YES
def my_function(
    long_variable_name:
        long_module_name.LongTypeName,
):
  ...

# NO
def my_function(
    long_variable_name: long_module_name.
        LongTypeName,
):
  ...

Forward Declarations

If you need to use a class name from the same module that is not yet defined – for example, if you need the class inside the class declaration, or if you use a class that is defined below – use a string for the class name.

class MyClass(object):

  def __init__(
    self,
    stack: List["MyClass"]
  ):
    ...

NoneType

In the Python type system, NoneType is a “first class” type, and for typing purposes, None is an alias for NoneType. If an argument can be None, it has to be declared! You can use Union, but if there is only one other type, use Optional.

Use explicit Optional instead of implicit Optional. Earlier versions of PEP-484 allowed a: Text = None to be interpretted as a: Optional[Text] = None, but that is no longer the preferred behavior.

# YES
def func(a: Optional[Text], b: Optional[Text] = None) -> Text:
  ...

def multiple_nullable_union(a: Union[None, Text, int]) -> Text:
  ...

# NO
def nullable_union(a: Union[None, Text]) -> Text:
  ...

def implicit_optional(a: Text = None) -> Text:
  ...

Type Aliases

You can declare aliases of complex types. The name of an alias should be CapWorded. If the alias is used only in this module, it should be _Private.

For example, if the name of the module together with the name of the type is too long:

_ShortName = module_with_long_name.TypeWithLongName
ComplexMap = Mapping[Text, List[Tuple[int, int]]]

Other examples are complex nested types and multiple return variables from a function (as a tuple).

Ignoring Types

You can disable type checking on a line with the special comment # type: ignore.

Typing Variables

If an internal variable has a type that is hard or impossible to infer, you can specify its type in a couple ways.

  • Type Comments: Use a # type: comment on the end of the line

      a = SomeUndecoratedFunction()  # type: Foo
    
  • Annotated Assignments: Use a colon and type between the variable name and value, as with function arguments.

      a: Foo = SomeUndecoratedFunction()
    

Tuples vs Lists

Unlike Lists, which can only have a single type, Tuples can have either a single repeated type or a set number of elements with different types. The latter is commonly used as return type from a function.

a = [1, 2, 3]  # type: List[int]
b = (1, 2, 3)  # type: Tuple[int, ...]
c = (1, "2", 3.5,)  # type: Tuple[int, Text, float]

TypeVars

The Python type system has generics. The factory function TypeVar is a common way to use them.

Example:

from typing import List, TypeVar
T = TypeVar("T")

def next(l: List[T]) -> T:
  return l.pop()

A TypeVar can be constrained:

AddableType = TypeVar("AddableType", int, float, Text)

def add(a: AddableType, b: AddableType) -> AddableType:
  return a + b

A common predefined type variable in the typing module is AnyStr. Use it for multiple annotations that can be bytes or unicode and must all be the same type.

from typing import AnyStr

def check_length(x: AnyStr) -> AnyStr:
  if len(x) <= 42:
    return x

  raise ValueError()

String types

The proper type for annotating strings depends on what versions of Python the code is intended for.

For Python 3 only code, prefer to use str. Text is also acceptable. Be consistent in using one or the other.

For Python 2 compatible code, use Text. In some rare cases, str may make sense; typically to aid compatibility when the return types aren’t the same between the two Python versions. Avoid using unicode: it doesn’t exist in Python 3.

The reason this discrepancy exists is because str means different things depending on the Python version.

For code that deals with binary data, use bytes.

def deals_with_binary_data(x: bytes) -> bytes:
  ...

For Python 2 compatible code that processes text data (str or unicode in Python 2, str in Python 3), use Text. For Python 3 only code that process text data, prefer str.

from typing import Text


def py2_compatible(x: Text) -> Text:
  ...

def py3_only(x: str) -> str:
  ...

If the type can be either bytes or text, use Union, with the appropriate text type.

from typing import Text, Union


def py2_compatible(x: Union[bytes, Text]) -> Union[bytes, Text]:
  ...

def py3_only(x: Union[bytes, str]) -> Union[bytes, str]:
  ...

If all the string types of a function are always the same, for example if the return type is the same as the argument type in the code above, use AnyStr.

Writing it like this will simplify the process of porting the code to Python 3.

Imports For Typing

For classes from the typing module, always import the class itself. You are explicitly allowed to import multiple specific classes on one line from the typing module. Ex:

from typing import Any, Dict, Optional

Given that this way of importing from typing adds items to the local namespace, any names in typing should be treated similarly to keywords, and not be defined in your Python code, typed or not. If there is a collision between a type and an existing name in a module, import it using import x as y.

from typing import Any as AnyType

Conditional Imports

Use conditional imports only in exceptional cases where the additional imports needed for type checking must be avoided at runtime. This pattern is discouraged; alternatives such as refactoring the code to allow top level imports should be preferred.

Imports that are needed only for type annotations can be placed within an if TYPE_CHECKING: block.

  • Conditionally imported types need to be referenced as strings, to be forward compatible with Python 3.6 where the annotation expressions are actually evaluated.
  • Only entities that are used solely for typing should be defined here; this includes aliases. Otherwise it will be a runtime error, as the module will not be imported at runtime.
  • The block should be right after all the normal imports.
  • There should be no empty lines in the typing imports list.
  • Sort this list as if it were a regular imports list.
import typing

if typing.TYPE_CHECKING:
  import sketch

def f(x: "sketch.Sketch"): ...

Circular Dependencies

Circular dependencies that are caused by typing are code smells. Such code is a good candidate for refactoring. Although technically it is possible to keep circular dependencies, the build system will not let you do so because each module has to depend on the other.

Replace modules that create circular dependency imports with Any. Set an alias with a meaningful name, and use the real type name from this module (any attribute of Any is Any). Alias definitions should be separated from the last import by one line.

from typing import Any

some_mod = Any  # some_mod.py imports this module.
...

def my_method(self, var: some_mod.SomeType) -> None:
  ...

Generics

When annotating, prefer to specify type parameters for generic types; otherwise, the generics’ parameters will be assumed to be Any.

def get_names(employee_ids: List[int]) -> Dict[int, Any]:
  ...
# These are both interpreted as get_names(employee_ids: List[Any]) -> Dict[Any, Any]
def get_names(employee_ids: list) -> Dict:
  ...

def get_names(employee_ids: List) -> Dict:
  ...

If the best type parameter for a generic is Any, make it explicit, but remember that in many cases TypeVar might be more appropriate:

def get_names(employee_ids: List[Any]) -> Dict[Any, Text]:
  """Returns a mapping from employee ID to employee name for given IDs."""
T = TypeVar('T')

def get_names(employee_ids: List[T]) -> Dict[T, Text]:
  """Returns a mapping from employee ID to employee name for given IDs."""