type annotations for xpath list

DL Neil PythonList at DancesWithMice.info
Wed Apr 8 20:29:15 EDT 2020


On 9/04/20 10:02 AM, Martin Alaçam wrote:
> Hello,
> 
> I have the following descriptor:
> 
>      self._pi = None
>      @property
>      def pi(self) -> list:
>          self._pi = self._root.xpath('processing-instruction()')
>          return self._pi
> 
> Mypy says: "Incompatible return value type (got "None", expected
> "List[Any]")"
> The xpath expression always returns a list, if it doesn't find anything it
> is an empty list. I am just getting started with type hinting, would
> appreciate any help.


Out of interest, what happens if you change the function to:

	self._pi:list = self._root.xpath('processing-instruction()')

Mypy *seems* to be remembering the type from the outer namespace and 
noting that the function's use of the same name differs. (yes, you had 
probably worked-out that for yourself)


Interestingly-enough, in a recent (off-line) communication with another 
list-member, we noted similar behavior from (?) a linter or was it Black 
("the uncompromising code formatter"), and concluded that because using 
the same identifier in both 'inner' and 'outer' name-spaces can lead to 
awkward 'gotchas' in certain situations, a general advice/'rule' of: 
'don't do it' is being applied.

Perhaps there is another/a better reason that someone else will provide...


Disclaimers:
- Python typing (and thus: mypy) has a somewhat experimental approach 
and is not a required part of the language, nor even particularly 
integrated into the language, as-such.
- linters are useful to some people, particularly those which have an 
option to turn-off individual aspects which otherwise become 'nagging'.
- some find Black useful, but to me its "uncompromising" philosophy 
seems non-pythonic (IMHO) - and I won't recommend anything that thinks 
it should make decisions because I'm too stupid (see also Apple, MSFT, 
Google, ...).
- the latter assessment may be correct, but not IMHO.
-- 
Regards =dn


More information about the Python-list mailing list