python-2.7pycharmpython-docx

Why can't I import WD_ALIGN_PARAGRAPH from docx.enum.text?


I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD_LINE_SPACING from docx.enum.text, but for some reason I can't import WD_ALIGN_PARAGRAPH.

At first, nearly non of the imports worked, but after I did
pip install python-docx
instead of
pip install docx
most of the imports worked except for WD_ALIGN_PARAGRAPH.

# works
from __future__ import print_function
import xlrd
import xlwt
import os
import subprocess
from calendar import monthrange
import datetime
from docx import Document
from datetime import datetime
from datetime import date
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Pt

# does not work
from docx.enum.text import WD_ALIGN_PARAGRAPH

I don't get any error messages but Pycharm marks the line as error: "Cannot find reference 'WD_ALIGN_PARAGRAPH' in 'text.py'".


Solution

  • You can use this instead:

    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    

    and then substitute WD_PARAGRAPH_ALIGNMENT wherever WD_ALIGN_PARAGRAPH would have appeared before.

    The reason this is happening is that the actual enum object is named WD_PARAGRAPH_ALIGNMENT, and a decorator is applied that also allows it to be referenced as WD_ALIGN_PARAGRAPH (which is a little shorter, and possibly clearer). I expect the syntax checker in PyCharm is operating on direct module attributes and doesn't pick up the alias, which is resolved by the Python parser/compiler.

    Interestingly, I expect your code would work fine either way. But to get rid of the annoying message you can use the base name.