ModuleNotFoundError: No module named '_lzma'

I’m using python 3.7.10 with torch 1.81 and torchvision 0.9.1 in my machine and while importing dset from torchvision.dataset this error shows up:

Traceback (most recent call last):
  File "", line 23, in <module>
    from dataloader import load_data
  File "/home/rdb/Prithviraj/Image-Restoration-in-Occluded-Images-using-GANs/", line 3, in <module>
    import torchvision.datasets as dset
  File "/home/rdb/.local/lib/python3.7/site-packages/torchvision/", line 7, in <module>
    from torchvision import datasets
  File "/home/rdb/.local/lib/python3.7/site-packages/torchvision/datasets/", line 6, in <module>
    from .mnist import MNIST, EMNIST, FashionMNIST, KMNIST, QMNIST
  File "/home/rdb/.local/lib/python3.7/site-packages/torchvision/datasets/", line 11, in <module>
    import lzma
  File "/usr/local/lib/python3.7/", line 27, in <module>
    from _lzma import *
ModuleNotFoundError: No module named '_lzma'

This means that the torchvision I have is broken or buggy. Can someone suggest a fix for this error.
If u need a demo code to run then please use this tutorial .

Any help would be great!!

It seems that the usage of lzma was removed in the master branch, but for 0.9.1 you could try to install it via pip or conda.

is it this command?
pip install backports.lzma

This could work. However, note that lzma should be a default Python package starting from Python 3.5, so unsure why it’s missing in your environment.
A related issue is here with more suggestions.

Ya, i have read this thread and it says that the fix is to do lazy import or something. But I don’t really understand it as _lmza should be imported by default when torchvision is imported. and as you said it is a default python package but the difference is I’m using python version 3.7.10 and you have mentioned about python3.5
Any suggestions what I should do next?

You could follow this advice, install the missing library, and then reinstall Python so that it’ll add the support. Alternatively, you could also search for other standalone Python libs (such as in your previous suggestion), but I haven’t tried to install any of them.

I tried to install that package but it says that the package is already up to date

sudo apt-get install -y liblzma-dev

Reading package lists... Done
Building dependency tree       
Reading state information... Done
liblzma-dev is already the newest version (5.1.1alpha+20120614-2ubuntu2).
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

So it wasn’t missing in the first place…

So there might a issue in torchvision.

The thread here says that torchvision works fine with version 0.7.0

do u recommend downgrading the version? (if so then please also show how to)

I don’t think it’s an issue in torchvision, as lzma should be a default Python package, and thus it would be a valid dependency.
I don’t know why your Python setup isn’t recognizing it, so you might need to create a new environment maybe.

I listed down all the packages of python using help("modules")

PIL                 _weakrefset         heapq               scipy
__future__          _xxtestfuzz         hmac                seaborn
_abc                abc                 html                secrets
_ast                absl                http                select
_asyncio            aifc                idlelib             selectors
_bisect             antigravity         imaplib             setuptools
_blake2             argparse            imghdr              shelve
_bootlocale         array               imp                 shlex
_bz2                ast                 importlib           shutil
_codecs             asynchat            inspect             signal
_codecs_cn          asyncio             io                  site
_codecs_hk          asyncore            ipaddress           six
_codecs_iso2022     atexit              itertools           smtpd
_codecs_jp          audioop             json                smtplib
_codecs_kr          base64              keyword             sndhdr
_codecs_tw          bdb                 kiwisolver          socket
_collections        binascii            lib2to3             socketserver
_collections_abc    binhex              linecache           spwd
_compat_pickle      bisect              locale              sqlite3
_compression        builtins            logging             sre_compile
_contextvars        bz2                 lzma                sre_constants
_crypt              cProfile            macpath             sre_parse
_csv                caffe2              mailbox             ssl
_ctypes             calendar            mailcap             stat
_ctypes_test        cgi                 marshal             statistics
_curses             cgitb               math                string
_curses_panel       chunk               matplotlib          stringprep
_datetime           cmath               mimetypes           struct
_dbm                cmd                 mmap                subprocess
_decimal            code                modulefinder        sunau
_dummy_thread       codecs              multiprocessing     symbol
_elementtree        codeop              netrc               symtable
_functools          collections         nis                 sys
_gdbm               colorsys            nntplib             sysconfig
_hashlib            compileall          ntpath              syslog
_heapq              concurrent          nturl2path          tabnanny
_imp                configparser        numbers             tarfile
_io                 contextlib          numpy               telnetlib
_json               contextvars         opcode              tempfile
_locale             copy                operator            termios
_lsprof             copyreg             optparse            test
_markupbase         crypt               os                  textwrap
_md5                csv                 ossaudiodev         this
_multibytecodec     ctypes              pandas              threading
_multiprocessing    curses              parser              time
_opcode             cycler              pathlib             timeit
_operator           dataclasses         pdb                 tkinter
_osx_support        datetime            pickle              token
_pickle             dateutil            pickletools         tokenize
_posixsubprocess    dbm                 pip                 torch
_py_abc             decimal             pipes               torchaudio
_pydecimal          difflib             pkg_resources       torchvision
_pyio               dis                 pkgutil             trace
_queue              distutils           platform            traceback
_random             doctest             plistlib            tracemalloc
_remote_module_non_sriptable dummy_threading     poplib              tty
_sha1               easy_install        posix               turtle
_sha256             email               posixpath           turtledemo
_sha3               encodings           pprint              types
_sha512             ensurepip           profile             typing
_signal             enum                pstats              typing_extensions
_sitebuiltins       errno               pty                 unicodedata
_socket             faulthandler        pwd                 unittest
_sqlite3            fcntl               py_compile          urllib
_sre                filecmp             pyclbr              uu
_ssl                fileinput           pydoc               uuid
_stat               fnmatch             pydoc_data          venv
_string             formatter           pyexpat             warnings
_strptime           fractions           pylab               wave
_struct             ftplib              pyparsing           weakref
_symtable           functools           pytz                webbrowser
_sysconfigdata_m_linux_x86_64-linux-gnu gc                  queue               wsgiref
_testbuffer         genericpath         quopri              xdrlib
_testcapi           get-pip             random              xml
_testimportmultiple getopt              re                  xmlrpc
_testmultiphase     getpass             readline            xxlimited
_thread             gettext             reprlib             xxsubtype
_threading_local    glob                resource            zipapp
_tracemalloc        grp                 rlcompleter         zipfile
_warnings           gzip                runpy               zipimport
_weakref            hashlib             sched               zlib

and as you can see there is no package called _lmza
So know that we have established that I don’t have this package, how should I add it ?
By now, I have tried using the following commands:

pip install backports.lzma
pip install pylzma
sudo apt-get install liblzma-dev

For the first two there is a error with a long traceback call.
while the 3rd command give this output:

The _lzma module is internal and your list shows indeed an available lzma module.
In my current environment it’s located at:


Could you check, if a direct import also fails:

import lzma

yes the import fails.

import lmza
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'lmza'

Something still seems to be strange in your Python setup.
Which Python version are you using and are you seeing the file in the pythonMAJOR.MINOR dir?

I’m using python 3.7.10.

Can you please mention where can I find the pythonMAJOR.MINOR?