Repository: dr-leo/pandaSDMX (python)

Issue:
Prune empty StructureMessage collections in to_pandas()
As raised by @dr-leo via e-mail:

> flows = ecb.dataflow()
>
> When I do 'to_pandas(flows)', the resulting DictLike has all the empty resources from the StructureMessage. I buy your Argument that at IM Level all supported resource types should be represented by an Attribute. However, I see no merit in representing absent resources by a key and empty dict.

Related to #79.

Pull request description:
Skip empty StructureMessage attributes in write_structuremessage
Closes #90.

Patch:
diff --git a/pandasdmx/writer.py b/pandasdmx/writer.py
index 024ee8a..b596505 100644
--- a/pandasdmx/writer.py
+++ b/pandasdmx/writer.py
@@ -158,8 +158,12 @@ def write_structuremessage(obj, include=None, **kwargs):
         attrs &= all_contents
     attrs = sorted(attrs)
 
-    result = DictLike((a, write(getattr(obj, a), **kwargs))
-                      for a in attrs)
+    result = DictLike()
+    for a in attrs:
+        dl = write(getattr(obj, a), **kwargs)
+        if len(dl):
+            # Only add non-empty elements
+            result[a] = dl
 
     return result
 


Test patch:
diff --git a/tests/test_writer.py b/tests/test_writer.py
index 5c3280c..2aa61d0 100644
--- a/tests/test_writer.py
+++ b/tests/test_writer.py
@@ -1,6 +1,5 @@
 """Tests for pandasdmx/writer.py."""
 # TODO test all possible values of Writer.write() arguments
-# - asframe
 # - attribute
 # - fromfreq
 # - parsetime
@@ -102,6 +101,20 @@ def test_write_agencyscheme():
 
     assert data['organisation_scheme']['AGENCIES']['ESTAT'] == 'Eurostat'
 
+    # to_pandas only returns keys for non-empty attributes of StructureMessage
+    # https://github.com/dr-leo/pandaSDMX/issues/90
+    assert set(data.keys()) == {'organisation_scheme'}
+
+    # Attribute access works
+    assert data.organisation_scheme.AGENCIES.ESTAT == 'Eurostat'
+
+    with pytest.raises(AttributeError):
+        data.codelist
+    with pytest.raises(AttributeError):
+        data.dataflow
+    with pytest.raises(AttributeError):
+        data.structure
+
 
 def test_write_categoryscheme():
     with specimen('insee-IPI-2010-A21-datastructure.xml') as f: