Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python import module prefixed with an underscore

Tags:

python

import

csv

hi today i ve encounterd some python magic i dont understand and that is

i have script where i am using csv module like

import csv 

and it throws

$> python generate_xml.py
generate_xml.py:21: SyntaxWarning: name 'parser' is assigned to before global declaration
  global parser
Traceback (most recent call last):
  File "generate_xml.py", line 2, in <module>
    import csv
  File "/usr/local/python2.5.1/lib/python2.5/csv.py", line 7, in <module>
    from _csv import Error, __version__, writer, reader, register_dialect, \
ImportError: No module named _csv

so i ve checked the csv.py file and what i saw is this

from _csv import Error, __version__, writer, reader, register_dialect, \
                 unregister_dialect, get_dialect, list_dialects, \
                 field_size_limit, \
                 QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \
                 __doc__
from _csv import Dialect as _Dialect

so i ve run python console and retyped it like

>>> _csv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_csv' is not defined
>>> from _csv import Error
>>>

my question is , what is this ? what does the _ (underscore) does in the import statement ? and why it cant find _csv module

edit updated traceback this version was installed as a second on the system, not by me

as i did some googling looks like the _is just a convention and should have not any meaning, will check module search path

like image 964
WKordos Avatar asked Jul 06 '26 13:07

WKordos


1 Answers

Some pure python modules have associated modules written in C, either for performance purposes or to handle low-level operations. _csv is such an associated module for the csv module. You can see the source here if you're interested.

The _csv module should be installed when Python is built or installed. If this is missing from a standard CPython installation - i.e. Python hasn't been built for a limited platform such as mobile or an embedded device - then it suggests that your installation has been corrupted or broken and needs to be reinstalled.

like image 189
snakecharmerb Avatar answered Jul 08 '26 04:07

snakecharmerb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!