lxml fails to import, with error `symbol not found in flat namespace '_xsltDocDefaultLoader'`

Question:

With the code:

from lxml.etree import HTML, XML

I get the traceback:

Traceback (most recent call last):
  File "/Users/username/code/project/lxml-test.py", line 3, in <module>
    from lxml.etree import HTML, XML
ImportError: dlopen(/Users/username/.virtualenvs/project-venv/lib/python3.11/site-packages/lxml/etree.cpython-311-darwin.so, 0x0002): 
symbol not found in flat namespace '_xsltDocDefaultLoader'

I’m on a mac m1 chip.

I installed libxml2 and libxslt via brew.

I’m running python 3.11 inside of a virtualenv.

What I’ve tried:

  • Uninstalling and re-installing lxml with pip, and tried several different versions. (4.7.1 & 4.8.0 didn’t compile. All of the 4.9.0,1,2 versions give me the above error)
  • Installing libxml2 and libxslt via brew and then reinstalling python-lxml.
  • Installing python-lxml via conda (as suggested here)

EDIT:

I posted this bug in lxml’s bug report forum, and was notified that this is a highly-duplicated bug report of Missing wheel for macos with M1 Edit

Asked By: Civilian

||

Answers:

I ran into a similar issue recently while trying to install the python-docx module within a 3.9 virtualenv on my laptop with the M1 Pro chip.

This answer helped solve my issue: Unable to install python-docx (MacOS)

Basically, you’d need to install the setuptools with pip within your virtualenv first and then try to install lxml with pip:

pip install -U setuptools

I hope this helps.

Answered By: umit1010

I solved my problem by cloning lxml, building it, and installing it via

pip install -e /path/to/lxml
Answered By: Civilian
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.