Python str子类表示一个不是真实字符串的值

I am a novice in python. Working on extending an older module. So far it had a function that returned str (output of a blocking shell command). Now I need that function to also be able to return an object so later operations can be done on it (checking output for a non-blocking shell command). So the function now returns an instance of my class which I subclassed from str for backward compatibility with older code which expects this function to return str. The problem is, however, when the returned object is passed to os.path.isdir - it always returns False, even with the string being a valid path

import os


class ShellWrap(str):

    def __new__(cls, dummy_str_value, process_handle):
        return str.__new__(cls,"")

    def __init__(self, dummy_str_value, process_handle):
        self._ph = process_handle
        self._output_str = ""

    def wait_for_output(self):
        # for simplicity just do 
        self._output_str = "/Users"

    def __str__(self):
        return self._output_str

    def __repr__(self):
        return self._output_str


>>> obj = ShellWrap("",None)
>>> obj.wait_for_output()
>>> print(obj)
... <class '__main__.ShellWrap'>
>>> print (ShellWrap.__mro__)
... <class '__main__.ShellWrap'>
   (<class '__main__.ShellWrap'>, <class 'str'>, <class 'object'>)
>>> print(type(obj._output_str))
... <class 'str'>
>>> print(obj)
... /Users
>>> print(obj._output_str)
... /Users

让我感到困惑的是:

 >>> print(os.path.isdir(obj))
... False **<<-- This one puzzles me**
print(os.path.isdir("/Users"))
... True

我试图添加PathLike继承,并实现了又一个笨拙,但没有成功:

class ShellWrap(str,PathLike):
   ....
   def __fspath__(self):
      return self._output_str

I do see, however, something strange in the debugger. When I put a watch on obj - it says it is of a class str but the value is shown by the debugger is without the quotes (unlike other 'pure' strs). Adding quotes manually to the string in the debugger - makes it work but I guess editing a string probably creates a new object, this time pure str.

我想念什么?

评论
时钟滴答响
时钟滴答响

str is the built-in string type. Dont use it for variable names.

"3.5" == str(3.5)

点赞
评论