2

I am attempting to read and analyze GTFS-realtime data from the NYC subway in Python. So far, I have successfully used both gtfs-realtime.proto and nyct-subway.proto to generate the proper Python classes and parsed the protobuf data into Python objects.

My problem comes when trying to access certain fields in these objects. For example, the header (feed.header) looks like this:

gtfs_realtime_version: "1.0"
incrementality: FULL_DATASET
timestamp: 1533111586
[nyct_feed_header] {
  nyct_subway_version: "1.0"
  trip_replacement_period {
    route_id: "A"
    replacement_period {
      end: 1533113386
 ...

I can access the first three attributes using dot access, but not nyct_feed_header. I suspect this is because it is part of the nyct-subway.proto extension, while the other three are part of the original.

I have found this attribute accessible in feed.header.ListFields(), but since that returns a list of (name, attribute) pairs, it is at best awkward to access.

Why aren't attributes from extensions accessible by dot access like the rest of them? Is there a better or more elegant way to access them than by using ListFields?

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • what's the rationale to use protobuf to read a GTFS feed instead of e.g. Google's transitfeed package https://github.com/google/transitfeed? AFAIK GTFS is essentially a CSV file format. – miraculixx Nov 14 '18 at 15:49
  • 1
    You're correct about GTFS - it's usually delivered as static CSVs. The question, though, is about GTFS-realtime - a related, but distinct standard for realtime transit information that uses protobuf. See https://developers.google.com/transit/gtfs-realtime/ – Tanner Thompson Nov 14 '18 at 16:01

1 Answers1

2

Extensions are accessed via the Extensions property on an object (see docs). E.g. with GTFS and the NYCT extensions:

import gtfs_realtime_pb2 as gtfs
import nyct_subway_pb2 as nyct

feed = gtfs.FeedMessage()
feed.ParseFromString(...)
feed.entity[0].trip_update.trip.Extensions[nyct.nyct_trip_descriptor].direction
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214