Skip to content

1.4 Other Formatting Markups

Santiago Garay edited this page Jun 26, 2020 · 4 revisions

Additional formatting markup may be included at module, class or function-level docstrings. The most widely used markups are explained below.

1.4.1 List

To create a bulleted list:

  • Place an asterisk at the start of a paragraph and indent properly. For an enumerated list start a line off with a number or letter followed by a right bracket ")".
  • Multi-line items separated by an empty line is recommended.
  • A nested list (such as inside the Args section) should be surrounded by blank lines. Items should be indented four spaces from the parent list item.

Please see Lists in reStructuredText for detailed descriptions of lists in docstrings.

Example 1: Inside a function description

@classmethod
def from_missing_values(cls, is_leap_year=False):
    """Initalize an EPW object with all data missing or empty.

    Note that this classmethod is intended for workflows where one plans
    to set all of the data within the EPW object.  The EPW file written
    out from the use of this method is not simulate-abe or useful since
    all hourly data slots just possess the missing value for that data
    type. To obtain a EPW that is simulate-able in EnergyPlus, one must
    at least set the following properties:

    * location
    * dry_bulb_temperature
    * dew_point_temperature
    * relative_humidity
    * atmospheric_station_pressure
    * direct_normal_radiation
    * diffuse_horizontal_radiation
    * wind_direction
    * wind_speed
    * total_sky_cover
    * opaque_sky_cover or horizontal_infrared_radiation_intensity

    Args:
        is_leap_year: A boolean to set whether the EPW object is for a leap year.

Html

image


Example 2: With multi-line items

def validate_analysis_period(self):
    """Get a collection where the header analysis_period aligns with datetimes.

    This means that checks for five criteria will be performed:

    1)  All datetimes in the data collection are in chronological order starting
        from the analysis_period start hour to the end hour.

    2)  No duplicate datetimes exist in the data collection.

    3)  There are no datetimes that lie outside of the analysis_period time range.

    4)  There are no datetimes that do not align with the analysis_period
        timestep.

    5)  Datetimes for February 29th are excluded if is_leap_year is False on
        the analysis_period.

    Note that there is no need to run this check any time that a discontinous
    data collection has been derived from a continuous one or when the
    validated_a_period attribute of the collection is True.  Furthermore, most
    methods on this data collection will still run without a validated
    analysis_period.
    """

Html

image


Example 3: As a nested list

...
Args:
    altitude: numeric
        Altitude angle of the sun in degrees. Note that some models use
        the apparent (refraction corrected) altitude angle, and some
        models use the true (not refraction-corrected) altitude angle. See
        model descriptions to determine which type of altitude angle is
        required. Apparent altitude angles must be calculated at sea level.
    model: string, default 'kastenyoung1989'

        Available models include the following:

        *   'simple' - secant(apparent altitude angle) - this gives -inf at altitude=0
        *   'kasten1966' - See reference [1] - requires apparent sun altitude
        *   'youngirvine1967' - See reference [2] - requires true sun altitude
        *   'kastenyoung1989' - See reference [3] - requires apparent sun altitude
        *   'gueymard1993' - See reference [4] - requires apparent sun altitude
        *   'young1994' - See reference [5] - requries true sun altitude
        *   'pickering2002' - See reference [6] - requires apparent sun altitude

Returns:
...

Html

image

1.4.2 Code-block

For documents that have to show snippets of code, the .. code-block:: python directive is used followed by an indented snippet of code and separated from the surrounding paragraphs by blank lines. Two widely used python snippets inside ladybug tools libraries are Usage block and Dictionary description.

Example 1: Usage block - single line

Used generally in class and function docstrings to illustrate their use through code examples and interactive sessions.

  @classmethod
  def from_date_time_string(cls, datetime_string, leap_year=False):
      """Create Ladybug DateTime from a DateTime string.

      Args:
          datetime_string: A text string representing a DateTime
              (ie. "21 Jun 12:00")
          leap_year: Boolean to note whether the Date Time is a part of a
              leap year. Default: False.

      Usage:

      .. code-block:: python

          dt = DateTime.from_date_time_string("31 Dec 12:00")
      """

Html

image


Example 2: Usage block - multi-line

    @staticmethod
    def compute_function_aligned(funct, data_collections, data_type, unit):
        """Compute a function with a list of aligned data collections or individual values.

        Args:
            funct: A function with a single numerical value as output and one or
                more numerical values as input.
            data_collections: A list with a length equal to the number of arguments
                for the function. Items of the list can be either Data Collections
                or individual values to be used at each datetime of other collections.
            data_type: An instance of a Ladybug data type that describes the results
                of the funct.
            unit: The units of the funct results.

        Return:
            A Data Collection with the results function. If all items in this list of
            data_collections are individual values, only a single value will be returned.

        Usage:

        .. code-block:: python

            from ladybug.datacollection import HourlyContinuousCollection
            from ladybug.epw import EPW
            from ladybug.psychrometrics import humid_ratio_from_db_rh
            from ladybug.datatype.percentage import HumidityRatio

            epw_file_path = './epws/denver.epw'
            denver_epw = EPW(epw_file_path)
            pressure_at_denver = 85000
            hr_inputs = [denver_epw.dry_bulb_temperature,
                         denver_epw.relative_humidity,
                         pressure_at_denver]
            humid_ratio = HourlyContinuousCollection.compute_function_aligned(
                humid_ratio_from_db_rh, hr_inputs, HumidityRatio(), 'fraction')
            # humid_ratio will be a Data Colleciton of humidity ratios at Denver
        """

Html

image


Example 3: Dictionary description

When specifying a dictionary as a function argument it is good practice to show an example of the dictionary data structure in a code-block with the format below. Please note an issue may be triggered with Sphinx autodoc generator when a colon is placed at the end of the argument description.

    @classmethod
    def from_dict(cls, data):
        """Create a ElectricEquipment object from a dictionary.

        Note that the dictionary must be a non-abridged version for this classmethod
        to work.

        Args:
            data: A ElectricEquipment dictionary following the format below. (<- a colon
                  here will affect the html output by sphinx)

        .. code-block:: python

            {
            "type": 'ElectricEquipment',
            "name": 'Open Office Equipment',
            "watts_per_area": 5, # equipment watts per square meter of floor area
            "schedule": {}, # ScheduleRuleset/ScheduleFixedInterval dictionary
            "radiant_fraction": 0.3, # fraction of heat that is long wave radiant
            "latent_fraction": 0, # fraction of heat that is latent
            "lost_fraction": 0 # fraction of heat that is lost
            }
        """

Html

image

1.4.3 Literal block

There are multiple ways to show syntax-highlighted literal blocks in a docstring:

Example 1: Using shell directive

Using the .. code-block:: shell directive followed by an indented literal block and separated from the surrounding paragraphs by blank lines.

    ...
    This is suitable for nearly all practical purposes and the only cases
    that could yield an incorrect result are when a point is co-linear with
    two or more polygon edges along the X vector like so:

    .. code-block:: shell

         _____     _____     _____
        |  .  |___|     |___|     |
        |_________________________|

    While this method covers most fringe cases, it will not test for whether
    a point lies perfectly on the edge of the polygon so it assesses whether
    ...

Html

image

More information on code-blocks here.


Example 2: Using reST doctest blocks

Literal blocks are introduced by ending a paragraph with the special marker ::. The literal block must be indented and separated from the surrounding paragraphs by blank lines.

  """Ladybug Data Collections.

  Collections have the following inheritance structure::

                             Base
           ___________________|__________________
          |             |           |            |
        Hourly        Daily     Monthly     MonthlyPerHour
    Discontinuous
          |
        Hourly
      Continuous

  All Data Collections in this module have the ability to:
  ...

Html

image

More information on reST doctest blocks here.

1.4.4 External links

Including external links does not require any special formatting with the exception of URLs that extend beyond the maximum line length limit. A backlash('\') can be used in those cases to split the address in two lines. Note there is no indentation in the second line.(*)

Example

    @property
    def sky_temperature(self):
        """Return annual Sky Temperature as a Ladybug Data Collection.

        This value in degrees Celsius is derived from the Horizontal Infrared
        Radiation Intensity in Wh/m2. It represents the long wave radiant
        temperature of the sky
        Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference\
/climate-calculations.html#energyplus-sky-temperature-calculation
        """

Html

image

(*) Against google recommendation: https://google.github.io/styleguide/pyguide.html#32-line-length

1.4.5 Notes

When adding notes such as references using the Note section header is recommended.

Example

def zhang_huang_solar(alt, cloud_cover, relative_humidity,
                      dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
                      irr_0=1355):
    """Calculate global horizontal solar irradiance using the Zhang-Huang model.

    Note:
        [1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files
        for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2.

    Args:

Html

image

1.4.6 Inline markups

Standard reST inline markups listed below may be used inside docstrings:

  • one asterisk: *text* for emphasis (italics),
  • two asterisks: **text** for strong emphasis (boldface)
  • back quotes: ``text`` for code samples.

Note that if asterisks, quotes or backquotes appear in running text they could create a conflict with Sphinx autodoc generator and should be escaped with a backslash as shown below:

Antimatter is a material that can \'subtract\' volumes from other volumes.

Clone this wiki locally