Skip to content

Instantly share code, notes, and snippets.

@joezuntz
Last active December 31, 2015 03:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joezuntz/7929541 to your computer and use it in GitHub Desktop.
Save joezuntz/7929541 to your computer and use it in GitHub Desktop.
Example of Table subclass helper for astropy. Uses our I3Table as an example.
import astropy.io.fits
import astropy.table
import astropy.io.registry
class I3Table(astropy.table.Table):
""" Im3shape table class. Same as a standard table except it supports
attribute style column access ("table.e1") and does not try to print itself
out when repr'd interactively.
"""
def __getattr__(self, name):
cols = self.__dict__['columns']
if name in cols:
return self[name]
raise AttributeError("No property or column %s"%name)
def __repr__(self):
return "<im3shape catalog %d cols %d rows>" % (len(self.colnames), len(self))
@classmethod
def _construct_subclass_reader_wrapper(cls,function):
def new_function(*args, **kwargs):
return cls(function(*args,**kwargs))
if function.__doc__:
new_function.__doc__ = function.__doc__+"\nWrapped programmatically to return "+cls.__name__
return new_function
@classmethod
def _register_subclass_io(cls,parent_class=astropy.table.Table):
reader_registrations = []
#Look at all the existing readers and if they are
#registered for the parent class then record the name
#and function they use
for (name,parent),reader in astropy.io.registry._readers.items():
if parent_class==parent:
reader_registrations.append((name,reader))
#register all those functions for the new class too,
#except that we need to wrap the function to return an instance
#of our class instead
for (name,reader) in reader_registrations:
new_reader = cls._construct_subclass_reader_wrapper(reader)
astropy.io.registry.register_reader(name, cls, new_reader)
#Now do exactly the same for the writers, except no wrapping needed
writer_registrations = []
#Get existing
for (name,parent),writer in astropy.io.registry._writers.items():
if parent_class==parent:
writer_registrations.append((name,writer))
#register new
for (name,writer) in writer_registrations:
astropy.io.registry.register_writer(name, cls, writer)
I3Table._register_subclass_io()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment