daiyue daiyue - 2 months ago 16
Python Question

Pycharm expected type 'optional[bytes]' got 'str' instead

I am using

rsplit
to split up a path name,

rootPath = (rootPath.rsplit('/', 1)[0]).rsplit('/', 1)[0]


But Pycharm warns,


expected type
optional [bytes]
, got
str
instead


In
python doc
, it stated using
sep
as the delimiter string
.

So how to fix this?

Jim Jim
Answer

I'm guessing rootPath is a bytes object and PyCharm is warning you that the sep parameter on rsplit has to either be None or bytes. That's specified in the beginning of the Documentation on Bytes and ByteArray Operations:

The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments.

That's what Optional means, Optional[type] is either None or type which in your case is bytes.

In a simple Python REPL the message is slightly different but the gist is the same:

b'hello/world'.rsplit('/') # error bytes-like object required

Instead you need to supply a byte separator:

b'hello/world'.rsplit(b'/') 

or None in order to get it to work.