Skip to content

UnboundLocalError when importing torch.cuda #254

@jcjohnson

Description

@jcjohnson

This code

import torch

def foo():
  print torch
  import torch.cuda
foo()

crashes on the print statement with UnboundLocalError: local variable 'torch' referenced before assignment.

All of the following permutations work without a problem:

import torch

def foo():
  import torch.cuda
  print torch
foo()
import torch
print torch
import torch.cuda
import torch
import torch.cuda
print torch

My use case for this pattern is to only import torch.cuda when command-flags request the usage of a GPU; in Torch7 I've used this pattern because users without CUDA installed were unable to install cutorch or cunn, so they had to be conditionally imported. Is this still a concern in PyTorch?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions