daiyue daiyue - 1 month ago 4x
Python Question

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

I am using

to split up a path name,

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

But Pycharm warns,

expected type
optional [bytes]
, got

python doc
, it stated using
as the delimiter string

So how to fix this?

Jim Jim

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:


or None in order to get it to work.