How to add PyTorch as a requirement in setup.py?

I am trying to build my python package which uses torch and torchvision. As they cannot be installed directly with say pip install torch, how to add them as a requirement in setup.py?

Hey. Here is one of the solutions from GitHub:

  1. They have requierments.txt
  2. They define helper function to read from requierments.txt into list of strings like this:
def _load_requirements(path_dir: str , file_name: str = 'requirements.txt', comment_char: str = '#') -> List[str]:
    """Load requirements from a file
    >>> _load_requirements(PROJECT_ROOT)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    ['numpy...', 'torch...', ...]
    """
    with open(os.path.join(path_dir, file_name), 'r') as file:
        lines = [ln.strip() for ln in file.readlines()]
    reqs = []
    for ln in lines:
        # filer all comments
        if comment_char in ln:
            ln = ln[:ln.index(comment_char)].strip()
        # skip directly installed dependencies
        if ln.startswith('http'):
            continue
        if ln:  # if requirement is not empty
            reqs.append(ln)
    return reqs
  1. In the setup.py they use this helper function to provide argument for setup function:
setup(
    ...
    install_requires=_load_requirements(PATH_ROOT),
    ....
)

Should work fine :slight_smile:

2 Likes

Will try to implement this. Thanks!