Repository: pydicom/pydicom

Issue:
UI elements raise exception when assigning None
```python
from pydicom.dataset import Dataset
ds = Dataset()
ds.SOPClassUID = ''  # OK, encoded as zero-length element
ds.SOPClassUID = None  # raises exception
```
I think it should be possible to assign None to a UI element to make the behaviour consistent with the other VR types, as the rest all allow it.

Discussion:

Patch:
diff --git a/doc/whatsnew/v1.4.0.rst b/doc/whatsnew/v1.4.0.rst
index 46b56f74a..85d361338 100644
--- a/doc/whatsnew/v1.4.0.rst
+++ b/doc/whatsnew/v1.4.0.rst
@@ -7,3 +7,6 @@ Changelog
 Fixes
 .....
 * Fixed handling of binary values in json encoding (:issue:`887`)
+* Prevent exception if assigning `None` to UI element (:issue:`894`)
+* Fixed print output for numeric multi-value elements (:issue:`892`)
+* Fixed testing PN values for truthiness (:issue:`891`)
diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py
index 56d05bee6..11e971ecc 100644
--- a/pydicom/dataelem.py
+++ b/pydicom/dataelem.py
@@ -378,7 +378,7 @@ class DataElement(object):
         elif self.VR == 'TM' and config.datetime_conversion:
             return pydicom.valuerep.TM(val)
         elif self.VR == "UI":
-            return UID(val)
+            return UID(val if val else '')
         elif not in_py2 and self.VR == "PN":
             return PersonName(val)
         # Later may need this for PersonName as for UI,
diff --git a/pydicom/multival.py b/pydicom/multival.py
index 178a1565b..e65ffffee 100644
--- a/pydicom/multival.py
+++ b/pydicom/multival.py
@@ -2,6 +2,7 @@
 """Code for multi-value data elements values,
 or any list of items that must all be the same type.
 """
+from pydicom import compat
 
 try:
     from collections.abc import MutableSequence
@@ -30,7 +31,7 @@ class MultiValue(MutableSequence):
         :param type_constructor: a constructor for the required
                            type for all list items. Could be the
                            class, or a factory function. For DICOM
-                           mult-value data elements, this will be the
+                           multi-value data elements, this will be the
                            class or type corresponding to the VR.
         :param iterable: an iterable (e.g. list, tuple) of items
                         to initialize the MultiValue list
@@ -59,8 +60,11 @@ class MultiValue(MutableSequence):
             self._list.__setitem__(i, self.type_constructor(val))
 
     def __str__(self):
-        lines = [str(x) for x in self]
-        return "['" + "', '".join(lines) + "']"
+        if not self:
+            return ''
+        lines = ["'{}'".format(x) if isinstance(x, compat.char_types)
+                 else str(x) for x in self]
+        return "[" + ", ".join(lines) + "]"
 
     __repr__ = __str__
 
diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py
index 49e857802..14ef2950e 100644
--- a/pydicom/valuerep.py
+++ b/pydicom/valuerep.py
@@ -603,8 +603,6 @@ def _encode_personname(components, encodings):
 
 class PersonName3(object):
     def __init__(self, val, encodings=None, original_string=None):
-        # handle None `val` as empty string
-        val = val or ''
         if isinstance(val, PersonName3):
             encodings = val.encodings
             self.original_string = val.original_string
@@ -614,6 +612,9 @@ class PersonName3(object):
             self.original_string = val
             self._components = None
         else:
+            # handle None `val` as empty string
+            val = val or ''
+
             # this is the decoded string - save the original string if
             # available for easier writing back
             self.original_string = original_string
@@ -774,6 +775,12 @@ class PersonName3(object):
         self._create_dict()
         return format_str % self._dict
 
+    def __bool__(self):
+        if self.original_string is None:
+            return (self._components is not None and
+                    (len(self._components) > 1 or bool(self._components[0])))
+        return bool(self.original_string)
+
 
 class PersonNameBase(object):
     """Base class for Person Name classes"""


Test patch:
diff --git a/pydicom/tests/test_dataelem.py b/pydicom/tests/test_dataelem.py
index a5011c867..1dd3df092 100644
--- a/pydicom/tests/test_dataelem.py
+++ b/pydicom/tests/test_dataelem.py
@@ -15,6 +15,7 @@ from pydicom.dataelem import (
     DataElement_from_raw,
 )
 from pydicom.dataset import Dataset
+from pydicom.multival import MultiValue
 from pydicom.tag import Tag
 from pydicom.uid import UID
 from pydicom.valuerep import DSfloat
@@ -368,6 +369,92 @@ class DataElementTests(unittest.TestCase):
         assert '[Overlay ID]' == private_data_elem.name
         assert 'UN' == private_data_elem.VR
 
+    def test_empty_text_values(self):
+        """Test that assigning an empty value behaves as expected."""
+        def check_empty_text_element(value):
+            setattr(ds, tag_name, value)
+            elem = ds[tag_name]
+            assert bool(elem.value) is False
+
+        text_vrs = {
+            'AE': 'Receiver',
+            'AS': 'PatientAge',
+            'AT': 'OffendingElement',
+            'CS': 'QualityControlSubject',
+            'DA': 'PatientBirthDate',
+            'DS': 'PatientWeight',
+            'DT': 'AcquisitionDateTime',
+            'IS': 'BeamNumber',
+            'LO': 'DataSetSubtype',
+            'LT': 'ExtendedCodeMeaning',
+            'PN': 'PatientName',
+            'SH': 'CodeValue',
+            'ST': 'InstitutionAddress',
+            'TM': 'StudyTime',
+            'UC': 'LongCodeValue',
+            'UI': 'SOPClassUID',
+            'UR': 'CodingSchemeURL',
+            'UT': 'StrainAdditionalInformation',
+        }
+        ds = Dataset()
+        # set value to new element
+        for tag_name in text_vrs.values():
+            check_empty_text_element(None)
+            del ds[tag_name]
+            check_empty_text_element(b'')
+            del ds[tag_name]
+            check_empty_text_element(u'')
+            del ds[tag_name]
+            check_empty_text_element([])
+            del ds[tag_name]
+
+        # set value to existing element
+        for tag_name in text_vrs.values():
+            check_empty_text_element(None)
+            check_empty_text_element(b'')
+            check_empty_text_element(u'')
+            check_empty_text_element([])
+            check_empty_text_element(None)
+
+    def test_empty_binary_values(self):
+        """Test that assigning an empty value behaves as expected for
+        non-text VRs."""
+        def check_empty_binary_element(value):
+            setattr(ds, tag_name, value)
+            elem = ds[tag_name]
+            assert bool(elem.value) is False
+
+        non_text_vrs = {
+            'SL': 'RationalNumeratorValue',
+            'SS': 'SelectorSSValue',
+            'UL': 'SimpleFrameList',
+            'US': 'SourceAcquisitionBeamNumber',
+            'FD': 'RealWorldValueLUTData',
+            'FL': 'VectorAccuracy',
+            'OB': 'FillPattern',
+            'OD': 'DoubleFloatPixelData',
+            'OF': 'UValueData',
+            'OL': 'TrackPointIndexList',
+            'OW': 'TrianglePointIndexList',
+            'UN': 'SelectorUNValue',
+        }
+        ds = Dataset()
+        # set value to new element
+        for tag_name in non_text_vrs.values():
+            check_empty_binary_element(None)
+            del ds[tag_name]
+            check_empty_binary_element([])
+            del ds[tag_name]
+            check_empty_binary_element(MultiValue(int, []))
+            del ds[tag_name]
+
+        # set value to existing element
+        for tag_name in non_text_vrs.values():
+            check_empty_binary_element(None)
+            check_empty_binary_element([])
+            check_empty_binary_element(MultiValue(int, []))
+            check_empty_binary_element(None)
+
 
 class RawDataElementTests(unittest.TestCase):
     def testKeyError(self):
diff --git a/pydicom/tests/test_multival.py b/pydicom/tests/test_multival.py
index 206ce08be..5f1b77395 100644
--- a/pydicom/tests/test_multival.py
+++ b/pydicom/tests/test_multival.py
@@ -1,43 +1,46 @@
 # Copyright 2008-2018 pydicom authors. See LICENSE file for details.
 """Test suite for MultiValue class"""
 
-import unittest
+import pytest
+
 from pydicom.multival import MultiValue
 from pydicom.valuerep import DS, DSfloat, DSdecimal, IS
-from pydicom import config
+from pydicom import config, compat
 from copy import deepcopy
 
 import sys
+
 python_version = sys.version_info
 
 
-class MultiValuetests(unittest.TestCase):
+class TestMultiValue(object):
     def testMultiDS(self):
         """MultiValue: Multi-valued data elements can be created........"""
         multival = MultiValue(DS, ['11.1', '22.2', '33.3'])
         for val in multival:
-            self.assertTrue(isinstance(val, (DSfloat, DSdecimal)),
-                            "Multi-value DS item not converted to DS")
+            assert isinstance(val, (DSfloat, DSdecimal))
 
     def testEmptyElements(self):
         """MultiValue: Empty number string elements are not converted..."""
         multival = MultiValue(DSfloat, ['1.0', ''])
-        self.assertEqual(1.0, multival[0])
-        self.assertEqual('', multival[1])
+        assert 1.0 == multival[0]
+        assert '' == multival[1]
         multival = MultiValue(IS, ['1', ''])
-        self.assertEqual(1, multival[0])
-        self.assertEqual('', multival[1])
+        assert 1 == multival[0]
+        assert '' == multival[1]
         multival = MultiValue(DSdecimal, ['1', ''])
-        self.assertEqual(1, multival[0])
-        self.assertEqual('', multival[1])
+        assert 1 == multival[0]
+        assert '' == multival[1]
+        multival = MultiValue(IS, [])
+        assert not multival
+        assert 0 == len(multival)
 
     def testLimits(self):
         """MultiValue: Raise error if any item outside DICOM limits...."""
         original_flag = config.enforce_valid_values
         config.enforce_valid_values = True
-        self.assertRaises(OverflowError,
-                          MultiValue,
-                          IS, [1, -2 ** 31 - 1])
+        with pytest.raises(OverflowError):
+            MultiValue(IS, [1, -2 ** 31 - 1])
         # Overflow error not raised for IS out of DICOM valid range
         config.enforce_valid_values = original_flag
 
@@ -45,44 +48,39 @@ class MultiValuetests(unittest.TestCase):
         """MultiValue: Append of item converts it to required type..."""
         multival = MultiValue(IS, [1, 5, 10])
         multival.append('5')
-        self.assertTrue(isinstance(multival[-1], IS))
-        self.assertEqual(multival[-1], 5,
-                         "Item set by append is not correct value")
+        assert isinstance(multival[-1], IS)
+        assert multival[-1] == 5
 
     def testSetIndex(self):
         """MultiValue: Setting list item converts it to required type"""
         multival = MultiValue(IS, [1, 5, 10])
         multival[1] = '7'
-        self.assertTrue(isinstance(multival[1], IS))
-        self.assertEqual(multival[1], 7,
-                         "Item set by index is not correct value")
+        assert isinstance(multival[1], IS)
+        assert multival[1] == 7
 
     def testDeleteIndex(self):
         """MultiValue: Deleting item at index behaves as expected..."""
         multival = MultiValue(IS, [1, 5, 10])
         del multival[1]
-        self.assertEqual(2, len(multival))
-        self.assertEqual(multival[0], 1)
-        self.assertEqual(multival[1], 10)
+        assert 2 == len(multival)
+        assert multival[0] == 1
+        assert multival[1] == 10
 
     def testExtend(self):
         """MultiValue: Extending a list converts all to required type"""
         multival = MultiValue(IS, [1, 5, 10])
         multival.extend(['7', 42])
-        self.assertTrue(isinstance(multival[-2], IS))
-        self.assertTrue(isinstance(multival[-1], IS))
-        self.assertEqual(multival[-2], 7,
-                         "Item set by extend not correct value")
+        assert isinstance(multival[-2], IS)
+        assert isinstance(multival[-1], IS)
+        assert multival[-2], 7
 
     def testSlice(self):
         """MultiValue: Setting slice converts items to required type."""
         multival = MultiValue(IS, range(7))
         multival[2:7:2] = [4, 16, 36]
         for val in multival:
-            self.assertTrue(isinstance(val, IS),
-                            "Slice IS value not correct type")
-        self.assertEqual(multival[4], 16,
-                         "Set by slice failed for item 4 of list")
+            assert isinstance(val, IS)
+            assert multival[4] == 16
 
     def testIssue236DeepCopy(self):
         """MultiValue: deepcopy of MultiValue does not generate an error"""
@@ -97,38 +95,45 @@ class MultiValuetests(unittest.TestCase):
         """MultiValue: allow inline sort."""
         multival = MultiValue(DS, [12, 33, 5, 7, 1])
         multival.sort()
-        self.assertEqual([1, 5, 7, 12, 33], multival)
+        assert [1, 5, 7, 12, 33] == multival
         multival.sort(reverse=True)
-        self.assertEqual([33, 12, 7, 5, 1], multival)
+        assert [33, 12, 7, 5, 1] == multival
         multival.sort(key=str)
-        self.assertEqual([1, 12, 33, 5, 7], multival)
+        assert [1, 12, 33, 5, 7] == multival
 
     def test_equal(self):
         """MultiValue: test equality operator"""
         multival = MultiValue(DS, [12, 33, 5, 7, 1])
         multival2 = MultiValue(DS, [12, 33, 5, 7, 1])
         multival3 = MultiValue(DS, [33, 12, 5, 7, 1])
-        self.assertTrue(multival == multival2)
-        self.assertFalse(multival == multival3)
+        assert multival == multival2
+        assert not (multival == multival3)
         multival = MultiValue(str, ['a', 'b', 'c'])
         multival2 = MultiValue(str, ['a', 'b', 'c'])
         multival3 = MultiValue(str, ['b', 'c', 'a'])
-        self.assertTrue(multival == multival2)
-        self.assertFalse(multival == multival3)
+        assert multival == multival2
+        assert not (multival == multival3)
 
     def test_not_equal(self):
         """MultiValue: test equality operator"""
         multival = MultiValue(DS, [12, 33, 5, 7, 1])
         multival2 = MultiValue(DS, [12, 33, 5, 7, 1])
         multival3 = MultiValue(DS, [33, 12, 5, 7, 1])
-        self.assertFalse(multival != multival2)
-        self.assertTrue(multival != multival3)
+        assert not multival != multival2
+        assert multival != multival3
         multival = MultiValue(str, ['a', 'b', 'c'])
         multival2 = MultiValue(str, ['a', 'b', 'c'])
         multival3 = MultiValue(str, ['b', 'c', 'a'])
-        self.assertFalse(multival != multival2)
-        self.assertTrue(multival != multival3)
-
-
-if __name__ == "__main__":
-    unittest.main()
+        assert not (multival != multival2)
+        assert multival != multival3
+
+    def test_str_rep(self):
+        """MultiValue: test print output"""
+        multival = MultiValue(IS, [])
+        assert '' == str(multival)
+        multival = MultiValue(compat.text_type, [1, 2, 3])
+        assert "['1', '2', '3']" == str(multival)
+        multival = MultiValue(int, [1, 2, 3])
+        assert '[1, 2, 3]' == str(multival)
+        multival = MultiValue(float, [1.1, 2.2, 3.3])
+        assert '[1.1, 2.2, 3.3]' == str(multival)