Repository: pandas-dev/pandas

Issue:
value_labels fails to assign value_label_dict, leads to AttributeError
#### Code Sample, a copy-pastable example if possible

```python
def test_StataReader(stata_path):
    """
    Args:
        stata_path - path to literally any valid stata file.
    """
    # Step 1: Delay reading value labels, which is done automaticaly when
    # decoding categoricals. Otherwise this only works if we have a stata file
    # with format verison <= 108
    reader = pandas.io.stata.StataReader(stata_path,
                                         convert_categoricals=False)
    # Patch format to be <= 108
    # https://github.com/pandas-dev/pandas/blob/master/pandas/io/stata.py#L1341-L1344
    with patch.object(reader, 'format_version', 108):
        # Trigger AttributeError when _read_value_labels immediately returns without
        # assigning value_label_dict, which value_labels() expects to exist
        # https://github.com/pandas-dev/pandas/blob/master/pandas/io/stata.py#L1745
        reader.value_labels()
```

#### Problem description

An unlikely code path will lead to an AttributeError.

#### Expected Output

I thin it is reasonable to expect `value_labels()` to return either `None` or `{}` when the stata file's `format_version` is <= 108

#### Output of ``pd.show_versions()``

<details>

>>> pandas.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.1.final.0
python-bits: 64
OS: Darwin
OS-release: 17.3.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.21.0
pytest: 3.0.7
pip: 9.0.1
setuptools: 27.2.0
Cython: None
numpy: 1.13.3
scipy: None
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: 1.0.0
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:
not really sure what you are suggesting. what exactly are you trying to accomplish here?
First step is to report the bug.

Logistically it seemed smarter to prompt discussion about the issue rather than just attempt a unilateral fix.

1. Should the behavior change, or should the AttributeError be documented?
1. If the behavior should change, does the community prefer `None` or `{}` as a return value for Stata files that don't support value labels.
    * my vote is `{}`

I'll happily submit a PR for either of the proposed behavior changes, but as a pandas PR is more than simply a diff to a single .py file I wanted to determine which fix (if any) before putting the PR together.
@miker985 can you describe the issue a little more clearly? Why does the current implementation cause an issue in user code?
Right now now my code looks like this

```python
reader  = pandas.io.stata.StataReader('some file', convert_categoricals=False)
try:
    labels_dict = reader.value_labels()
except AttributeError:  # stata file too old to contain value labels
    labels_dict = {}

# do stuff with labels dict, basically assembling categorical data by hand
```

My specific use case is I am attempting to utilize pandas to load data from a DTA file and then do stuff with the labeled data. I have to set `convert_categoricals=False` because there is a fundamental mismatch between pandas categoricals and Stata's value labels (pandas requires unique category names and Stata does not).

I think that raising an `AttributeError` is inappropriate in this situation. It's being raised incidentally because `_read_value_labels` is not behaving in a way that `value_labels` is expecting, rather than to signal what is really going on (that the stata file being read doesn't have value labels because the format doesn't support it).

It's also inconsistent. Within `.read()` there's [an explicit check of the file format version to prevent this AttributeError](https://github.com/pandas-dev/pandas/blob/master/pandas/io/stata.py#L1593) but for whatever reason this check is not present in `value_labels()`
OK, if you want to make a small test that exercises this, and see if making that change breaks anything then go for it.
It should just return an empty dictionary since there are none.  <=108 is very old Stata and so I suspect that no one who has worked on this recently has any method to create dta files from Stata in a format <=108.
A little background v113 was the dta file format in Stata 8 which was designed to run on Windows NT & 98.

Resolving patch:
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -1341,12 +1341,14 @@ def _null_terminate(self, s):
                 return s
 
     def _read_value_labels(self):
-        if self.format_version <= 108:
-            # Value labels are not supported in version 108 and earlier.
-            return
         if self._value_labels_read:
             # Don't read twice
             return
+        if self.format_version <= 108:
+            # Value labels are not supported in version 108 and earlier.
+            self._value_labels_read = True
+            self.value_label_dict = dict()
+            return
 
         if self.format_version >= 117:
             self.path_or_buf.seek(self.seek_value_labels)


Test patch:
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -589,6 +589,16 @@ def test_105(self):
         df0['psch_dis'] = df0["psch_dis"].astype(np.float32)
         tm.assert_frame_equal(df.head(3), df0)
 
+    def test_value_labels_old_format(self):
+        # GH 19417
+        #
+        # Test that value_labels() returns an empty dict if the file format
+        # predates supporting value labels.
+        dpath = os.path.join(self.dirpath, 'S4_EDUC1.dta')
+        reader = StataReader(dpath)
+        assert reader.value_labels() == {}
+        reader.close()
+
     def test_date_export_formats(self):
         columns = ['tc', 'td', 'tw', 'tm', 'tq', 'th', 'ty']
         conversions = {c: c for c in columns}