Adding new method, with new dispatch pattern for an existing library function

I’m extending the ‘interface’ of ZipFile.Reader() so it will understand FilePathsBase.PosixPath as an argument. Is my solution properly idiomatic in Julia?

using ZipFile, FilePathsBase
ZipFile.Reader(pp::PosixPath) = ZipFile.Reader(string(pp))

typeof(archive_file_path)
PosixPath

z = ZipFile.Reader(archive_file_path)
z_by_filename = Dict( f.name => f for f in z.files)

Seems to work nicely…

Dict{String, ZipFile.ReadableFile} with 16 entries:
  "verbatim.txt"            => ZipFile.ReadableFile(name=verbatim.txt, method=D…
  "dataset/1bc719fd-c4e1-4… => ZipFile.ReadableFile(name=dataset/1bc719fd-c4e1-…
  "dataset/aae308f4-9f9c-4… => ZipFile.ReadableFile(name=dataset/aae308f4-9f9c-…
  "multimedia.txt"          => ZipFile.ReadableFile(name=multimedia.txt, method…
  "dataset/b6465deb-2071-4… => ZipFile.ReadableFile(name=dataset/b6465deb-2071-…
  "dataset/50c9509d-22c7-4… => ZipFile.ReadableFile(name=dataset/50c9509d-22c7-…

Cheers…

You’re kind of losing all advantages of having pp be a PosixPath in the first place, by converting it to a String. Under the hood, ZipFile.jl seems to just open the file directly anyway, so I’d do

ZipFile.Reader(pp::PosixPath) = ZipFile.Reader(open(pp))

instead, which dispatches to ZipFile.Reader(::IO) and saves you from creating a new String (which will allocate).

Another option would be investigating how to make ZipFile.jl more aware of FilePathsBase.jl and its AbstractPath, to make it work in general without having to define a forwarding method for each subtype of AbstractPath.

2 Likes

Now I get what you said - thanks!
Yes it seemed like an awful hack for the type-system.

Which is what the compiler was trying to tell me with : ZipFile.Reader(::IO)

MethodError: no method matching ZipFile.Reader(::PosixPath)
Closest candidates are:
  ZipFile.Reader(::AbstractString) at /home/peterg/.julia/packages/ZipFile/fdYkP/src/ZipFile.jl:117
  ZipFile.Reader(::IO) at /home/peterg/.julia/packages/ZipFile/fdYkP/src/ZipFile.jl:113
  ZipFile.Reader(::IO, ::Bool) at /home/peterg/.julia/packages/ZipFile/fdYkP/src/ZipFile.jl:103

It’s week 3 of me using Julia - so I didn’t feel quite ready to create a pull on someone’s library. But maybe I should go through the process on a local dev copy…
I’ve seen how to do it on an example, but not built anything with it…

Julia library management seems really nice…

3 Likes