For this case you may use recursion. It feels to be most natural for the case (of course if there's no special treatment in Python yet):
ARCHIVE_PATH = "path/to/archive.tar"
INNER_PATHS = [
"nested/within/archive/one.tar",
"nested/within/archive/two.tar",
# Arbitary number of these
]
def list_inner_contents(archive_path, inner_paths):
def rec(tf, rest_paths):
if not rest_paths:
return tf.getnames()
with TarFile(fileobj=tf.extractfile(rest_paths[0])) as tf2:
return rec(tf2, rest_paths[1:])
with TarFile(archive_path) as tf:
try:
return rec(tf, inner_paths)
except RuntimeError:
# We come here in case the inner_paths list is too long
# and we go too deeply in the recursion
return None